ZTWHHH commited on
Commit
31b550d
·
verified ·
1 Parent(s): e5b2293

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. openflamingo/lib/python3.10/site-packages/mypyc/doc/Makefile +20 -0
  2. openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pyc +0 -0
  3. openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rst +27 -0
  4. openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rst +46 -0
  5. openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rst +20 -0
  6. openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.py +59 -0
  7. openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.md +25 -0
  8. openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.md +552 -0
  9. openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rst +59 -0
  10. openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rst +332 -0
  11. openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rst +50 -0
  12. openflamingo/lib/python3.10/site-packages/mypyc/doc/future.md +42 -0
  13. openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rst +240 -0
  14. openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rst +62 -0
  15. openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rst +162 -0
  16. openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rst +150 -0
  17. openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rst +65 -0
  18. openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rst +206 -0
  19. openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rst +55 -0
  20. openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rst +244 -0
  21. openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rst +47 -0
  22. openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rst +59 -0
  23. openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rst +398 -0
  24. openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pyc +0 -0
  25. openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.py +503 -0
  26. openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.py +516 -0
  27. openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.py +1038 -0
  28. openflamingo/lib/python3.10/site-packages/mypyc/irbuild/__init__.py +0 -0
  29. openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.py +1457 -0
  30. openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.py +0 -0
  31. openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.so +0 -0
  32. openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.so +0 -0
  33. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.so +0 -0
  34. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.py +0 -0
  35. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pyc +0 -0
  36. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pyc +0 -0
  37. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pyc +0 -0
  38. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pyc +0 -0
  39. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pyc +0 -0
  40. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pyc +0 -0
  41. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pyc +0 -0
  42. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pyc +0 -0
  43. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pyc +0 -0
  44. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pyc +0 -0
  45. openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pyc +0 -0
  46. openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.py +109 -0
  47. openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.py +325 -0
  48. openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.so +0 -0
  49. openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.py +101 -0
  50. openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.so +0 -0
openflamingo/lib/python3.10/site-packages/mypyc/doc/Makefile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Minimal makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line, and also
5
+ # from the environment for the first two.
6
+ SPHINXOPTS ?=
7
+ SPHINXBUILD ?= sphinx-build
8
+ SOURCEDIR = .
9
+ BUILDDIR = _build
10
+
11
+ # Put it first so that "make" without argument is like "make help".
12
+ help:
13
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14
+
15
+ .PHONY: help Makefile
16
+
17
+ # Catch-all target: route all unknown targets to Sphinx using the new
18
+ # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19
+ %: Makefile
20
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pyc ADDED
Binary file (708 Bytes). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rst ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _bool-ops:
2
+
3
+ Native boolean operations
4
+ =========================
5
+
6
+ Operations on ``bool`` values that are listed here have fast,
7
+ optimized implementations.
8
+
9
+ Construction
10
+ ------------
11
+
12
+ * ``True``
13
+ * ``False``
14
+ * ``bool(obj)``
15
+
16
+ Operators
17
+ ---------
18
+
19
+ * ``b1 and b2``
20
+ * ``b1 or b2``
21
+ * ``not b``
22
+
23
+ Functions
24
+ ---------
25
+
26
+ * ``any(expr for ... in ...)``
27
+ * ``all(expr for ... in ...)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rst ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _bytes-ops:
2
+
3
+ Native bytes operations
4
+ ========================
5
+
6
+ These ``bytes`` operations have fast, optimized implementations. Other
7
+ bytes operations use generic implementations that are often slower.
8
+
9
+ Construction
10
+ ------------
11
+
12
+ * Bytes literal
13
+ * ``bytes(x: list)``
14
+
15
+ Operators
16
+ ---------
17
+
18
+ * Concatenation (``b1 + b2``)
19
+ * Indexing (``b[n]``)
20
+ * Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``)
21
+ * Comparisons (``==``, ``!=``)
22
+
23
+ .. _bytes-methods:
24
+
25
+ Methods
26
+ -------
27
+
28
+ * ``b.decode()``
29
+ * ``b.decode(encoding: str)``
30
+ * ``b.decode(encoding: str, errors: str)``
31
+ * ``b.join(x: Iterable)``
32
+
33
+ .. note::
34
+
35
+ :ref:`str.encode() <str-methods>` is also optimized.
36
+
37
+ Formatting
38
+ ----------
39
+
40
+ A subset of % formatting operations are optimized (``b"..." % (...)``).
41
+
42
+ Functions
43
+ ---------
44
+
45
+ * ``len(b: bytes)``
46
+ * ``ord(b: bytes)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rst ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _compilation-units:
2
+
3
+ Compilation units
4
+ =================
5
+
6
+ When you run mypyc to compile a set of modules, these modules form a
7
+ *compilation unit*. Mypyc will use early binding for references within
8
+ the compilation unit.
9
+
10
+ If you run mypyc multiple times to compile multiple sets of modules,
11
+ each invocation will result in a new compilation unit. References
12
+ between separate compilation units will fall back to late binding,
13
+ i.e. looking up names using Python namespace dictionaries. Also, all
14
+ calls will use the slower Python calling convention, where arguments
15
+ and the return value will be boxed (and potentially unboxed again in
16
+ the called function).
17
+
18
+ For maximal performance, minimize interactions across compilation
19
+ units. The simplest way to achieve this is to compile your entire
20
+ program as a single compilation unit.
openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # This file only contains a selection of the most common options. For a full
4
+ # list see the documentation:
5
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+
12
+ # If extensions (or modules to document with autodoc) are in another directory,
13
+ # add these directories to sys.path here. If the directory is relative to the
14
+ # documentation root, use os.path.abspath to make it absolute, like shown here.
15
+ sys.path.insert(0, os.path.abspath("../.."))
16
+
17
+ from mypy.version import __version__ as mypy_version
18
+
19
+ # -- Project information -----------------------------------------------------
20
+
21
+ project = "mypyc"
22
+ copyright = "2020-2022, mypyc team"
23
+ author = "mypyc team"
24
+
25
+ # The version info for the project you're documenting, acts as replacement for
26
+ # |version| and |release|, also used in various other places throughout the
27
+ # built documents.
28
+ #
29
+ # The short X.Y version.
30
+ version = mypy_version.split("-")[0]
31
+ # The full version, including alpha/beta/rc tags.
32
+ release = mypy_version
33
+
34
+ # -- General configuration ---------------------------------------------------
35
+
36
+ # Add any Sphinx extension module names here, as strings. They can be
37
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
38
+ # ones.
39
+ extensions: list[str] = []
40
+
41
+ # Add any paths that contain templates here, relative to this directory.
42
+ templates_path = ["_templates"]
43
+
44
+ # List of patterns, relative to source directory, that match files and
45
+ # directories to ignore when looking for source files.
46
+ # This pattern also affects html_static_path and html_extra_path.
47
+ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
48
+
49
+
50
+ # -- Options for HTML output -------------------------------------------------
51
+
52
+ # The theme to use for HTML and HTML Help pages. See the documentation for
53
+ # a list of builtin themes.
54
+ html_theme = "furo"
55
+
56
+ # Add any paths that contain custom static files (such as style sheets) here,
57
+ # relative to this directory. They are copied after the builtin static files,
58
+ # so a file named "default.css" will overwrite the builtin "default.css".
59
+ html_static_path = ["_static"]
openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Timings of CPython Operations
2
+
3
+ Here are some *very rough* approximate timings of CPython interpreter
4
+ operations:
5
+
6
+ * `f(1)` (empty function body): 70-90ns
7
+ * `f(n=1)` (empty function body): 90-110ns
8
+ * `o.x`: 30-40ns
9
+ * `o.f(1)` (empty method body): 80-160ns
10
+ * `Cls(1)` (initialize attribute in `__init__`): 290-330ns
11
+ * `x + y` (integers): 20-35ns
12
+ * `a[i]` (list) : 20-40ns
13
+ * `[i]` (also dealloc): 35-55ns
14
+ * `a.append(i)` (list, average over 5 appends): 70ns
15
+ * `d[s]` (dict, shared str key): 20ns
16
+ * `d[s] = i` (dict, shared str key): 40ns
17
+ * `isinstance(x, A)`: 100ns
18
+ * `(x, y)`: 20-35ns
19
+ * `x, y = t` (tuple expand): 10ns
20
+
21
+ Note that these results are very imprecise due to many factors, but
22
+ these should give a rough idea of the relative costs of various
23
+ operations.
24
+
25
+ Details: CPython 3.6.2, Macbook Pro 15" (Mid 2015), macOS Sierra
openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.md ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction for Mypyc Contributors
2
+
3
+ This is a short introduction aimed at anybody who is interested in
4
+ contributing to mypyc, or anybody who is curious to understand how
5
+ mypyc works internally.
6
+
7
+ ## Key Differences from Python
8
+
9
+ Code compiled using mypyc is often much faster than CPython since it
10
+ does these things differently:
11
+
12
+ * Mypyc generates C that is compiled to native code, instead of
13
+ compiling to interpreted byte code, which CPython uses. Interpreted
14
+ byte code always has some interpreter overhead, which slows things
15
+ down.
16
+
17
+ * Mypyc doesn't let you arbitrarily monkey patch classes and functions
18
+ in compiled modules. This allows *early binding* -- mypyc
19
+ statically binds calls to compiled functions, instead of going
20
+ through a namespace dictionary. Mypyc can also call methods of
21
+ compiled classes using vtables, which are more efficient than
22
+ dictionary lookups used by CPython.
23
+
24
+ * Mypyc compiles classes to C extension classes, which are generally
25
+ more efficient than normal Python classes. They use an efficient,
26
+ fixed memory representation (essentially a C struct). This lets us
27
+ use direct memory access instead of (typically) two hash table
28
+ lookups to access an attribute.
29
+
30
+ * As a result of early binding, compiled code can use C calls to call
31
+ compiled functions. Keyword arguments can be translated to
32
+ positional arguments during compilation. Thus most calls to native
33
+ functions and methods directly map to simple C calls. CPython calls
34
+ are quite expensive, since mapping of keyword arguments, `*args`,
35
+ and so on has to mostly happen at runtime.
36
+
37
+ * Compiled code has runtime type checks to ensure that runtimes types
38
+ match the declared static types. Compiled code can thus make
39
+ assumptions about the types of expressions, resulting in both faster
40
+ and smaller code, since many runtime type checks performed by the
41
+ CPython interpreter can be omitted.
42
+
43
+ * Compiled code can often use unboxed (not heap allocated)
44
+ representations for integers, booleans and tuples.
45
+
46
+ ## Supported Python Features
47
+
48
+ Mypyc supports a large subset of Python. Note that if you try to
49
+ compile something that is not supported, you may not always get a very
50
+ good error message.
51
+
52
+ Here are some major things that aren't yet supported in compiled code:
53
+
54
+ * Many dunder methods (only some work, such as `__init__` and `__eq__`)
55
+ * Monkey patching compiled functions or classes
56
+ * General multiple inheritance (a limited form is supported)
57
+ * Named tuple defined using the class-based syntax
58
+ * Defining protocols
59
+
60
+ We are generally happy to accept contributions that implement new Python
61
+ features.
62
+
63
+ ## Development Environment
64
+
65
+ First you should set up the mypy development environment as described in
66
+ the [mypy docs](https://github.com/python/mypy/blob/master/README.md).
67
+ macOS, Linux and Windows are supported.
68
+
69
+ ## Compiling and Running Programs
70
+
71
+ When working on a mypyc feature or a fix, you'll often need to run
72
+ compiled code. For example, you may want to do interactive testing or
73
+ to run benchmarks. This is also handy if you want to inspect the
74
+ generated C code (see Inspecting Generated C).
75
+
76
+ Run `mypyc` to compile a module to a C extension using your
77
+ development version of mypyc:
78
+
79
+ ```
80
+ $ mypyc program.py
81
+ ```
82
+
83
+ This will generate a C extension for `program` in the current working
84
+ directory. For example, on a Linux system the generated file may be
85
+ called `program.cpython-37m-x86_64-linux-gnu.so`.
86
+
87
+ Since C extensions can't be run as programs, use `python3 -c` to run
88
+ the compiled module as a program:
89
+
90
+ ```
91
+ $ python3 -c "import program"
92
+ ```
93
+
94
+ Note that `__name__` in `program.py` will now be `program`, not
95
+ `__main__`!
96
+
97
+ You can manually delete the C extension to get back to an interpreted
98
+ version (this example works on Linux):
99
+
100
+ ```
101
+ $ rm program.*.so
102
+ ```
103
+
104
+ Another option is to invoke mypyc through tests (see Testing below).
105
+
106
+ ## High-level Overview of Mypyc
107
+
108
+ Mypyc compiles a Python module (or a set of modules) to C, and
109
+ compiles the generated C to a Python C extension module (or
110
+ modules). You can compile only a subset of your program to C --
111
+ compiled and interpreted code can freely and transparently
112
+ interact. You can also freely use any Python libraries (including C
113
+ extensions) in compiled code.
114
+
115
+ Mypyc will only make compiled code faster. To see a significant
116
+ speedup, you must make sure that most of the time is spent in compiled
117
+ code -- and not in libraries, for example.
118
+
119
+ Mypyc has these passes:
120
+
121
+ * Type check the code using mypy and infer types for variables and
122
+ expressions. This produces a mypy AST (defined in `mypy.nodes`) and
123
+ a type map that describes the inferred types (`mypy.types.Type`) of
124
+ all expressions (as PEP 484 types).
125
+
126
+ * Translate the mypy AST into a mypyc-specific intermediate representation (IR).
127
+ * The IR is defined in `mypyc.ir` (see below for an explanation of the IR).
128
+ * Various primitive operations used in the IR are defined in `mypyc.primitives`.
129
+ * The translation to IR happens in `mypyc.irbuild`. The top-level logic is in
130
+ `mypyc.irbuild.main`.
131
+
132
+ * Insert checks for uses of potentially uninitialized variables
133
+ (`mypyc.transform.uninit`).
134
+
135
+ * Insert exception handling (`mypyc.transform.exceptions`).
136
+
137
+ * Insert explicit reference count inc/dec opcodes (`mypyc.transform.refcount`).
138
+
139
+ * Translate the IR into C (`mypyc.codegen`).
140
+
141
+ * Compile the generated C code using a C compiler (`mypyc.build`).
142
+
143
+ ## Useful Background Information
144
+
145
+ Beyond the mypy documentation, here are some things that are helpful to
146
+ know for mypyc contributors:
147
+
148
+ * Experience with C
149
+ ([The C Programming Language](https://en.wikipedia.org/wiki/The_C_Programming_Language)
150
+ is a classic book about C)
151
+ * Basic familiarity with the Python C API (see
152
+ [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.
153
+ * Basics of compilers (see the
154
+ [mypy wiki](https://github.com/python/mypy/wiki/Learning-Resources)
155
+ for some ideas)
156
+
157
+ ## Mypyc Intermediate Representation (IR)
158
+
159
+ The mypyc IR is defined in `mypyc.ir`. It covers several key concepts
160
+ that are essential to understand by all mypyc contributors:
161
+
162
+ * `mypyc.ir.ops.Op` is an Abstract Base Class for all IR
163
+ operations. These are low-level and generally map to simple
164
+ fragments of C each. Mypy expressions are translated to
165
+ linear sequences of these ops.
166
+
167
+ * `mypyc.ir.ops.BasicBlock` is a container of a sequence of ops with a
168
+ branch/goto/return at the end, and no branch/goto/return ops in the
169
+ middle. Each function is compiled to a bunch of basic blocks.
170
+
171
+ * `mypyc.ir.rtypes.RType` and its subclasses are the types used for
172
+ everything in the IR. These are lower-level and simpler than mypy or
173
+ PEP 484 types. For example, there are no general-purpose generic
174
+ types types here. Each `List[X]` type (for any `X`) is represented
175
+ by a single `list` type, for example.
176
+
177
+ * Primitive types are special RTypes of which mypyc has some special
178
+ understanding, and there are typically some specialized
179
+ ops. Examples include `int` (referred to as `int_rprimitive` in the
180
+ code) and `list` (`list_rprimitive`). Python types for which there
181
+ is no specific RType type will be represented by the catch-all
182
+ `object_rprimitive` type.
183
+
184
+ * Instances of compiled classes are generally represented using the
185
+ `RInstance` type. Classes are compiled to C extension classes and
186
+ contain vtables for fast method calls and fast attribute access.
187
+
188
+ * IR representations of functions and classes live in
189
+ `mypyc.ir.func_ir` and `mypyc.ir.class_ir`, respectively.
190
+
191
+ Look at the docstrings and comments in `mypyc.ir` for additional
192
+ information. See the test cases in
193
+ `mypyc/test-data/irbuild-basic.test` for examples of what the IR looks
194
+ like in a pretty-printed form.
195
+
196
+ ## Testing overview
197
+
198
+ Most mypyc test cases are defined in the same format (`.test`) as used
199
+ for test cases for mypy. Look at mypy developer documentation for a
200
+ general overview of how things work. Test cases live under
201
+ `mypyc/test-data/`, and you can run all mypyc tests via `pytest
202
+ -q mypyc`. If you don't make changes to code under `mypy/`, it's not
203
+ important to regularly run mypy tests during development.
204
+
205
+ You can use `python runtests.py mypyc-fast` to run a subset of mypyc
206
+ tests that covers most functionality but runs significantly quicker
207
+ than the entire test suite.
208
+
209
+ When you create a PR, we have Continuous Integration jobs set up that
210
+ compile mypy using mypyc and run the mypy test suite using the
211
+ compiled mypy. This will sometimes catch additional issues not caught
212
+ by the mypyc test suite. It's okay to not do this in your local
213
+ development environment.
214
+
215
+ We discuss writing tests in more detail later in this document.
216
+
217
+ ## Inspecting Generated IR
218
+
219
+ It's often useful to look at the generated IR when debugging issues or
220
+ when trying to understand how mypyc compiles some code. When you
221
+ compile some module by running `mypyc`, mypyc will write the
222
+ pretty-printed IR into `build/ops.txt`. This is the final IR that
223
+ includes the output from exception and reference count handling
224
+ insertion passes.
225
+
226
+ We also have tests that verify the generate IR
227
+ (`mypyc/test-data/irbuild-*.text`).
228
+
229
+ ## Type-checking Mypyc
230
+
231
+ `./runtests.py self` type checks mypy and mypyc. This is pretty slow,
232
+ however, since it's using an uncompiled mypy.
233
+
234
+ Installing a released version of mypy using `pip` (which is compiled)
235
+ and using `dmypy` (mypy daemon) is a much, much faster way to type
236
+ check mypyc during development.
237
+
238
+ ## Value Representation
239
+
240
+ Mypyc uses a tagged pointer representation for values of type `int`
241
+ (`CPyTagged`), `char` for booleans, and C structs for tuples. For most
242
+ other objects mypyc uses the CPython `PyObject *`.
243
+
244
+ Python integers that fit in 31/63 bits (depending on whether we are on
245
+ a 32-bit or 64-bit platform) are represented as C integers
246
+ (`CPyTagged`) shifted left by 1. Integers that don't fit in this
247
+ representation are represented as pointers to a `PyObject *` (this is
248
+ always a Python `int` object) with the least significant bit
249
+ set. Tagged integer operations are defined in `mypyc/lib-rt/int_ops.c`
250
+ and `mypyc/lib-rt/CPy.h`.
251
+
252
+ There are also low-level integer types, such as `int32` (see
253
+ `mypyc.ir.rtypes`), that don't use the tagged representation. These
254
+ types are not exposed to users, but they are used in generated code.
255
+
256
+ ## Overview of Generated C
257
+
258
+ Mypyc compiles a function into two functions, a native function and
259
+ a wrapper function:
260
+
261
+ * The native function takes a fixed number of C arguments with the
262
+ correct C types. It assumes that all argument have correct types.
263
+
264
+ * The wrapper function conforms to the Python C API calling convention
265
+ and takes an arbitrary set of arguments. It processes the arguments,
266
+ checks their types, unboxes values with special representations and
267
+ calls the native function. The return value from the native function
268
+ is translated back to a Python object ("boxing").
269
+
270
+ Calls to other compiled functions don't go through the Python module
271
+ namespace but directly call the target native C function. This makes
272
+ calls very fast compared to CPython.
273
+
274
+ The generated code does runtime checking so that it can assume that
275
+ values always have the declared types. Whenever accessing CPython
276
+ values which might have unexpected types we need to insert a runtime
277
+ type check operation. For example, when getting a list item we need to
278
+ insert a runtime type check (an unbox or a cast operation), since
279
+ Python lists can contain arbitrary objects.
280
+
281
+ The generated code uses various helpers defined in
282
+ `mypyc/lib-rt/CPy.h`. The implementations are in various `.c` files
283
+ under `mypyc/lib-rt`.
284
+
285
+ ## Inspecting Generated C
286
+
287
+ It's often useful to inspect the C code genenerate by mypyc to debug
288
+ issues. Mypyc stores the generated C code as `build/__native.c`.
289
+ Compiled native functions have the prefix `CPyDef_`, while wrapper
290
+ functions used for calling functions from interpreted Python code have
291
+ the `CPyPy_` prefix.
292
+
293
+ ## Other Important Limitations
294
+
295
+ All of these limitations will likely be fixed in the future:
296
+
297
+ * We don't detect stack overflows.
298
+
299
+ * We don't handle Ctrl-C in compiled code.
300
+
301
+ ## Hints for Implementing Typical Mypyc Features
302
+
303
+ This section gives an overview of where to look for and
304
+ what to do to implement specific kinds of mypyc features.
305
+
306
+ ### Testing
307
+
308
+ Our bread-and-butter testing strategy is compiling code with mypyc and
309
+ running it. There are downsides to this (kind of slow, tests a huge
310
+ number of components at once, insensitive to the particular details of
311
+ the IR), but there really is no substitute for running code. You can
312
+ also write tests that test the generated IR, however.
313
+
314
+ ### Tests that compile and run code
315
+
316
+ Test cases that compile and run code are located in
317
+ `mypyc/test-data/run*.test` and the test runner is in
318
+ `mypyc.test.test_run`. The code to compile comes after `[case
319
+ test<name>]`. The code gets saved into the file `native.py`, and it
320
+ gets compiled into the module `native`.
321
+
322
+ Each test case uses a non-compiled Python driver that imports the
323
+ `native` module and typically calls some compiled functions. Some
324
+ tests also perform assertions and print messages in the driver.
325
+
326
+ If you don't provide a driver, a default driver is used. The default
327
+ driver just calls each module-level function that is prefixed with
328
+ `test_` and reports any uncaught exceptions as failures. (Failure to
329
+ build or a segfault also count as failures.) `testStringOps` in
330
+ `mypyc/test-data/run-strings.test` is an example of a test that uses
331
+ the default driver.
332
+
333
+ You should usually use the default driver (don't include
334
+ `driver.py`). It's the simplest way to write most tests.
335
+
336
+ Here's an example test case that uses the default driver:
337
+
338
+ ```
339
+ [case testConcatenateLists]
340
+ def test_concat_lists() -> None:
341
+ assert [1, 2] + [5, 6] == [1, 2, 5, 6]
342
+
343
+ def test_concat_empty_lists() -> None:
344
+ assert [] + [] == []
345
+ ```
346
+
347
+ There is one test case, `testConcatenateLists`. It has two sub-cases,
348
+ `test_concat_lists` and `test_concat_empty_lists`. Note that you can
349
+ use the pytest -k argument to only run `testConcetanateLists`, but you
350
+ can't filter tests at the sub-case level.
351
+
352
+ It's recommended to have multiple sub-cases per test case, since each
353
+ test case has significant fixed overhead. Each test case is run in a
354
+ fresh Python subprocess.
355
+
356
+ Many of the existing test cases provide a custom driver by having
357
+ `[file driver.py]`, followed by the driver implementation. Here the
358
+ driver is not compiled, which is useful if you want to test
359
+ interactions between compiled and non-compiled code. However, many of
360
+ the tests don't have a good reason to use a custom driver -- when they
361
+ were written, the default driver wasn't available.
362
+
363
+ Test cases can also have a `[out]` section, which specifies the
364
+ expected contents of stdout the test case should produce. New test
365
+ cases should prefer assert statements to `[out]` sections.
366
+
367
+ ### IR tests
368
+
369
+ If the specifics of the generated IR of a change is important
370
+ (because, for example, you want to make sure a particular optimization
371
+ is triggering), you should add a `mypyc.irbuild` test as well. Test
372
+ cases are located in `mypyc/test-data/irbuild-*.test` and the test
373
+ driver is in `mypyc.test.test_irbuild`. IR build tests do a direct
374
+ comparison of the IR output, so try to make the test as targeted as
375
+ possible so as to capture only the important details. (Many of our
376
+ existing IR build tests do not follow this advice, unfortunately!)
377
+
378
+ If you pass the `--update-data` flag to pytest, it will automatically
379
+ update the expected output of any tests to match the actual
380
+ output. This is very useful for changing or creating IR build tests,
381
+ but make sure to carefully inspect the diff!
382
+
383
+ You may also need to add some definitions to the stubs used for
384
+ builtins during tests (`mypyc/test-data/fixtures/ir.py`). We don't use
385
+ full typeshed stubs to run tests since they would seriously slow down
386
+ tests.
387
+
388
+ ### Benchmarking
389
+
390
+ Many mypyc improvements attempt to make some operations faster. For
391
+ any such change, you should run some measurements to verify that
392
+ there actually is a measurable performance impact.
393
+
394
+ A typical benchmark would initialize some data to be operated on, and
395
+ then measure time spent in some function. In particular, you should
396
+ not measure time needed to run the entire benchmark program, as this
397
+ would include Python startup overhead and other things that aren't
398
+ relevant. In general, for microbenchmarks, you want to do as little as
399
+ possible in the timed portion. So ideally you'll just have some loops
400
+ and the code under test. Be ready to provide your benchmark in code
401
+ review so that mypyc developers can check that the benchmark is fine
402
+ (writing a good benchmark is non-trivial).
403
+
404
+ You should run a benchmark at least five times, in both original and
405
+ changed versions, ignore outliers, and report the average
406
+ runtime. Actual performance of a typical desktop or laptop computer is
407
+ quite variable, due to dynamic CPU clock frequency changes, background
408
+ processes, etc. If you observe a high variance in timings, you'll need
409
+ to run the benchmark more times. Also try closing most applications,
410
+ including web browsers.
411
+
412
+ Interleave original and changed runs. Don't run 10 runs with variant A
413
+ followed by 10 runs with variant B, but run an A run, a B run, an A
414
+ run, etc. Otherwise you risk that the CPU frequency will be different
415
+ between variants. You can also try adding a delay of 5 to 20s between
416
+ runs to avoid CPU frequency changes.
417
+
418
+ Instead of averaging over many measurements, you can try to adjust
419
+ your environment to provide more stable measurements. However, this
420
+ can be hard to do with some hardware, including many laptops. Victor
421
+ Stinner has written a series of blog posts about making measurements
422
+ stable:
423
+
424
+ * https://vstinner.github.io/journey-to-stable-benchmark-system.html
425
+ * https://vstinner.github.io/journey-to-stable-benchmark-average.html
426
+
427
+ ### Adding C Helpers
428
+
429
+ If you add an operation that compiles into a lot of C code, you may
430
+ also want to add a C helper function for the operation to make the
431
+ generated code smaller. Here is how to do this:
432
+
433
+ * Declare the operation in `mypyc/lib-rt/CPy.h`. We avoid macros, and
434
+ we generally avoid inline functions to make it easier to target
435
+ additional backends in the future.
436
+
437
+ * Consider adding a unit test for your C helper in `mypyc/lib-rt/test_capi.cc`.
438
+ We use
439
+ [Google Test](https://github.com/google/googletest) for writing
440
+ tests in C++. The framework is included in the repository under the
441
+ directory `googletest/`. The C unit tests are run as part of the
442
+ pytest test suite (`test_c_unit_test`).
443
+
444
+ ### Adding a Specialized Primitive Operation
445
+
446
+ Mypyc speeds up operations on primitive types such as `list` and `int`
447
+ by having primitive operations specialized for specific types. These
448
+ operations are declared in `mypyc.primitives` (and
449
+ `mypyc/lib-rt/CPy.h`). For example, `mypyc.primitives.list_ops`
450
+ contains primitives that target list objects.
451
+
452
+ The operation definitions are data driven: you specify the kind of
453
+ operation (such as a call to `builtins.len` or a binary addition) and
454
+ the operand types (such as `list_primitive`), and what code should be
455
+ generated for the operation. Mypyc does AST matching to find the most
456
+ suitable primitive operation automatically.
457
+
458
+ Look at the existing primitive definitions and the docstrings in
459
+ `mypyc.primitives.registry` for examples and more information.
460
+
461
+ ### Adding a New Primitive Type
462
+
463
+ Some types (typically Python Python built-in types), such as `int` and
464
+ `list`, are special cased in mypyc to generate optimized operations
465
+ specific to these types. We'll occasionally want to add additional
466
+ primitive types.
467
+
468
+ Here are some hints about how to add support for a new primitive type
469
+ (this may be incomplete):
470
+
471
+ * Decide whether the primitive type has an "unboxed" representation (a
472
+ representation that is not just `PyObject *`). For most types we'll
473
+ use a boxed representation, as it's easier to implement and more
474
+ closely matches Python semantics.
475
+
476
+ * Create a new instance of `RPrimitive` to support the primitive type
477
+ and add it to `mypyc.ir.rtypes`. Make sure all the attributes are
478
+ set correctly and also define `<foo>_rprimitive` and
479
+ `is_<foo>_rprimitive`.
480
+
481
+ * Update `mypyc.irbuild.mapper.Mapper.type_to_rtype()`.
482
+
483
+ * If the type is not unboxed, update `emit_cast` in `mypyc.codegen.emit`.
484
+
485
+ If the type is unboxed, there are some additional steps:
486
+
487
+ * Update `emit_box` in `mypyc.codegen.emit`.
488
+
489
+ * Update `emit_unbox` in `mypyc.codegen.emit`.
490
+
491
+ * Update `emit_inc_ref` and `emit_dec_ref` in `mypypc.codegen.emit`.
492
+ If the unboxed representation does not need reference counting,
493
+ these can be no-ops.
494
+
495
+ * Update `emit_error_check` in `mypyc.codegen.emit`.
496
+
497
+ * Update `emit_gc_visit` and `emit_gc_clear` in `mypyc.codegen.emit`
498
+ if the type has an unboxed representation with pointers.
499
+
500
+ The above may be enough to allow you to declare variables with the
501
+ type, pass values around, perform runtime type checks, and use generic
502
+ fallback primitive operations to perform method calls, binary
503
+ operations, and so on. You likely also want to add some faster,
504
+ specialized primitive operations for the type (see Adding a
505
+ Specialized Primitive Operation above for how to do this).
506
+
507
+ Add a test case to `mypyc/test-data/run*.test` to test compilation and
508
+ running compiled code. Ideas for things to test:
509
+
510
+ * Test using the type as an argument.
511
+
512
+ * Test using the type as a return value.
513
+
514
+ * Test passing a value of the type to a function both within
515
+ compiled code and from regular Python code. Also test this
516
+ for return values.
517
+
518
+ * Test using the type as list item type. Test both getting a list item
519
+ and setting a list item.
520
+
521
+ ### Supporting More Python Syntax
522
+
523
+ Mypyc supports most Python syntax, but there are still some gaps.
524
+
525
+ Support for syntactic sugar that doesn't need additional IR operations
526
+ typically only requires changes to `mypyc.irbuild`.
527
+
528
+ Some new syntax also needs new IR primitives to be added to
529
+ `mypyc.primitives`. See `mypyc.primitives.registry` for documentation
530
+ about how to do this.
531
+
532
+ ### Other Hints
533
+
534
+ * This developer documentation is not aimed to be very complete. Much
535
+ of our documentation is in comments and docstring in the code. If
536
+ something is unclear, study the code.
537
+
538
+ * It can be useful to look through some recent PRs to get an idea of
539
+ what typical code changes, test cases, etc. look like.
540
+
541
+ * Feel free to open GitHub issues with questions if you need help when
542
+ contributing, or ask questions in existing issues. Note that we only
543
+ support contributors. Mypyc is not (yet) an end-user product. You
544
+ can also ask questions in our Gitter chat
545
+ (https://gitter.im/mypyc-dev/community).
546
+
547
+ ## Undocumented Workflows
548
+
549
+ These workflows would be useful for mypyc contributors. We should add
550
+ them to mypyc developer documentation:
551
+
552
+ * How to inspect the generated IR before some transform passes.
openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rst ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _dict-ops:
2
+
3
+ Native dict operations
4
+ ======================
5
+
6
+ These ``dict`` operations have fast, optimized implementations. Other
7
+ dictionary operations use generic implementations that are often slower.
8
+
9
+ Construction
10
+ ------------
11
+
12
+ Construct dict from keys and values:
13
+
14
+ * ``{key: value, ...}``
15
+
16
+ Construct empty dict:
17
+
18
+ * ``{}``
19
+ * ``dict()``
20
+
21
+ Construct dict from another object:
22
+
23
+ * ``dict(d: dict)``
24
+ * ``dict(x: Iterable)``
25
+
26
+ Dict comprehensions:
27
+
28
+ * ``{...: ... for ... in ...}``
29
+ * ``{...: ... for ... in ... if ...}``
30
+
31
+ Operators
32
+ ---------
33
+
34
+ * ``d[key]``
35
+ * ``value in d``
36
+
37
+ Statements
38
+ ----------
39
+
40
+ * ``d[key] = value``
41
+ * ``for key in d:``
42
+
43
+ Methods
44
+ -------
45
+
46
+ * ``d.get(key)``
47
+ * ``d.get(key, default)``
48
+ * ``d.keys()``
49
+ * ``d.values()``
50
+ * ``d.items()``
51
+ * ``d.copy()``
52
+ * ``d.clear()``
53
+ * ``d1.update(d2: dict)``
54
+ * ``d.update(x: Iterable)``
55
+
56
+ Functions
57
+ ---------
58
+
59
+ * ``len(d: dict)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rst ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _differences-from-python:
2
+
3
+ Differences from Python
4
+ =======================
5
+
6
+ Mypyc aims to be sufficiently compatible with Python semantics so that
7
+ migrating code to mypyc often doesn't require major code
8
+ changes. There are various differences to enable performance gains
9
+ that you need to be aware of, however.
10
+
11
+ This section documents notable differences from Python. We discuss
12
+ many of them also elsewhere, but it's convenient to have them here in
13
+ one place.
14
+
15
+ Running compiled modules
16
+ ------------------------
17
+
18
+ You can't use ``python3 <module>.py`` or ``python3 -m <module>``
19
+ to run compiled modules. Use ``python3 -c "import <module>"`` instead,
20
+ or write a wrapper script that imports your module.
21
+
22
+ As a side effect, you can't rely on checking the ``__name__`` attribute in compiled
23
+ code, like this::
24
+
25
+ if __name__ == "__main__": # Can't be used in compiled code
26
+ main()
27
+
28
+ Type errors prevent compilation
29
+ -------------------------------
30
+
31
+ You can't compile code that generates mypy type check errors. You can
32
+ sometimes ignore these with a ``# type: ignore`` comment, but this can
33
+ result in bad code being generated, and it's considered dangerous.
34
+
35
+ .. note::
36
+
37
+ In the future, mypyc may reject ``# type: ignore`` comments that
38
+ may be unsafe.
39
+
40
+ Runtime type checking
41
+ ---------------------
42
+
43
+ Non-erased types in annotations will be type checked at runtime. For example,
44
+ consider this function::
45
+
46
+ def twice(x: int) -> int:
47
+ return x * 2
48
+
49
+ If you try to call this function with a ``float`` or ``str`` argument,
50
+ you'll get a type error on the call site, even if the call site is not
51
+ being type checked::
52
+
53
+ twice(5) # OK
54
+ twice(2.2) # TypeError
55
+ twice("blah") # TypeError
56
+
57
+ Also, values with *inferred* types will be type checked. For example,
58
+ consider a call to the stdlib function ``socket.gethostname()`` in
59
+ compiled code. This function is not compiled (no stdlib modules are
60
+ compiled with mypyc), but mypyc uses a *library stub file* to infer
61
+ the return type as ``str``. Compiled code calling ``gethostname()``
62
+ will fail with ``TypeError`` if ``gethostname()`` would return an
63
+ incompatible value, such as ``None``::
64
+
65
+ import socket
66
+
67
+ # Fail if returned value is not a str
68
+ name = socket.gethostname()
69
+
70
+ Note that ``gethostname()`` is defined like this in the stub file for
71
+ ``socket`` (in typeshed)::
72
+
73
+ def gethostname() -> str: ...
74
+
75
+ Thus mypyc verifies that library stub files and annotations in
76
+ non-compiled code match runtime values. This adds an extra layer of
77
+ type safety.
78
+
79
+ Casts such as ``cast(str, x)`` will also result in strict type
80
+ checks. Consider this example::
81
+
82
+ from typing import cast
83
+ ...
84
+ x = cast(str, y)
85
+
86
+ The last line is essentially equivalent to this Python code when compiled::
87
+
88
+ if not isinstance(y, str):
89
+ raise TypeError(...)
90
+ x = y
91
+
92
+ In interpreted mode ``cast`` does not perform a runtime type check.
93
+
94
+ Native classes
95
+ --------------
96
+
97
+ Native classes behave differently from Python classes. See
98
+ :ref:`native-classes` for the details.
99
+
100
+ Primitive types
101
+ ---------------
102
+
103
+ Some primitive types behave differently in compiled code to improve
104
+ performance.
105
+
106
+ ``int`` objects use an unboxed (non-heap-allocated) representation for small
107
+ integer values. A side effect of this is that the exact runtime type of
108
+ ``int`` values is lost. For example, consider this simple function::
109
+
110
+ def first_int(x: List[int]) -> int:
111
+ return x[0]
112
+
113
+ print(first_int([True])) # Output is 1, instead of True!
114
+
115
+ ``bool`` is a subclass of ``int``, so the above code is
116
+ valid. However, when the list value is converted to ``int``, ``True``
117
+ is converted to the corresponding ``int`` value, which is ``1``.
118
+
119
+ Note that integers still have an arbitrary precision in compiled code,
120
+ similar to normal Python integers.
121
+
122
+ Fixed-length tuples are unboxed, similar to integers. The exact type
123
+ and identity of fixed-length tuples is not preserved, and you can't
124
+ reliably use ``is`` checks to compare tuples that are used in compiled
125
+ code.
126
+
127
+ .. _early-binding:
128
+
129
+ Early binding
130
+ -------------
131
+
132
+ References to functions, types, most attributes, and methods in the
133
+ same :ref:`compilation unit <compilation-units>` use *early binding*:
134
+ the target of the reference is decided at compile time, whenever
135
+ possible. This contrasts with normal Python behavior of *late
136
+ binding*, where the target is found by a namespace lookup at
137
+ runtime. Omitting these namespace lookups improves performance, but
138
+ some Python idioms don't work without changes.
139
+
140
+ Note that non-final module-level variables still use late binding.
141
+ You may want to avoid these in very performance-critical code.
142
+
143
+ Examples of early and late binding::
144
+
145
+ from typing import Final
146
+
147
+ import lib # "lib" is not compiled
148
+
149
+ x = 0
150
+ y: Final = 1
151
+
152
+ def func() -> None:
153
+ pass
154
+
155
+ class Cls:
156
+ def __init__(self, attr: int) -> None:
157
+ self.attr = attr
158
+
159
+ def method(self) -> None:
160
+ pass
161
+
162
+ def example() -> None:
163
+ # Early binding:
164
+ var = y
165
+ func()
166
+ o = Cls()
167
+ o.x
168
+ o.method()
169
+
170
+ # Late binding:
171
+ var = x # Module-level variable
172
+ lib.func() # Accessing library that is not compiled
173
+
174
+ Pickling and copying objects
175
+ ----------------------------
176
+
177
+ Mypyc tries to enforce that instances native classes are properly
178
+ initialized by calling ``__init__`` implicitly when constructing
179
+ objects, even if objects are constructed through ``pickle``,
180
+ ``copy.copy`` or ``copy.deepcopy``, for example.
181
+
182
+ If a native class doesn't support calling ``__init__`` without arguments,
183
+ you can't pickle or copy instances of the class. Use the
184
+ ``mypy_extensions.mypyc_attr`` class decorator to override this behavior
185
+ and enable pickling through the ``serializable`` flag::
186
+
187
+ from mypy_extensions import mypyc_attr
188
+ import pickle
189
+
190
+ @mypyc_attr(serializable=True)
191
+ class Cls:
192
+ def __init__(self, n: int) -> None:
193
+ self.n = n
194
+
195
+ data = pickle.dumps(Cls(5))
196
+ obj = pickle.loads(data) # OK
197
+
198
+ Additional notes:
199
+
200
+ * All subclasses inherit the ``serializable`` flag.
201
+ * If a class has the ``allow_interpreted_subclasses`` attribute, it
202
+ implicitly supports serialization.
203
+ * Enabling serialization may slow down attribute access, since compiled
204
+ code has to be always prepared to raise ``AttributeError`` in case an
205
+ attribute is not defined at runtime.
206
+ * If you try to pickle an object without setting the ``serializable``
207
+ flag, you'll get a ``TypeError`` about missing arguments to
208
+ ``__init__``.
209
+
210
+
211
+ Monkey patching
212
+ ---------------
213
+
214
+ Since mypyc function and class definitions are immutable, you can't
215
+ perform arbitrary monkey patching, such as replacing functions or
216
+ methods with mocks in tests.
217
+
218
+ .. note::
219
+
220
+ Each compiled module has a Python namespace that is initialized to
221
+ point to compiled functions and type objects. This namespace is a
222
+ regular ``dict`` object, and it *can* be modified. However,
223
+ compiled code generally doesn't use this namespace, so any changes
224
+ will only be visible to non-compiled code.
225
+
226
+ Stack overflows
227
+ ---------------
228
+
229
+ Compiled code currently doesn't check for stack overflows. Your
230
+ program may crash in an unrecoverable fashion if you have too many
231
+ nested function calls, typically due to out-of-control recursion.
232
+
233
+ .. note::
234
+
235
+ This limitation will be fixed in the future.
236
+
237
+ Final values
238
+ ------------
239
+
240
+ Compiled code replaces a reference to an attribute declared ``Final`` with
241
+ the value of the attribute computed at compile time. This is an example of
242
+ :ref:`early binding <early-binding>`. Example::
243
+
244
+ MAX: Final = 100
245
+
246
+ def limit_to_max(x: int) -> int:
247
+ if x > MAX:
248
+ return MAX
249
+ return x
250
+
251
+ The two references to ``MAX`` don't involve any module namespace lookups,
252
+ and are equivalent to this code::
253
+
254
+ def limit_to_max(x: int) -> int:
255
+ if x > 100:
256
+ return 100
257
+ return x
258
+
259
+ When run as interpreted, the first example will execute slower due to
260
+ the extra namespace lookups. In interpreted code final attributes can
261
+ also be modified.
262
+
263
+ Unsupported features
264
+ --------------------
265
+
266
+ Some Python features are not supported by mypyc (yet). They can't be
267
+ used in compiled code, or there are some limitations. You can
268
+ partially work around some of these limitations by running your code
269
+ in interpreted mode.
270
+
271
+ Nested classes
272
+ **************
273
+
274
+ Nested classes are not supported.
275
+
276
+ Conditional functions or classes
277
+ ********************************
278
+
279
+ Function and class definitions guarded by an if-statement are not supported.
280
+
281
+ Dunder methods
282
+ **************
283
+
284
+ Native classes **cannot** use these dunders. If defined, they will not
285
+ work as expected.
286
+
287
+ * ``__del__``
288
+ * ``__index__``
289
+ * ``__getattr__``, ``__getattribute__``
290
+ * ``__setattr__``
291
+ * ``__delattr__``
292
+
293
+ Generator expressions
294
+ *********************
295
+
296
+ Generator expressions are not supported. To make it easier to compile
297
+ existing code, they are implicitly replaced with list comprehensions.
298
+ *This does not always produce the same behavior.*
299
+
300
+ To work around this limitation, you can usually use a generator
301
+ function instead. You can sometimes replace the generator expression
302
+ with an explicit list comprehension.
303
+
304
+ Descriptors
305
+ ***********
306
+
307
+ Native classes can't contain arbitrary descriptors. Properties, static
308
+ methods and class methods are supported.
309
+
310
+ Introspection
311
+ *************
312
+
313
+ Various methods of introspection may break by using mypyc. Here's an
314
+ non-exhaustive list of what won't work:
315
+
316
+ - Instance ``__annotations__`` is usually not kept
317
+ - Frames of compiled functions can't be inspected using ``inspect``
318
+ - Compiled methods aren't considered methods by ``inspect.ismethod``
319
+ - ``inspect.signature`` chokes on compiled functions
320
+
321
+ Profiling hooks and tracing
322
+ ***************************
323
+
324
+ Compiled functions don't trigger profiling and tracing hooks, such as
325
+ when using the ``profile``, ``cProfile``, or ``trace`` modules.
326
+
327
+ Debuggers
328
+ *********
329
+
330
+ You can't set breakpoints in compiled functions or step through
331
+ compiled functions using ``pdb``. Often you can debug your code in
332
+ interpreted mode instead.
openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rst ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _float-ops:
2
+
3
+ Native float operations
4
+ ========================
5
+
6
+ These ``float`` operations have fast, optimized implementations. Other
7
+ floating point operations use generic implementations that are often
8
+ slower.
9
+
10
+ Construction
11
+ ------------
12
+
13
+ * Float literal
14
+ * ``float(x: int)``
15
+ * ``float(x: i64)``
16
+ * ``float(x: i32)``
17
+ * ``float(x: i16)``
18
+ * ``float(x: u8)``
19
+ * ``float(x: str)``
20
+ * ``float(x: float)`` (no-op)
21
+
22
+ Operators
23
+ ---------
24
+
25
+ * Arithmetic (``+``, ``-``, ``*``, ``/``, ``//``, ``%``)
26
+ * Comparisons (``==``, ``!=``, ``<``, etc.)
27
+ * Augmented assignment (``x += y``, etc.)
28
+
29
+ Functions
30
+ ---------
31
+
32
+ * ``int(f)``
33
+ * ``i64(f)`` (convert to 64-bit signed integer)
34
+ * ``i32(f)`` (convert to 32-bit signed integer)
35
+ * ``i16(f)`` (convert to 16-bit signed integer)
36
+ * ``u8(f)`` (convert to 8-bit unsigned integer)
37
+ * ``abs(f)``
38
+ * ``math.sin(f)``
39
+ * ``math.cos(f)``
40
+ * ``math.tan(f)``
41
+ * ``math.sqrt(f)``
42
+ * ``math.exp(f)``
43
+ * ``math.log(f)``
44
+ * ``math.floor(f)``
45
+ * ``math.ceil(f)``
46
+ * ``math.fabs(f)``
47
+ * ``math.pow(x, y)``
48
+ * ``math.copysign(x, y)``
49
+ * ``math.isinf(f)``
50
+ * ``math.isnan(f)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/future.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Future
2
+
3
+ This document introduces some ideas for future improvements.
4
+
5
+ ## Basic Optimizations
6
+
7
+ Implement basic optimizations such as common subexpression elimination and
8
+ loop invariant code motion.
9
+
10
+ Importantly, common subexpression elimination could be used to avoid
11
+ redundant type checks.
12
+
13
+ ## Operation-specific Optimizations
14
+
15
+ Some operations or combinations of successive operations can be
16
+ replaced with more efficient operations. Examples:
17
+
18
+ * If `s` is a string, `s[i] == 'x'` doesn't need to construct the
19
+ intermediate single-character string object `s[i]` but just compare
20
+ the character value to `ord('x')`.
21
+
22
+ * `a + ':' + b` (two string concetenations) can be implemented as
23
+ single three-operand concatenation that doesn't construct an
24
+ intermediate object.
25
+
26
+ * `x in {1, 3}` can be translated into `x == 1 or x == 3` (more
27
+ generally we need to evaluate all right-hand-side items).
28
+
29
+ ## Integer Range Analysis
30
+
31
+ Implement integer range analysis. This can be used in various ways:
32
+
33
+ * Use untagged representations for some registers.
34
+ * Use faster integer arithmetic operations for operations that
35
+ only deal with short integers or that can't overflow.
36
+ * Remove redundant list and string index checks.
37
+
38
+ ## Always Defined Attributes
39
+
40
+ Somehow make it possible to enforce that attributes in a class are always
41
+ defined. This makes attribute access faster since we don't need to explicitly
42
+ check if the attribute is defined.
openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rst ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Getting started
2
+ ===============
3
+
4
+ Here you will learn some basic things you need to know to get started with mypyc.
5
+
6
+ Prerequisites
7
+ -------------
8
+
9
+ You need a Python C extension development environment. The way to set this up
10
+ depends on your operating system.
11
+
12
+ macOS
13
+ *****
14
+
15
+ Install Xcode command line tools:
16
+
17
+ .. code-block::
18
+
19
+ $ xcode-select --install
20
+
21
+ Linux
22
+ *****
23
+
24
+ You need a C compiler and CPython headers and libraries. The specifics
25
+ of how to install these varies by distribution. Here are instructions for
26
+ Ubuntu 18.04, for example:
27
+
28
+ .. code-block::
29
+
30
+ $ sudo apt install python3-dev
31
+
32
+ Windows
33
+ *******
34
+
35
+ 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)
36
+
37
+ Installation
38
+ ------------
39
+
40
+ Mypyc is shipped as part of the mypy distribution. Install mypy like
41
+ this (you need Python 3.8 or later):
42
+
43
+ .. code-block::
44
+
45
+ $ python3 -m pip install -U 'mypy[mypyc]'
46
+
47
+ On some systems you need to use this instead:
48
+
49
+ .. code-block::
50
+
51
+ $ python -m pip install -U 'mypy[mypyc]'
52
+
53
+ Example program
54
+ ---------------
55
+
56
+ Let's start with a classic micro-benchmark, recursive fibonacci. Save
57
+ this file as ``fib.py``:
58
+
59
+ .. code-block:: python
60
+
61
+ import time
62
+
63
+ def fib(n: int) -> int:
64
+ if n <= 1:
65
+ return n
66
+ else:
67
+ return fib(n - 2) + fib(n - 1)
68
+
69
+ t0 = time.time()
70
+ fib(32)
71
+ print(time.time() - t0)
72
+
73
+ Note that we gave the ``fib`` function a type annotation. Without it,
74
+ performance won't be as impressive after compilation.
75
+
76
+ .. note::
77
+
78
+ `Mypy documentation
79
+ <https://mypy.readthedocs.io/en/stable/index.html>`_ is a good
80
+ introduction if you are new to type annotations or mypy. Mypyc uses
81
+ mypy to perform type checking and type inference, so some familiarity
82
+ with mypy is very useful.
83
+
84
+ Compiling and running
85
+ ---------------------
86
+
87
+ We can run ``fib.py`` as a regular, interpreted program using CPython:
88
+
89
+ .. code-block:: console
90
+
91
+ $ python3 fib.py
92
+ 0.4125328063964844
93
+
94
+ It took about 0.41s to run on my computer.
95
+
96
+ Run ``mypyc`` to compile the program to a binary C extension:
97
+
98
+ .. code-block:: console
99
+
100
+ $ mypyc fib.py
101
+
102
+ This will generate a C extension for ``fib`` in the current working
103
+ directory. For example, on a Linux system the generated file may be
104
+ called ``fib.cpython-37m-x86_64-linux-gnu.so``.
105
+
106
+ Since C extensions can't be run as programs, use ``python3 -c`` to run
107
+ the compiled module as a program:
108
+
109
+ .. code-block:: console
110
+
111
+ $ python3 -c "import fib"
112
+ 0.04097270965576172
113
+
114
+ After compilation, the program is about 10x faster. Nice!
115
+
116
+ .. note::
117
+
118
+ ``__name__`` in ``fib.py`` would now be ``"fib"``, not ``"__main__"``.
119
+
120
+ You can also pass most
121
+ `mypy command line options <https://mypy.readthedocs.io/en/stable/command_line.html>`_
122
+ to ``mypyc``.
123
+
124
+ Deleting compiled binary
125
+ ------------------------
126
+
127
+ You can manually delete the C extension to get back to an interpreted
128
+ version (this example works on Linux):
129
+
130
+ .. code-block::
131
+
132
+ $ rm fib.*.so
133
+
134
+ Using setup.py
135
+ --------------
136
+
137
+ You can also use ``setup.py`` to compile modules using mypyc. Here is an
138
+ example ``setup.py`` file::
139
+
140
+ from setuptools import setup
141
+
142
+ from mypyc.build import mypycify
143
+
144
+ setup(
145
+ name='mylib',
146
+ packages=['mylib'],
147
+ ext_modules=mypycify([
148
+ 'mylib/__init__.py',
149
+ 'mylib/mod.py',
150
+ ]),
151
+ )
152
+
153
+ We used ``mypycify(...)`` to specify which files to compile using
154
+ mypyc. Your ``setup.py`` can include additional Python files outside
155
+ ``mypycify(...)`` that won't be compiled.
156
+
157
+ Now you can build a wheel (.whl) file for the package::
158
+
159
+ python3 setup.py bdist_wheel
160
+
161
+ The wheel is created under ``dist/``.
162
+
163
+ You can also compile the C extensions in-place, in the current directory (similar
164
+ to using ``mypyc`` to compile modules)::
165
+
166
+ python3 setup.py build_ext --inplace
167
+
168
+ You can include most `mypy command line options
169
+ <https://mypy.readthedocs.io/en/stable/command_line.html>`_ in the
170
+ list of arguments passed to ``mypycify()``. For example, here we use
171
+ the ``--disallow-untyped-defs`` flag to require that all functions
172
+ have type annotations::
173
+
174
+ ...
175
+ setup(
176
+ name='frobnicate',
177
+ packages=['frobnicate'],
178
+ ext_modules=mypycify([
179
+ '--disallow-untyped-defs', # Pass a mypy flag
180
+ 'frobnicate.py',
181
+ ]),
182
+ )
183
+
184
+ .. note:
185
+
186
+ You may be tempted to use `--check-untyped-defs
187
+ <https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-check-untyped-defs>`_
188
+ to type check functions without type annotations. Note that this
189
+ may reduce performance, due to many transitions between type-checked and unchecked
190
+ code.
191
+
192
+ Recommended workflow
193
+ --------------------
194
+
195
+ A simple way to use mypyc is to always compile your code after any
196
+ code changes, but this can get tedious, especially if you have a lot
197
+ of code. Instead, you can do most development in interpreted mode.
198
+ This development workflow has worked smoothly for developing mypy and
199
+ mypyc (often we forget that we aren't working on a vanilla Python
200
+ project):
201
+
202
+ 1. During development, use interpreted mode. This gives you a fast
203
+ edit-run cycle.
204
+
205
+ 2. Use type annotations liberally and use mypy to type check your code
206
+ during development. Mypy and tests can find most errors that would
207
+ break your compiled code, if you have good type annotation
208
+ coverage. (Running mypy is pretty quick.)
209
+
210
+ 3. After you've implemented a feature or a fix, compile your project
211
+ and run tests again, now in compiled mode. Usually nothing will
212
+ break here, assuming your type annotation coverage is good. This
213
+ can happen locally or in a Continuous Integration (CI) job. If you
214
+ have CI, compiling locally may be rarely needed.
215
+
216
+ 4. Release or deploy a compiled version. Optionally, include a
217
+ fallback interpreted version for platforms that mypyc doesn't
218
+ support.
219
+
220
+ This mypyc workflow only involves minor tweaks to a typical Python
221
+ workflow. Most of development, testing and debugging happens in
222
+ interpreted mode. Incremental mypy runs, especially when using the
223
+ mypy daemon, are very quick (often a few hundred milliseconds).
224
+
225
+ Next steps
226
+ ----------
227
+
228
+ You can sometimes get good results by just annotating your code and
229
+ compiling it. If this isn't providing meaningful performance gains, if
230
+ you have trouble getting your code to work under mypyc, or if you want
231
+ to optimize your code for maximum performance, you should read the
232
+ rest of the documentation in some detail.
233
+
234
+ Here are some specific recommendations, or you can just read the
235
+ documentation in order:
236
+
237
+ * :ref:`using-type-annotations`
238
+ * :ref:`native-classes`
239
+ * :ref:`differences-from-python`
240
+ * :ref:`performance-tips`
openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rst ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. mypyc documentation master file, created by
2
+ sphinx-quickstart on Sun Apr 5 14:01:55 2020.
3
+ You can adapt this file completely to your liking, but it should at least
4
+ contain the root `toctree` directive.
5
+
6
+ Welcome to mypyc documentation!
7
+ ===============================
8
+
9
+ Mypyc compiles Python modules to C extensions. It uses standard Python
10
+ `type hints
11
+ <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ to
12
+ generate fast code.
13
+
14
+ .. toctree::
15
+ :maxdepth: 2
16
+ :caption: First steps
17
+
18
+ introduction
19
+ getting_started
20
+
21
+ .. toctree::
22
+ :maxdepth: 2
23
+ :caption: Using mypyc
24
+
25
+ using_type_annotations
26
+ native_classes
27
+ differences_from_python
28
+ compilation_units
29
+
30
+ .. toctree::
31
+ :maxdepth: 2
32
+ :caption: Native operations reference
33
+
34
+ native_operations
35
+ int_operations
36
+ bool_operations
37
+ float_operations
38
+ str_operations
39
+ bytes_operations
40
+ list_operations
41
+ dict_operations
42
+ set_operations
43
+ tuple_operations
44
+
45
+ .. toctree::
46
+ :maxdepth: 2
47
+ :caption: Advanced topics
48
+
49
+ performance_tips_and_tricks
50
+
51
+ .. toctree::
52
+ :hidden:
53
+ :caption: Project Links
54
+
55
+ GitHub <https://github.com/python/mypy>
56
+
57
+ Indices and tables
58
+ ==================
59
+
60
+ * :ref:`genindex`
61
+ * :ref:`modindex`
62
+ * :ref:`search`
openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rst ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _int-ops:
2
+
3
+ Native integer operations
4
+ =========================
5
+
6
+ Mypyc supports these integer types:
7
+
8
+ * ``int`` (arbitrary-precision integer)
9
+ * ``i64`` (64-bit signed integer)
10
+ * ``i32`` (32-bit signed integer)
11
+ * ``i16`` (16-bit signed integer)
12
+ * ``u8`` (8-bit unsigned integer)
13
+
14
+ ``i64``, ``i32``, ``i16`` and ``u8`` are *native integer types* and
15
+ are available in the ``mypy_extensions`` module. ``int`` corresponds
16
+ to the Python ``int`` type, but uses a more efficient runtime
17
+ representation (tagged pointer). Native integer types are value types.
18
+
19
+ All integer types have optimized primitive operations, but the native
20
+ integer types are more efficient than ``int``, since they don't
21
+ require range or bounds checks.
22
+
23
+ Operations on integers that are listed here have fast, optimized
24
+ implementations. Other integer operations use generic implementations
25
+ that are generally slower. Some operations involving integers and other
26
+ types, such as list indexing, are documented elsewhere.
27
+
28
+ Construction
29
+ ------------
30
+
31
+ ``int`` type:
32
+
33
+ * Integer literal
34
+ * ``int(x: float)``
35
+ * ``int(x: i64)``
36
+ * ``int(x: i32)``
37
+ * ``int(x: i16)``
38
+ * ``int(x: u8)``
39
+ * ``int(x: str)``
40
+ * ``int(x: str, base: int)``
41
+ * ``int(x: int)`` (no-op)
42
+
43
+ ``i64`` type:
44
+
45
+ * ``i64(x: int)``
46
+ * ``i64(x: float)``
47
+ * ``i64(x: i64)`` (no-op)
48
+ * ``i64(x: i32)``
49
+ * ``i64(x: i16)``
50
+ * ``i64(x: u8)``
51
+ * ``i64(x: str)``
52
+ * ``i64(x: str, base: int)``
53
+
54
+ ``i32`` type:
55
+
56
+ * ``i32(x: int)``
57
+ * ``i32(x: float)``
58
+ * ``i32(x: i64)`` (truncate)
59
+ * ``i32(x: i32)`` (no-op)
60
+ * ``i32(x: i16)``
61
+ * ``i32(x: u8)``
62
+ * ``i32(x: str)``
63
+ * ``i32(x: str, base: int)``
64
+
65
+ ``i16`` type:
66
+
67
+ * ``i16(x: int)``
68
+ * ``i16(x: float)``
69
+ * ``i16(x: i64)`` (truncate)
70
+ * ``i16(x: i32)`` (truncate)
71
+ * ``i16(x: i16)`` (no-op)
72
+ * ``i16(x: u8)``
73
+ * ``i16(x: str)``
74
+ * ``i16(x: str, base: int)``
75
+
76
+ Conversions from ``int`` to a native integer type raise
77
+ ``OverflowError`` if the value is too large or small. Conversions from
78
+ a wider native integer type to a narrower one truncate the value and never
79
+ fail. More generally, operations between native integer types don't
80
+ check for overflow.
81
+
82
+ Implicit conversions
83
+ --------------------
84
+
85
+ ``int`` values can be implicitly converted to a native integer type,
86
+ for convenience. This means that these are equivalent::
87
+
88
+ from mypy_extensions import i64
89
+
90
+ def implicit() -> None:
91
+ # Implicit conversion of 0 (int) to i64
92
+ x: i64 = 0
93
+
94
+ def explicit() -> None:
95
+ # Explicit conversion of 0 (int) to i64
96
+ x = i64(0)
97
+
98
+ Similarly, a native integer value can be implicitly converted to an
99
+ arbitrary-precision integer. These two functions are equivalent::
100
+
101
+ def implicit(x: i64) -> int:
102
+ # Implicit conversion from i64 to int
103
+ return x
104
+
105
+ def explicit(x: i64) -> int:
106
+ # Explicit conversion from i64 to int
107
+ return int(x)
108
+
109
+ Operators
110
+ ---------
111
+
112
+ * Arithmetic (``+``, ``-``, ``*``, ``//``, ``/``, ``%``)
113
+ * Bitwise operations (``&``, ``|``, ``^``, ``<<``, ``>>``, ``~``)
114
+ * Comparisons (``==``, ``!=``, ``<``, etc.)
115
+ * Augmented assignment (``x += y``, etc.)
116
+
117
+ If one of the above native integer operations overflows or underflows
118
+ with signed operands, the behavior is undefined. Signed native integer
119
+ types should only be used if all possible values are small enough for
120
+ the type. For this reason, the arbitrary-precision ``int`` type is
121
+ recommended for signed values unless the performance of integer
122
+ operations is critical.
123
+
124
+ Operations on unsigned integers (``u8``) wrap around on overflow.
125
+
126
+ It's a compile-time error to mix different native integer types in a
127
+ binary operation such as addition. An explicit conversion is required::
128
+
129
+ from mypy_extensions import i64, i32
130
+
131
+ def add(x: i64, y: i32) -> None:
132
+ a = x + y # Error (i64 + i32)
133
+ b = x + i64(y) # OK
134
+
135
+ You can freely mix a native integer value and an arbitrary-precision
136
+ ``int`` value in an operation. The native integer type is "sticky"
137
+ and the ``int`` operand is coerced to the native integer type::
138
+
139
+ def example(x: i64, y: int) -> None:
140
+ a = x * y
141
+ # Type of "a" is "i64"
142
+ ...
143
+ b = 1 - x
144
+ # Similarly, type of "b" is "i64"
145
+
146
+ Statements
147
+ ----------
148
+
149
+ For loop over a range is compiled efficiently, if the ``range(...)`` object
150
+ is constructed in the for statement (after ``in``):
151
+
152
+ * ``for x in range(end)``
153
+ * ``for x in range(start, end)``
154
+ * ``for x in range(start, end, step)``
155
+
156
+ If one of the arguments to ``range`` in a for loop is a native integer
157
+ type, the type of the loop variable is inferred to have this native
158
+ integer type, instead of ``int``::
159
+
160
+ for x in range(i64(n)):
161
+ # Type of "x" is "i64"
162
+ ...
openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rst ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Introduction
2
+ ============
3
+
4
+ Mypyc compiles Python modules to C extensions. It uses standard Python
5
+ `type hints
6
+ <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ to
7
+ generate fast code.
8
+
9
+ The compiled language is a strict, *gradually typed* Python variant. It
10
+ restricts the use of some dynamic Python features to gain performance,
11
+ but it's mostly compatible with standard Python.
12
+
13
+ Mypyc uses `mypy <https://www.mypy-lang.org/>`_ to perform type
14
+ checking and type inference. Most type system features in the stdlib
15
+ `typing <https://docs.python.org/3/library/typing.html>`_ module are
16
+ supported.
17
+
18
+ Compiled modules can import arbitrary Python modules and third-party
19
+ libraries. You can compile anything from a single performance-critical
20
+ module to your entire codebase. You can run the modules you compile
21
+ also as normal, interpreted Python modules.
22
+
23
+ Existing code with type annotations is often **1.5x to 5x** faster
24
+ when compiled. Code tuned for mypyc can be **5x to 10x** faster.
25
+
26
+ Mypyc currently aims to speed up non-numeric code, such as server
27
+ applications. Mypyc is also used to compile itself (and mypy).
28
+
29
+ Why mypyc?
30
+ ----------
31
+
32
+ **Easy to get started.** Compiled code has the look and feel of
33
+ regular Python code. Mypyc supports familiar Python syntax and idioms.
34
+
35
+ **Expressive types.** Mypyc fully supports standard Python type hints.
36
+ Mypyc has local type inference, generics, optional types, tuple types,
37
+ union types, and more. Type hints act as machine-checked
38
+ documentation, making code not only faster but also easier to
39
+ understand and modify.
40
+
41
+ **Python ecosystem.** Mypyc runs on top of CPython, the
42
+ standard Python implementation. You can use any third-party libraries,
43
+ including C extensions, installed with pip. Mypyc uses only valid Python
44
+ syntax, so all Python editors and IDEs work perfectly.
45
+
46
+ **Fast program startup.** Mypyc uses ahead-of-time compilation, so
47
+ compilation does not slow down program startup. Slow program startup
48
+ is a common issue with JIT compilers.
49
+
50
+ **Migration path for existing code.** Existing Python code often
51
+ requires only minor changes to compile using mypyc.
52
+
53
+ **Waiting for compilation is optional.** Compiled code also runs as
54
+ normal Python code. You can use interpreted Python during development,
55
+ with familiar and fast workflows.
56
+
57
+ **Runtime type safety.** Mypyc protects you from segfaults and memory
58
+ corruption. Any unexpected runtime type safety violation is a bug in
59
+ mypyc. Runtime values are checked against type annotations. (Without
60
+ mypyc, type annotations are ignored at runtime.)
61
+
62
+ **Find errors statically.** Mypyc uses mypy for static type checking
63
+ that helps catch many bugs.
64
+
65
+ Use cases
66
+ ---------
67
+
68
+ **Fix only performance bottlenecks.** Often most time is spent in a few
69
+ Python modules or functions. Add type annotations and compile these
70
+ modules for easy performance gains.
71
+
72
+ **Compile it all.** During development you can use interpreted mode,
73
+ for a quick edit-run cycle. In releases all non-test code is compiled.
74
+ This is how mypy achieved a 4x performance improvement over interpreted
75
+ Python.
76
+
77
+ **Take advantage of existing type hints.** If you already use type
78
+ annotations in your code, adopting mypyc will be easier. You've already
79
+ done most of the work needed to use mypyc.
80
+
81
+ **Alternative to a lower-level language.** Instead of writing
82
+ performance-critical code in C, C++, Cython or Rust, you may get good
83
+ performance while staying in the comfort of Python.
84
+
85
+ **Migrate C extensions.** Maintaining C extensions is not always fun
86
+ for a Python developer. With mypyc you may get performance similar to
87
+ the original C, with the convenience of Python.
88
+
89
+ Differences from Cython
90
+ -----------------------
91
+
92
+ Mypyc targets many similar use cases as Cython. Mypyc does many things
93
+ differently, however:
94
+
95
+ * No need to use non-standard syntax, such as ``cpdef``, or extra
96
+ decorators to get good performance. Clean, normal-looking
97
+ type-annotated Python code can be fast without language extensions.
98
+ This makes it practical to compile entire codebases without a
99
+ developer productivity hit.
100
+
101
+ * Mypyc has first-class support for features in the ``typing`` module,
102
+ such as tuple types, union types and generics.
103
+
104
+ * Mypyc has powerful type inference, provided by mypy. Variable type
105
+ annotations are not needed for optimal performance.
106
+
107
+ * Mypyc fully integrates with mypy for robust and seamless static type
108
+ checking.
109
+
110
+ * Mypyc performs strict enforcement of type annotations at runtime,
111
+ resulting in better runtime type safety and easier debugging.
112
+
113
+ Unlike Cython, mypyc doesn't directly support interfacing with C libraries
114
+ or speeding up numeric code.
115
+
116
+ How does it work
117
+ ----------------
118
+
119
+ Mypyc uses several techniques to produce fast code:
120
+
121
+ * Mypyc uses *ahead-of-time compilation* to native code. This removes
122
+ CPython interpreter overhead.
123
+
124
+ * Mypyc enforces type annotations (and type comments) at runtime,
125
+ raising ``TypeError`` if runtime values don't match annotations.
126
+ Value types only need to be checked in the boundaries between
127
+ dynamic and static typing.
128
+
129
+ * Compiled code uses optimized, type-specific primitives.
130
+
131
+ * Mypyc uses *early binding* to resolve called functions and name
132
+ references at compile time. Mypyc avoids many dynamic namespace
133
+ lookups.
134
+
135
+ * Classes are compiled to *C extension classes*. They use `vtables
136
+ <https://en.wikipedia.org/wiki/Virtual_method_table>`_ for fast
137
+ method calls and attribute access.
138
+
139
+ * Mypyc treats compiled functions, classes, and attributes declared
140
+ ``Final`` as immutable.
141
+
142
+ * Mypyc has memory-efficient, unboxed representations for integers and
143
+ booleans.
144
+
145
+ Development status
146
+ ------------------
147
+
148
+ Mypyc is currently alpha software. It's only recommended for
149
+ production use cases with careful testing, and if you are willing to
150
+ contribute fixes or to work around issues you will encounter.
openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rst ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _list-ops:
2
+
3
+ Native list operations
4
+ ======================
5
+
6
+ These ``list`` operations have fast, optimized implementations. Other
7
+ list operations use generic implementations that are often slower.
8
+
9
+ Construction
10
+ ------------
11
+
12
+ Construct list with specific items:
13
+
14
+ * ``[item0, ..., itemN]``
15
+
16
+ Construct empty list:
17
+
18
+ * ``[]``
19
+ * ``list()``
20
+
21
+ Construct list from iterable:
22
+
23
+ * ``list(x: Iterable)``
24
+
25
+ List comprehensions:
26
+
27
+ * ``[... for ... in ...]``
28
+ * ``[... for ... in ... if ...]``
29
+
30
+ Operators
31
+ ---------
32
+
33
+ * ``lst[n]`` (get item by integer index)
34
+ * ``lst[n:m]``, ``lst[n:]``, ``lst[:m]``, ``lst[:]`` (slicing)
35
+ * ``lst * n``, ``n * lst``
36
+ * ``obj in lst``
37
+
38
+ Statements
39
+ ----------
40
+
41
+ Set item by integer index:
42
+
43
+ * ``lst[n] = x``
44
+
45
+ For loop over a list:
46
+
47
+ * ``for item in lst:``
48
+
49
+ Methods
50
+ -------
51
+
52
+ * ``lst.append(obj)``
53
+ * ``lst.extend(x: Iterable)``
54
+ * ``lst.insert(index, obj)``
55
+ * ``lst.pop(index=-1)``
56
+ * ``lst.remove(obj)``
57
+ * ``lst.count(obj)``
58
+ * ``lst.index(obj)``
59
+ * ``lst.reverse()``
60
+ * ``lst.sort()``
61
+
62
+ Functions
63
+ ---------
64
+
65
+ * ``len(lst: list)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rst ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _native-classes:
2
+
3
+ Native classes
4
+ ==============
5
+
6
+ Classes in compiled modules are *native classes* by default (some
7
+ exceptions are discussed below). Native classes are compiled to C
8
+ extension classes, which have some important differences from normal
9
+ Python classes. Native classes are similar in many ways to built-in
10
+ types, such as ``int``, ``str``, and ``list``.
11
+
12
+ Immutable namespaces
13
+ --------------------
14
+
15
+ The type object namespace of native classes is mostly immutable (but
16
+ class variables can be assigned to)::
17
+
18
+ class Cls:
19
+ def method1(self) -> None:
20
+ print("method1")
21
+
22
+ def method2(self) -> None:
23
+ print("method2")
24
+
25
+ Cls.method1 = Cls.method2 # Error
26
+ Cls.new_method = Cls.method2 # Error
27
+
28
+ Only attributes defined within a class definition (or in a base class)
29
+ can be assigned to (similar to using ``__slots__``)::
30
+
31
+ class Cls:
32
+ x: int
33
+
34
+ def __init__(self, y: int) -> None:
35
+ self.x = 0
36
+ self.y = y
37
+
38
+ def method(self) -> None:
39
+ self.z = "x"
40
+
41
+ o = Cls(0)
42
+ print(o.x, o.y) # OK
43
+ o.z = "y" # OK
44
+ o.extra = 3 # Error: no attribute "extra"
45
+
46
+ .. _inheritance:
47
+
48
+ Inheritance
49
+ -----------
50
+
51
+ Only single inheritance is supported (except for :ref:`traits
52
+ <trait-types>`). Most non-native classes can't be used as base
53
+ classes.
54
+
55
+ These non-native classes can be used as base classes of native
56
+ classes:
57
+
58
+ * ``object``
59
+ * ``dict`` (and ``Dict[k, v]``)
60
+ * ``BaseException``
61
+ * ``Exception``
62
+ * ``ValueError``
63
+ * ``IndexError``
64
+ * ``LookupError``
65
+ * ``UserWarning``
66
+ * ``typing.NamedTuple``
67
+ * ``enum.Enum``
68
+
69
+ By default, a non-native class can't inherit a native class, and you
70
+ can't inherit from a native class outside the compilation unit that
71
+ defines the class. You can enable these through
72
+ ``mypy_extensions.mypyc_attr``::
73
+
74
+ from mypy_extensions import mypyc_attr
75
+
76
+ @mypyc_attr(allow_interpreted_subclasses=True)
77
+ class Cls:
78
+ ...
79
+
80
+ Allowing interpreted subclasses has only minor impact on performance
81
+ of instances of the native class. Accessing methods and attributes of
82
+ a *non-native* subclass (or a subclass defined in another compilation
83
+ unit) will be slower, since it needs to use the normal Python
84
+ attribute access mechanism.
85
+
86
+ You need to install ``mypy-extensions`` to use ``@mypyc_attr``:
87
+
88
+ .. code-block:: text
89
+
90
+ pip install --upgrade mypy-extensions
91
+
92
+ Class variables
93
+ ---------------
94
+
95
+ Class variables must be explicitly declared using ``attr: ClassVar``
96
+ or ``attr: ClassVar[<type>]``. You can't assign to a class variable
97
+ through an instance. Example::
98
+
99
+ from typing import ClassVar
100
+
101
+ class Cls:
102
+ cv: ClassVar = 0
103
+
104
+ Cls.cv = 2 # OK
105
+ o = Cls()
106
+ print(o.cv) # OK (2)
107
+ o.cv = 3 # Error!
108
+
109
+ .. tip::
110
+
111
+ Constant class variables can be declared using ``typing.Final`` or
112
+ ``typing.Final[<type>]``.
113
+
114
+ Generic native classes
115
+ ----------------------
116
+
117
+ Native classes can be generic. Type variables are *erased* at runtime,
118
+ and instances don't keep track of type variable values.
119
+
120
+ Compiled code thus can't check the values of type variables when
121
+ performing runtime type checks. These checks are delayed to when
122
+ reading a value with a type variable type::
123
+
124
+ from typing import TypeVar, Generic, cast
125
+
126
+ T = TypeVar('T')
127
+
128
+ class Box(Generic[T]):
129
+ def __init__(self, item: T) -> None:
130
+ self.item = item
131
+
132
+ x = Box(1) # Box[int]
133
+ y = cast(Box[str], x) # OK (type variable value not checked)
134
+ y.item # Runtime error: item is "int", but "str" expected
135
+
136
+ Metaclasses
137
+ -----------
138
+
139
+ Most metaclasses aren't supported with native classes, since their
140
+ behavior is too dynamic. You can use these metaclasses, however:
141
+
142
+ * ``abc.ABCMeta``
143
+ * ``typing.GenericMeta`` (used by ``typing.Generic``)
144
+
145
+ .. note::
146
+
147
+ If a class definition uses an unsupported metaclass, *mypyc
148
+ compiles the class into a regular Python class*.
149
+
150
+ Class decorators
151
+ ----------------
152
+
153
+ Similar to metaclasses, most class decorators aren't supported with
154
+ native classes, as they are usually too dynamic. These class
155
+ decorators can be used with native classes, however:
156
+
157
+ * ``mypy_extensions.trait`` (for defining :ref:`trait types <trait-types>`)
158
+ * ``mypy_extensions.mypyc_attr`` (see :ref:`above <inheritance>`)
159
+ * ``dataclasses.dataclass``
160
+ * ``@attr.s(auto_attribs=True)``
161
+
162
+ Dataclasses and attrs classes have partial native support, and they aren't as
163
+ efficient as pure native classes.
164
+
165
+ .. note::
166
+
167
+ If a class definition uses an unsupported class decorator, *mypyc
168
+ compiles the class into a regular Python class*.
169
+
170
+ Deleting attributes
171
+ -------------------
172
+
173
+ By default, attributes defined in native classes can't be deleted. You
174
+ can explicitly allow certain attributes to be deleted by using
175
+ ``__deletable__``::
176
+
177
+ class Cls:
178
+ x: int = 0
179
+ y: int = 0
180
+ other: int = 0
181
+
182
+ __deletable__ = ['x', 'y'] # 'x' and 'y' can be deleted
183
+
184
+ o = Cls()
185
+ del o.x # OK
186
+ del o.y # OK
187
+ del o.other # Error
188
+
189
+ You must initialize the ``__deletable__`` attribute in the class body,
190
+ using a list or a tuple expression with only string literal items that
191
+ refer to attributes. These are not valid::
192
+
193
+ a = ['x', 'y']
194
+
195
+ class Cls:
196
+ x: int
197
+ y: int
198
+
199
+ __deletable__ = a # Error: cannot use variable 'a'
200
+
201
+ __deletable__ = ('a',) # Error: not in a class body
202
+
203
+ Other properties
204
+ ----------------
205
+
206
+ Instances of native classes don't usually have a ``__dict__`` attribute.
openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rst ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Miscellaneous native operations
2
+ ===============================
3
+
4
+ This is a list of various non-type-specific operations that have
5
+ custom native implementations. If an operation has no native
6
+ implementation, mypyc will use fallback generic implementations that
7
+ are often not as fast.
8
+
9
+ .. note::
10
+
11
+ Operations specific to various primitive types are described
12
+ in the following sections.
13
+
14
+ Operators
15
+ ---------
16
+
17
+ * ``x is y`` (this is very fast for all types)
18
+
19
+ Functions
20
+ ---------
21
+
22
+ * ``isinstance(obj, type: type)``
23
+ * ``isinstance(obj, type: tuple)``
24
+ * ``cast(<type>, obj)``
25
+ * ``type(obj)``
26
+ * ``len(obj)``
27
+ * ``abs(obj)``
28
+ * ``id(obj)``
29
+ * ``iter(obj)``
30
+ * ``next(iter: Iterator)``
31
+ * ``hash(obj)``
32
+ * ``getattr(obj, attr)``
33
+ * ``getattr(obj, attr, default)``
34
+ * ``setattr(obj, attr, value)``
35
+ * ``hasattr(obj, attr)``
36
+ * ``delattr(obj, name)``
37
+ * ``slice(start, stop, step)``
38
+ * ``globals()``
39
+
40
+ Method decorators
41
+ -----------------
42
+
43
+ * ``@property``
44
+ * ``@staticmethod``
45
+ * ``@classmethod``
46
+ * ``@abc.abstractmethod``
47
+
48
+ Statements
49
+ ----------
50
+
51
+ These variants of statements have custom implementations:
52
+
53
+ * ``for ... in seq:`` (for loop over a sequence)
54
+ * ``for ... in enumerate(...):``
55
+ * ``for ... in zip(...):``
openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rst ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _performance-tips:
2
+
3
+ Performance tips and tricks
4
+ ===========================
5
+
6
+ Performance optimization is part art, part science. Just using mypyc
7
+ in a simple manner will likely make your code faster, but squeezing
8
+ the most performance out of your code requires the use of some
9
+ techniques we'll summarize below.
10
+
11
+ Profiling
12
+ ---------
13
+
14
+ If you are speeding up existing code, understanding where time is
15
+ spent is important. Mypyc speeds up code that you compile. If most of
16
+ the time is spent elsewhere, you may come back disappointed. For
17
+ example, if you spend 40% of time outside compiled code, even if
18
+ compiled code would go 100x faster, overall performance will only be
19
+ 2.5x faster.
20
+
21
+ A simple (but often effective) approach is to record the time in
22
+ various points of program execution using ``time.time()``, and to
23
+ print out elapsed time (or to write it to a log file).
24
+
25
+ The stdlib modules ``profile`` and ``cProfile`` can provide much more
26
+ detailed data. (But these only work well with non-compiled code.)
27
+
28
+ Avoiding slow libraries
29
+ -----------------------
30
+
31
+ If profiling indicates that a lot of time is spent in the stdlib or
32
+ third-party libraries, you still have several options.
33
+
34
+ First, if most time is spent in a few library features, you can
35
+ perhaps easily reimplement them in type-annotated Python, or extract
36
+ the relevant code and annotate it. Now it may be easy to compile this
37
+ code to speed it up.
38
+
39
+ Second, you may be able to avoid the library altogether, or use an
40
+ alternative, more efficient library to achieve the same purpose.
41
+
42
+ Type annotations
43
+ ----------------
44
+
45
+ As discussed earlier, type annotations are key to major performance
46
+ gains. You should at least consider adding annotations to any
47
+ performance-critical functions and classes. It may also be helpful to
48
+ annotate code called by this code, even if it's not compiled, since
49
+ this may help mypy infer better types in the compile code. If you use
50
+ libraries, ensure they have stub files with decent type annotation
51
+ coverage. Writing a stub file is often easy, and you only need to
52
+ annotate features you use a lot.
53
+
54
+ If annotating external code or writing stubs feel too burdensome, a
55
+ simple workaround is to annotate variables explicitly. For example,
56
+ here we call ``acme.get_items()``, but it has no type annotation. We
57
+ can use an explicit type annotation for the variable to which we
58
+ assign the result::
59
+
60
+ from typing import List, Tuple
61
+ import acme
62
+
63
+ def work() -> None:
64
+ # Annotate "items" to help mypyc
65
+ items: List[Tuple[int, str]] = acme.get_items()
66
+ for item in items:
67
+ ... # Do some work here
68
+
69
+ Without the annotation on ``items``, the type would be ``Any`` (since
70
+ ``acme`` has no type annotation), resulting in slower, generic
71
+ operations being used later in the function.
72
+
73
+ Avoiding slow Python features
74
+ -----------------------------
75
+
76
+ Mypyc can optimize some features more effectively than others. Here
77
+ the difference is sometimes big -- some things only get marginally
78
+ faster at best, while others can get 10x faster, or more. Avoiding
79
+ these slow features in performance-critical parts of your code can
80
+ help a lot.
81
+
82
+ These are some of the most important things to avoid:
83
+
84
+ * Using class decorators or metaclasses in compiled code (that aren't
85
+ properly supported by mypyc)
86
+
87
+ * Heavy reliance on interpreted Python libraries (C extensions are
88
+ usually fine)
89
+
90
+ These things also tend to be relatively slow:
91
+
92
+ * Using Python classes and instances of Python classes (native classes
93
+ are much faster)
94
+
95
+ * Calling decorated functions (``@property``, ``@staticmethod``, and
96
+ ``@classmethod`` are special cased and thus fast)
97
+
98
+ * Calling nested functions
99
+
100
+ * Calling functions or methods defined in other compilation units
101
+
102
+ * Using ``*args`` or ``**kwargs``
103
+
104
+ * Using generator functions
105
+
106
+ * Using callable values (i.e. not leveraging early binding to call
107
+ functions or methods)
108
+
109
+ Nested functions can often be replaced with module-level functions or
110
+ methods of native classes.
111
+
112
+ Callable values and nested functions can sometimes be replaced with an
113
+ instance of a native class with a single method only, such as
114
+ ``call(...)``. You can derive the class from an ABC, if there are
115
+ multiple possible functions.
116
+
117
+ .. note::
118
+
119
+ Some slow features will likely get efficient implementations in the
120
+ future. You should check this section every once in a while to see
121
+ if some additional operations are fast.
122
+
123
+ Using fast native features
124
+ --------------------------
125
+
126
+ Some native operations are particularly quick relative to the
127
+ corresponding interpreted operations. Using them as much as possible
128
+ may allow you to see 10x or more in performance gains.
129
+
130
+ Some things are not much (or any) faster in compiled code, such as set
131
+ math operations. In contrast, calling a method of a native class is
132
+ much faster in compiled code.
133
+
134
+ If you are used to optimizing for CPython, you might have replaced
135
+ some class instances with dictionaries, as they can be
136
+ faster. However, in compiled code, this "optimization" would likely
137
+ slow down your code.
138
+
139
+ Similarly, caching a frequently called method in a local variable can
140
+ help in CPython, but it can slow things down in compiled code, since
141
+ the code won't use :ref:`early binding <early-binding>`::
142
+
143
+ def squares(n: int) -> List[int]:
144
+ a = []
145
+ append = a.append # Not a good idea in compiled code!
146
+ for i in range(n):
147
+ append(i * i)
148
+ return a
149
+
150
+ Here are examples of features that are fast, in no particular order
151
+ (this list is *not* exhaustive):
152
+
153
+ * Calling compiled functions directly defined in the same compilation
154
+ unit (with positional and/or keyword arguments)
155
+
156
+ * Calling methods of native classes defined in the same compilation
157
+ unit (with positional and/or keyword arguments)
158
+
159
+ * Many integer operations
160
+
161
+ * Many ``float`` operations
162
+
163
+ * Booleans
164
+
165
+ * :ref:`Native list operations <list-ops>`, such as indexing,
166
+ ``append``, and list comprehensions
167
+
168
+ * While loops
169
+
170
+ * For loops over ranges and lists, and with ``enumerate`` or ``zip``
171
+
172
+ * Reading dictionary items
173
+
174
+ * ``isinstance()`` checks against native classes and instances of
175
+ primitive types (and unions of them)
176
+
177
+ * Accessing local variables
178
+
179
+ * Accessing attributes of native classes
180
+
181
+ * Accessing final module-level attributes
182
+
183
+ * Comparing strings for equality
184
+
185
+ These features are also fast, but somewhat less so (relative to other
186
+ related operations):
187
+
188
+ * Constructing instances of native classes
189
+
190
+ * Constructing dictionaries
191
+
192
+ * Setting dictionary items
193
+
194
+ * Native :ref:`dict <dict-ops>` and :ref:`set <set-ops>` operations
195
+
196
+ * Accessing module-level variables
197
+
198
+ Generally anything documented as a native operation is fast, even if
199
+ it's not explicitly mentioned here
200
+
201
+ Adjusting garbage collection
202
+ ----------------------------
203
+
204
+ Compilation does not speed up cyclic garbage collection. If everything
205
+ else gets much faster, it's possible that garbage collection will take
206
+ a big fraction of time. You can use ``gc.set_threshold()`` to adjust
207
+ the garbage collector to run less often::
208
+
209
+ import gc
210
+
211
+ # Spend less time in gc; do this before significant computation
212
+ gc.set_threshold(150000)
213
+
214
+ ... # Actual work happens here
215
+
216
+ Fast interpreter shutdown
217
+ -------------------------
218
+
219
+ If you allocate many objects, it's possible that your program spends a
220
+ lot of time cleaning up when the Python runtime shuts down. Mypyc
221
+ won't speed up the shutdown of a Python process much.
222
+
223
+ You can call ``os._exit(code)`` to immediately terminate the Python
224
+ process, skipping normal cleanup. This can give a nice boost to a
225
+ batch process or a command-line tool.
226
+
227
+ .. note::
228
+
229
+ This can be dangerous and can lose data. You need to ensure
230
+ that all streams are flushed and everything is otherwise cleaned up
231
+ properly.
232
+
233
+ Work smarter
234
+ ------------
235
+
236
+ Usually there are many things you can do to improve performance, even
237
+ if most tweaks will yield only minor gains. The key to being effective
238
+ is to focus on things that give a large gain with a small effort.
239
+
240
+ For example, low-level optimizations, such as avoiding a nested
241
+ function, can be pointless, if you could instead avoid a metaclass --
242
+ to allow a key class to be compiled as a native class. The latter
243
+ optimization could speed up numerous method calls and attribute
244
+ accesses, just like that.
openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rst ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _set-ops:
2
+
3
+ Native set operations
4
+ ======================
5
+
6
+ These ``set`` operations have fast, optimized implementations. Other
7
+ set operations use generic implementations that are often slower.
8
+
9
+ Construction
10
+ ------------
11
+
12
+ Construct set with specific items:
13
+
14
+ * ``{item0, ..., itemN}``
15
+
16
+ Construct empty set:
17
+
18
+ * ``set()``
19
+
20
+ Construct set from iterable:
21
+
22
+ * ``set(x: Iterable)``
23
+
24
+ Set comprehensions:
25
+
26
+ * ``{... for ... in ...}``
27
+ * ``{... for ... in ... if ...}``
28
+
29
+ Operators
30
+ ---------
31
+
32
+ * ``item in s``
33
+
34
+ Methods
35
+ -------
36
+
37
+ * ``s.add(item)``
38
+ * ``s.remove(item)``
39
+ * ``s.discard(item)``
40
+ * ``s.update(x: Iterable)``
41
+ * ``s.clear()``
42
+ * ``s.pop()``
43
+
44
+ Functions
45
+ ---------
46
+
47
+ * ``len(s: set)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rst ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _str-ops:
2
+
3
+ Native string operations
4
+ ========================
5
+
6
+ These ``str`` operations have fast, optimized implementations. Other
7
+ string operations use generic implementations that are often slower.
8
+
9
+ Construction
10
+ ------------
11
+
12
+ * String literal
13
+ * ``str(x: int)``
14
+ * ``str(x: object)``
15
+
16
+ Operators
17
+ ---------
18
+
19
+ * Concatenation (``s1 + s2``)
20
+ * Indexing (``s[n]``)
21
+ * Slicing (``s[n:m]``, ``s[n:]``, ``s[:m]``)
22
+ * Comparisons (``==``, ``!=``)
23
+ * Augmented assignment (``s1 += s2``)
24
+
25
+ .. _str-methods:
26
+
27
+ Methods
28
+ -------
29
+
30
+ * ``s.encode()``
31
+ * ``s.encode(encoding: str)``
32
+ * ``s.encode(encoding: str, errors: str)``
33
+ * ``s1.endswith(s2: str)``
34
+ * ``s.join(x: Iterable)``
35
+ * ``s.replace(old: str, new: str)``
36
+ * ``s.replace(old: str, new: str, count: int)``
37
+ * ``s.split()``
38
+ * ``s.split(sep: str)``
39
+ * ``s.split(sep: str, maxsplit: int)``
40
+ * ``s1.startswith(s2: str)``
41
+
42
+ .. note::
43
+
44
+ :ref:`bytes.decode() <bytes-methods>` is also optimized.
45
+
46
+ Formatting
47
+ ----------
48
+
49
+ A subset of these common string formatting expressions are optimized:
50
+
51
+ * F-strings
52
+ * ``"...".format(...)``
53
+ * ``"..." % (...)``
54
+
55
+ Functions
56
+ ---------
57
+
58
+ * ``len(s: str)``
59
+ * ``ord(s: str)``
openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rst ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _using-type-annotations:
2
+
3
+ Using type annotations
4
+ ======================
5
+
6
+ You will get the most out of mypyc if you compile code with precise
7
+ type annotations. Not all type annotations will help performance
8
+ equally, however. Using types such as :ref:`primitive types
9
+ <primitive-types>`, :ref:`native classes <native-class-intro>`,
10
+ :ref:`union types <union-types>`, :ref:`trait types <trait-types>`,
11
+ and :ref:`tuple types <tuple-types>` as much as possible is a key to
12
+ major performance gains over CPython.
13
+
14
+ In contrast, some other types, including ``Any``, are treated as
15
+ :ref:`erased types <erased-types>`. Operations on erased types use
16
+ generic operations that work with arbitrary objects, similar to how
17
+ the CPython interpreter works. If you only use erased types, the only
18
+ notable benefits over CPython will be the removal of interpreter
19
+ overhead (from compilation) and a bit of :ref:`early binding
20
+ <early-binding>`, which will usually only give minor performance
21
+ gains.
22
+
23
+ .. _primitive-types:
24
+
25
+ Primitive types
26
+ ---------------
27
+
28
+ The following built-in types are treated as *primitive types* by
29
+ mypyc, and many operations on these types have efficient
30
+ implementations:
31
+
32
+ * ``int`` (:ref:`native operations <int-ops>`)
33
+ * ``i64`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
34
+ * ``i32`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
35
+ * ``i16`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
36
+ * ``u8`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
37
+ * ``float`` (:ref:`native operations <float-ops>`)
38
+ * ``bool`` (:ref:`native operations <bool-ops>`)
39
+ * ``str`` (:ref:`native operations <str-ops>`)
40
+ * ``List[T]`` (:ref:`native operations <list-ops>`)
41
+ * ``Dict[K, V]`` (:ref:`native operations <dict-ops>`)
42
+ * ``Set[T]`` (:ref:`native operations <set-ops>`)
43
+ * ``Tuple[T, ...]`` (variable-length tuple; :ref:`native operations <tuple-ops>`)
44
+ * ``None``
45
+
46
+ The link after each type lists all supported native, optimized
47
+ operations for the type. You can use all operations supported by
48
+ Python, but *native operations* will have custom, optimized
49
+ implementations.
50
+
51
+ Primitive containers
52
+ --------------------
53
+
54
+ Primitive container objects such as ``list`` and ``dict`` don't
55
+ maintain knowledge of the item types at runtime -- the item type is
56
+ *erased*.
57
+
58
+ This means that item types are checked when items are accessed, not
59
+ when a container is passed as an argument or assigned to another
60
+ variable. For example, here we have a runtime type error on the final
61
+ line of ``example`` (the ``Any`` type means an arbitrary, unchecked
62
+ value)::
63
+
64
+ from typing import List, Any
65
+
66
+ def example(a: List[Any]) -> None:
67
+ b: List[int] = a # No error -- items are not checked
68
+ print(b[0]) # Error here -- got str, but expected int
69
+
70
+ example(["x"])
71
+
72
+ .. _native-class-intro:
73
+
74
+ Native classes
75
+ --------------
76
+
77
+ Classes that get compiled to C extensions are called native
78
+ classes. Most common operations on instances of these classes are
79
+ optimized, including construction, attribute access and method calls.
80
+
81
+ Native class definitions look exactly like normal Python class
82
+ definitions. A class is usually native if it's in a compiled module
83
+ (though there are some exceptions).
84
+
85
+ Consider this example:
86
+
87
+ .. code-block::
88
+
89
+ class Point:
90
+ def __init__(self, x: int, y: int) -> None:
91
+ self.x = x
92
+ self.y = y
93
+
94
+ def shift(p: Point) -> Point:
95
+ return Point(p.x + 1, p.y + 1)
96
+
97
+ All operations in the above example use native operations, if the file
98
+ is compiled.
99
+
100
+ Native classes have some notable different from Python classes:
101
+
102
+ * Only attributes and methods defined in the class body or methods are
103
+ supported. If you try to assign to an undefined attribute outside
104
+ the class definition, ``AttributeError`` will be raised. This enables
105
+ an efficient memory layout and fast method calls for native classes.
106
+
107
+ * Native classes usually don't define the ``__dict__`` attribute (they
108
+ don't have an attribute dictionary). This follows from only having
109
+ a specific set of attributes.
110
+
111
+ * Native classes can't have an arbitrary metaclass or use most class
112
+ decorators.
113
+
114
+ Native classes only support single inheritance. A limited form of
115
+ multiple inheritance is supported through *trait types*. You generally
116
+ must inherit from another native class (or ``object``). By default,
117
+ you can't inherit a Python class from a native class (but there's
118
+ an :ref:`override <inheritance>` to allow that).
119
+
120
+ See :ref:`native-classes` for more details.
121
+
122
+ .. _tuple-types:
123
+
124
+ Tuple types
125
+ -----------
126
+
127
+ Fixed-length
128
+ `tuple types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#tuple-types>`_
129
+ such as ``Tuple[int, str]`` are represented
130
+ as :ref:`value types <value-and-heap-types>` when stored in variables,
131
+ passed as arguments, or returned from functions. Value types are
132
+ allocated in the low-level machine stack or in CPU registers, as
133
+ opposed to *heap types*, which are allocated dynamically from the
134
+ heap.
135
+
136
+ Like all value types, tuples will be *boxed*, i.e. converted to
137
+ corresponding heap types, when stored in Python containers, or passed
138
+ to non-native code. A boxed tuple value will be a regular Python tuple
139
+ object.
140
+
141
+ .. _union-types:
142
+
143
+ Union types
144
+ -----------
145
+
146
+ `Union types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#union-types>`_
147
+ and
148
+ `optional types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type>`_
149
+ that contain primitive types, native class types and
150
+ trait types are also efficient. If a union type has
151
+ :ref:`erased <erased-types>` items, accessing items with
152
+ non-erased types is often still quite efficient.
153
+
154
+ A value with a union types is always :ref:`boxed <value-and-heap-types>`,
155
+ even if it contains a value that also has an unboxed representation, such
156
+ as an integer or a boolean.
157
+
158
+ For example, using ``Optional[int]`` is quite efficient, but the value
159
+ will always be boxed. A plain ``int`` value will usually be faster, since
160
+ it has an unboxed representation.
161
+
162
+ .. _trait-types:
163
+
164
+ Trait types
165
+ -----------
166
+
167
+ Trait types enable a form of multiple inheritance for native classes.
168
+ A native class can inherit any number of traits. Trait types are
169
+ defined as classes using the ``mypy_extensions.trait`` decorator::
170
+
171
+ from mypy_extensions import trait
172
+
173
+ @trait
174
+ class MyTrait:
175
+ def method(self) -> None:
176
+ ...
177
+
178
+ Traits can define methods, properties and attributes. They often
179
+ define abstract methods. Traits can be generic.
180
+
181
+ If a class subclasses both a non-trait class and traits, the traits
182
+ must be placed at the end of the base class list::
183
+
184
+ class Base: ...
185
+
186
+ class Derived(Base, MyTrait, FooTrait): # OK
187
+ ...
188
+
189
+ class Derived2(MyTrait, FooTrait, Base):
190
+ # Error: traits should come last
191
+ ...
192
+
193
+ Traits have some special properties:
194
+
195
+ * You shouldn't create instances of traits (though mypyc does not
196
+ prevent it yet).
197
+
198
+ * Traits can subclass other traits or native classes, but the MRO must be
199
+ linear (just like with native classes).
200
+
201
+ * Accessing methods or attributes through a trait type is somewhat
202
+ less efficient than through a native class type, but this is much
203
+ faster than through Python class types or other
204
+ :ref:`erased types <erased-types>`.
205
+
206
+ You need to install ``mypy-extensions`` to use ``@trait``:
207
+
208
+ .. code-block:: text
209
+
210
+ pip install --upgrade mypy-extensions
211
+
212
+ .. _erased-types:
213
+
214
+ Erased types
215
+ ------------
216
+
217
+ Mypyc supports many other kinds of types as well, beyond those
218
+ described above. However, these types don't have customized
219
+ operations, and they are implemented using *type erasure*. Type
220
+ erasure means that all other types are equivalent to untyped values at
221
+ runtime, i.e. they are the equivalent of the type ``Any``. Erased
222
+ types include these:
223
+
224
+ * Python classes (including ABCs)
225
+
226
+ * Non-mypyc extension types and primitive types (including built-in
227
+ types that are not primitives)
228
+
229
+ * `Callable types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas>`_
230
+
231
+ * `Type variable types <https://mypy.readthedocs.io/en/stable/generics.html>`_
232
+
233
+ * Type `Any <https://mypy.readthedocs.io/en/stable/dynamic_typing.html>`_
234
+
235
+ * Protocol types
236
+
237
+ Using erased types can still improve performance, since they can
238
+ enable better types to be inferred for expressions that use these
239
+ types. For example, a value with type ``Callable[[], int]`` will not
240
+ allow native calls. However, the return type is a primitive type, and
241
+ we can use fast operations on the return value::
242
+
243
+ from typing import Callable
244
+
245
+ def call_and_inc(f: Callable[[], int]) -> int:
246
+ # Slow call, since f has an erased type
247
+ n = f()
248
+ # Fast increment; inferred type of n is int (primitive type)
249
+ n += 1
250
+ return n
251
+
252
+ If the type of the argument ``f`` was ``Any``, the type of ``n`` would
253
+ also be ``Any``, resulting in a generic, slower increment operation
254
+ being used.
255
+
256
+ Strict runtime type checking
257
+ ----------------------------
258
+
259
+ Compiled code ensures that any variable or expression with a
260
+ non-erased type only has compatible values at runtime. This is in
261
+ contrast with using *optional static typing*, such as by using mypy,
262
+ when type annotations are not enforced at runtime. Mypyc ensures
263
+ type safety both statically and at runtime.
264
+
265
+ ``Any`` types and erased types in general can compromise type safety,
266
+ and this is by design. Inserting strict runtime type checks for all
267
+ possible values would be too expensive and against the goal of
268
+ high performance.
269
+
270
+ .. _value-and-heap-types:
271
+
272
+ Value and heap types
273
+ --------------------
274
+
275
+ In CPython, memory for all objects is dynamically allocated on the
276
+ heap. All Python types are thus *heap types*. In compiled code, some
277
+ types are *value types* -- no object is (necessarily) allocated on the
278
+ heap. ``bool``, ``float``, ``None``, :ref:`native integer types <native-ints>`
279
+ and fixed-length tuples are value types.
280
+
281
+ ``int`` is a hybrid. For typical integer values, it is a value
282
+ type. Large enough integer values, those that require more than 63
283
+ bits (or 31 bits on 32-bit platforms) to represent, use a heap-based
284
+ representation (same as CPython).
285
+
286
+ Value types have a few differences from heap types:
287
+
288
+ * When an instance of a value type is used in a context that expects a
289
+ heap value, for example as a list item, it will transparently switch
290
+ to a heap-based representation (boxing) as needed.
291
+
292
+ * Similarly, mypyc transparently changes from a heap-based
293
+ representation to a value representation (unboxing).
294
+
295
+ * Object identity of integers, floating point values and tuples is not
296
+ preserved. You should use ``==`` instead of ``is`` if you are comparing
297
+ two integers, floats or fixed-length tuples.
298
+
299
+ * When an instance of a subclass of a value type is converted to the
300
+ base type, it is implicitly converted to an instance of the target
301
+ type. For example, a ``bool`` value assigned to a variable with an
302
+ ``int`` type will be converted to the corresponding integer.
303
+
304
+ The latter conversion is the only implicit type conversion that
305
+ happens in mypyc programs.
306
+
307
+ Example::
308
+
309
+ def example() -> None:
310
+ # A small integer uses the value (unboxed) representation
311
+ x = 5
312
+ # A large integer uses the heap (boxed) representation
313
+ x = 2**500
314
+ # Lists always contain boxed integers
315
+ a = [55]
316
+ # When reading from a list, the object is automatically unboxed
317
+ x = a[0]
318
+ # True is converted to 1 on assignment
319
+ x = True
320
+
321
+ Since integers and floating point values have a different runtime
322
+ representations and neither can represent all the values of the other
323
+ type, type narrowing of floating point values through assignment is
324
+ disallowed in compiled code. For consistency, mypyc rejects assigning
325
+ an integer value to a float variable even in variable initialization.
326
+ An explicit conversion is required.
327
+
328
+ Examples::
329
+
330
+ def narrowing(n: int) -> None:
331
+ # Error: Incompatible value representations in assignment
332
+ # (expression has type "int", variable has type "float")
333
+ x: float = 0
334
+
335
+ y: float = 0.0 # Ok
336
+
337
+ if f():
338
+ y = n # Error
339
+ if f():
340
+ y = float(n) # Ok
341
+
342
+ .. _native-ints:
343
+
344
+ Native integer types
345
+ --------------------
346
+
347
+ You can use the native integer types ``i64`` (64-bit signed integer),
348
+ ``i32`` (32-bit signed integer), ``i16`` (16-bit signed integer), and
349
+ ``u8`` (8-bit unsigned integer) if you know that integer values will
350
+ always fit within fixed bounds. These types are faster than the
351
+ arbitrary-precision ``int`` type, since they don't require overflow
352
+ checks on operations. They may also use less memory than ``int``
353
+ values. The types are imported from the ``mypy_extensions`` module
354
+ (installed via ``pip install mypy_extensions``).
355
+
356
+ Example::
357
+
358
+ from mypy_extensions import i64
359
+
360
+ def sum_list(l: list[i64]) -> i64:
361
+ s: i64 = 0
362
+ for n in l:
363
+ s += n
364
+ return s
365
+
366
+ # Implicit conversions from int to i64
367
+ print(sum_list([1, 3, 5]))
368
+
369
+ .. note::
370
+
371
+ Since there are no overflow checks when performing native integer
372
+ arithmetic, the above function could result in an overflow or other
373
+ undefined behavior if the sum might not fit within 64 bits.
374
+
375
+ The behavior when running as interpreted Python program will be
376
+ different if there are overflows. Declaring native integer types
377
+ have no effect unless code is compiled. Native integer types are
378
+ effectively equivalent to ``int`` when interpreted.
379
+
380
+ Native integer types have these additional properties:
381
+
382
+ * Values can be implicitly converted between ``int`` and a native
383
+ integer type (both ways).
384
+
385
+ * Conversions between different native integer types must be explicit.
386
+ A conversion to a narrower native integer type truncates the value
387
+ without a runtime overflow check.
388
+
389
+ * If a binary operation (such as ``+``) or an augmented assignment
390
+ (such as ``+=``) mixes native integer and ``int`` values, the
391
+ ``int`` operand is implicitly coerced to the native integer type
392
+ (native integer types are "sticky").
393
+
394
+ * You can't mix different native integer types in binary
395
+ operations. Instead, convert between types explicitly.
396
+
397
+ For more information about native integer types, refer to
398
+ :ref:`native integer operations <int-ops>`.
openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Intermediate representation of classes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, NamedTuple
6
+
7
+ from mypyc.common import PROPSET_PREFIX, JsonDict
8
+ from mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature
9
+ from mypyc.ir.ops import DeserMaps, Value
10
+ from mypyc.ir.rtypes import RInstance, RType, deserialize_type
11
+ from mypyc.namegen import NameGenerator, exported_name
12
+
13
+ # Some notes on the vtable layout: Each concrete class has a vtable
14
+ # that contains function pointers for its methods. So that subclasses
15
+ # may be efficiently used when their parent class is expected, the
16
+ # layout of child vtables must be an extension of their base class's
17
+ # vtable.
18
+ #
19
+ # This makes multiple inheritance tricky, since obviously we cannot be
20
+ # an extension of multiple parent classes. We solve this by requiring
21
+ # all but one parent to be "traits", which we can operate on in a
22
+ # somewhat less efficient way. For each trait implemented by a class,
23
+ # we generate a separate vtable for the methods in that trait.
24
+ # We then store an array of (trait type, trait vtable) pointers alongside
25
+ # a class's main vtable. When we want to call a trait method, we
26
+ # (at runtime!) search the array of trait vtables to find the correct one,
27
+ # then call through it.
28
+ # Trait vtables additionally need entries for attribute getters and setters,
29
+ # since they can't always be in the same location.
30
+ #
31
+ # To keep down the number of indirections necessary, we store the
32
+ # array of trait vtables in the memory *before* the class vtable, and
33
+ # search it backwards. (This is a trick we can only do once---there
34
+ # are only two directions to store data in---but I don't think we'll
35
+ # need it again.)
36
+ # There are some tricks we could try in the future to store the trait
37
+ # vtables inline in the trait table (which would cut down one indirection),
38
+ # but this seems good enough for now.
39
+ #
40
+ # As an example:
41
+ # Imagine that we have a class B that inherits from a concrete class A
42
+ # and traits T1 and T2, and that A has methods foo() and
43
+ # bar() and B overrides bar() with a more specific type.
44
+ # Then B's vtable will look something like:
45
+ #
46
+ # T1 type object
47
+ # ptr to B's T1 trait vtable
48
+ # T2 type object
49
+ # ptr to B's T2 trait vtable
50
+ # -> | A.foo
51
+ # | Glue function that converts between A.bar's type and B.bar
52
+ # B.bar
53
+ # B.baz
54
+ #
55
+ # The arrow points to the "start" of the vtable (what vtable pointers
56
+ # point to) and the bars indicate which parts correspond to the parent
57
+ # class A's vtable layout.
58
+ #
59
+ # Classes that allow interpreted code to subclass them also have a
60
+ # "shadow vtable" that contains implementations that delegate to
61
+ # making a pycall, so that overridden methods in interpreted children
62
+ # will be called. (A better strategy could dynamically generate these
63
+ # vtables based on which methods are overridden in the children.)
64
+
65
+ # Descriptions of method and attribute entries in class vtables.
66
+ # The 'cls' field is the class that the method/attr was defined in,
67
+ # which might be a parent class.
68
+ # The 'shadow_method', if present, contains the method that should be
69
+ # placed in the class's shadow vtable (if it has one).
70
+
71
+
72
+ class VTableMethod(NamedTuple):
73
+ cls: "ClassIR" # noqa: UP037
74
+ name: str
75
+ method: FuncIR
76
+ shadow_method: FuncIR | None
77
+
78
+
79
+ VTableEntries = List[VTableMethod]
80
+
81
+
82
+ class ClassIR:
83
+ """Intermediate representation of a class.
84
+
85
+ This also describes the runtime structure of native instances.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ name: str,
91
+ module_name: str,
92
+ is_trait: bool = False,
93
+ is_generated: bool = False,
94
+ is_abstract: bool = False,
95
+ is_ext_class: bool = True,
96
+ is_final_class: bool = False,
97
+ ) -> None:
98
+ self.name = name
99
+ self.module_name = module_name
100
+ self.is_trait = is_trait
101
+ self.is_generated = is_generated
102
+ self.is_abstract = is_abstract
103
+ self.is_ext_class = is_ext_class
104
+ self.is_final_class = is_final_class
105
+ # An augmented class has additional methods separate from what mypyc generates.
106
+ # Right now the only one is dataclasses.
107
+ self.is_augmented = False
108
+ # Does this inherit from a Python class?
109
+ self.inherits_python = False
110
+ # Do instances of this class have __dict__?
111
+ self.has_dict = False
112
+ # Do we allow interpreted subclasses? Derived from a mypyc_attr.
113
+ self.allow_interpreted_subclasses = False
114
+ # Does this class need getseters to be generated for its attributes? (getseters are also
115
+ # added if is_generated is False)
116
+ self.needs_getseters = False
117
+ # Is this class declared as serializable (supports copy.copy
118
+ # and pickle) using @mypyc_attr(serializable=True)?
119
+ #
120
+ # Additionally, any class with this attribute False but with
121
+ # an __init__ that can be called without any arguments is
122
+ # *implicitly serializable*. In this case __init__ will be
123
+ # called during deserialization without arguments. If this is
124
+ # True, we match Python semantics and __init__ won't be called
125
+ # during deserialization.
126
+ #
127
+ # This impacts also all subclasses. Use is_serializable() to
128
+ # also consider base classes.
129
+ self._serializable = False
130
+ # If this a subclass of some built-in python class, the name
131
+ # of the object for that class. We currently only support this
132
+ # in a few ad-hoc cases.
133
+ self.builtin_base: str | None = None
134
+ # Default empty constructor
135
+ self.ctor = FuncDecl(name, None, module_name, FuncSignature([], RInstance(self)))
136
+ # Attributes defined in the class (not inherited)
137
+ self.attributes: dict[str, RType] = {}
138
+ # Deletable attributes
139
+ self.deletable: list[str] = []
140
+ # We populate method_types with the signatures of every method before
141
+ # we generate methods, and we rely on this information being present.
142
+ self.method_decls: dict[str, FuncDecl] = {}
143
+ # Map of methods that are actually present in an extension class
144
+ self.methods: dict[str, FuncIR] = {}
145
+ # Glue methods for boxing/unboxing when a class changes the type
146
+ # while overriding a method. Maps from (parent class overridden, method)
147
+ # to IR of glue method.
148
+ self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {}
149
+
150
+ # Properties are accessed like attributes, but have behavior like method calls.
151
+ # They don't belong in the methods dictionary, since we don't want to expose them to
152
+ # Python's method API. But we want to put them into our own vtable as methods, so that
153
+ # they are properly handled and overridden. The property dictionary values are a tuple
154
+ # containing a property getter and an optional property setter.
155
+ self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {}
156
+ # We generate these in prepare_class_def so that we have access to them when generating
157
+ # other methods and properties that rely on these types.
158
+ self.property_types: dict[str, RType] = {}
159
+
160
+ self.vtable: dict[str, int] | None = None
161
+ self.vtable_entries: VTableEntries = []
162
+ self.trait_vtables: dict[ClassIR, VTableEntries] = {}
163
+ # N.B: base might not actually quite be the direct base.
164
+ # It is the nearest concrete base, but we allow a trait in between.
165
+ self.base: ClassIR | None = None
166
+ self.traits: list[ClassIR] = []
167
+ # Supply a working mro for most generated classes. Real classes will need to
168
+ # fix it up.
169
+ self.mro: list[ClassIR] = [self]
170
+ # base_mro is the chain of concrete (non-trait) ancestors
171
+ self.base_mro: list[ClassIR] = [self]
172
+
173
+ # Direct subclasses of this class (use subclasses() to also include non-direct ones)
174
+ # None if separate compilation prevents this from working.
175
+ #
176
+ # Often it's better to use has_no_subclasses() or subclasses() instead.
177
+ self.children: list[ClassIR] | None = []
178
+
179
+ # Instance attributes that are initialized in the class body.
180
+ self.attrs_with_defaults: set[str] = set()
181
+
182
+ # Attributes that are always initialized in __init__ or class body
183
+ # (inferred in mypyc.analysis.attrdefined using interprocedural analysis)
184
+ self._always_initialized_attrs: set[str] = set()
185
+
186
+ # Attributes that are sometimes initialized in __init__
187
+ self._sometimes_initialized_attrs: set[str] = set()
188
+
189
+ # If True, __init__ can make 'self' visible to unanalyzed/arbitrary code
190
+ self.init_self_leak = False
191
+
192
+ # Definedness of these attributes is backed by a bitmap. Index in the list
193
+ # indicates the bit number. Includes inherited attributes. We need the
194
+ # bitmap for types such as native ints that can't have a dedicated error
195
+ # value that doesn't overlap a valid value. The bitmap is used if the
196
+ # value of an attribute is the same as the error value.
197
+ self.bitmap_attrs: list[str] = []
198
+
199
+ def __repr__(self) -> str:
200
+ return (
201
+ "ClassIR("
202
+ "name={self.name}, module_name={self.module_name}, "
203
+ "is_trait={self.is_trait}, is_generated={self.is_generated}, "
204
+ "is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, "
205
+ "is_final_class={self.is_final_class}"
206
+ ")".format(self=self)
207
+ )
208
+
209
+ @property
210
+ def fullname(self) -> str:
211
+ return f"{self.module_name}.{self.name}"
212
+
213
+ def real_base(self) -> ClassIR | None:
214
+ """Return the actual concrete base class, if there is one."""
215
+ if len(self.mro) > 1 and not self.mro[1].is_trait:
216
+ return self.mro[1]
217
+ return None
218
+
219
+ def vtable_entry(self, name: str) -> int:
220
+ assert self.vtable is not None, "vtable not computed yet"
221
+ assert name in self.vtable, f"{self.name!r} has no attribute {name!r}"
222
+ return self.vtable[name]
223
+
224
+ def attr_details(self, name: str) -> tuple[RType, ClassIR]:
225
+ for ir in self.mro:
226
+ if name in ir.attributes:
227
+ return ir.attributes[name], ir
228
+ if name in ir.property_types:
229
+ return ir.property_types[name], ir
230
+ raise KeyError(f"{self.name!r} has no attribute {name!r}")
231
+
232
+ def attr_type(self, name: str) -> RType:
233
+ return self.attr_details(name)[0]
234
+
235
+ def method_decl(self, name: str) -> FuncDecl:
236
+ for ir in self.mro:
237
+ if name in ir.method_decls:
238
+ return ir.method_decls[name]
239
+ raise KeyError(f"{self.name!r} has no attribute {name!r}")
240
+
241
+ def method_sig(self, name: str) -> FuncSignature:
242
+ return self.method_decl(name).sig
243
+
244
+ def has_method(self, name: str) -> bool:
245
+ try:
246
+ self.method_decl(name)
247
+ except KeyError:
248
+ return False
249
+ return True
250
+
251
+ def is_method_final(self, name: str) -> bool:
252
+ subs = self.subclasses()
253
+ if subs is None:
254
+ return self.is_final_class
255
+
256
+ if self.has_method(name):
257
+ method_decl = self.method_decl(name)
258
+ for subc in subs:
259
+ if subc.method_decl(name) != method_decl:
260
+ return False
261
+ return True
262
+ else:
263
+ return not any(subc.has_method(name) for subc in subs)
264
+
265
+ def has_attr(self, name: str) -> bool:
266
+ try:
267
+ self.attr_type(name)
268
+ except KeyError:
269
+ return False
270
+ return True
271
+
272
+ def is_deletable(self, name: str) -> bool:
273
+ return any(name in ir.deletable for ir in self.mro)
274
+
275
+ def is_always_defined(self, name: str) -> bool:
276
+ if self.is_deletable(name):
277
+ return False
278
+ return name in self._always_initialized_attrs
279
+
280
+ def name_prefix(self, names: NameGenerator) -> str:
281
+ return names.private_name(self.module_name, self.name)
282
+
283
+ def struct_name(self, names: NameGenerator) -> str:
284
+ return f"{exported_name(self.fullname)}Object"
285
+
286
+ def get_method_and_class(
287
+ self, name: str, *, prefer_method: bool = False
288
+ ) -> tuple[FuncIR, ClassIR] | None:
289
+ for ir in self.mro:
290
+ if name in ir.methods:
291
+ func_ir = ir.methods[name]
292
+ if not prefer_method and func_ir.decl.implicit:
293
+ # This is an implicit accessor, so there is also an attribute definition
294
+ # which the caller prefers. This happens if an attribute overrides a
295
+ # property.
296
+ return None
297
+ return func_ir, ir
298
+
299
+ return None
300
+
301
+ def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None:
302
+ res = self.get_method_and_class(name, prefer_method=prefer_method)
303
+ return res[0] if res else None
304
+
305
+ def has_method_decl(self, name: str) -> bool:
306
+ return any(name in ir.method_decls for ir in self.mro)
307
+
308
+ def has_no_subclasses(self) -> bool:
309
+ return self.children == [] and not self.allow_interpreted_subclasses
310
+
311
+ def subclasses(self) -> set[ClassIR] | None:
312
+ """Return all subclasses of this class, both direct and indirect.
313
+
314
+ Return None if it is impossible to identify all subclasses, for example
315
+ because we are performing separate compilation.
316
+ """
317
+ if self.children is None or self.allow_interpreted_subclasses:
318
+ return None
319
+ result = set(self.children)
320
+ for child in self.children:
321
+ if child.children:
322
+ child_subs = child.subclasses()
323
+ if child_subs is None:
324
+ return None
325
+ result.update(child_subs)
326
+ return result
327
+
328
+ def concrete_subclasses(self) -> list[ClassIR] | None:
329
+ """Return all concrete (i.e. non-trait and non-abstract) subclasses.
330
+
331
+ Include both direct and indirect subclasses. Place classes with no children first.
332
+ """
333
+ subs = self.subclasses()
334
+ if subs is None:
335
+ return None
336
+ concrete = {c for c in subs if not (c.is_trait or c.is_abstract)}
337
+ # We place classes with no children first because they are more likely
338
+ # to appear in various isinstance() checks. We then sort leaves by name
339
+ # to get stable order.
340
+ return sorted(concrete, key=lambda c: (len(c.children or []), c.name))
341
+
342
+ def is_serializable(self) -> bool:
343
+ return any(ci._serializable for ci in self.mro)
344
+
345
+ def serialize(self) -> JsonDict:
346
+ return {
347
+ "name": self.name,
348
+ "module_name": self.module_name,
349
+ "is_trait": self.is_trait,
350
+ "is_ext_class": self.is_ext_class,
351
+ "is_abstract": self.is_abstract,
352
+ "is_generated": self.is_generated,
353
+ "is_augmented": self.is_augmented,
354
+ "is_final_class": self.is_final_class,
355
+ "inherits_python": self.inherits_python,
356
+ "has_dict": self.has_dict,
357
+ "allow_interpreted_subclasses": self.allow_interpreted_subclasses,
358
+ "needs_getseters": self.needs_getseters,
359
+ "_serializable": self._serializable,
360
+ "builtin_base": self.builtin_base,
361
+ "ctor": self.ctor.serialize(),
362
+ # We serialize dicts as lists to ensure order is preserved
363
+ "attributes": [(k, t.serialize()) for k, t in self.attributes.items()],
364
+ # We try to serialize a name reference, but if the decl isn't in methods
365
+ # then we can't be sure that will work so we serialize the whole decl.
366
+ "method_decls": [
367
+ (k, d.id if k in self.methods else d.serialize())
368
+ for k, d in self.method_decls.items()
369
+ ],
370
+ # We serialize method fullnames out and put methods in a separate dict
371
+ "methods": [(k, m.id) for k, m in self.methods.items()],
372
+ "glue_methods": [
373
+ ((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items()
374
+ ],
375
+ # We serialize properties and property_types separately out of an
376
+ # abundance of caution about preserving dict ordering...
377
+ "property_types": [(k, t.serialize()) for k, t in self.property_types.items()],
378
+ "properties": list(self.properties),
379
+ "vtable": self.vtable,
380
+ "vtable_entries": serialize_vtable(self.vtable_entries),
381
+ "trait_vtables": [
382
+ (cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items()
383
+ ],
384
+ # References to class IRs are all just names
385
+ "base": self.base.fullname if self.base else None,
386
+ "traits": [cir.fullname for cir in self.traits],
387
+ "mro": [cir.fullname for cir in self.mro],
388
+ "base_mro": [cir.fullname for cir in self.base_mro],
389
+ "children": (
390
+ [cir.fullname for cir in self.children] if self.children is not None else None
391
+ ),
392
+ "deletable": self.deletable,
393
+ "attrs_with_defaults": sorted(self.attrs_with_defaults),
394
+ "_always_initialized_attrs": sorted(self._always_initialized_attrs),
395
+ "_sometimes_initialized_attrs": sorted(self._sometimes_initialized_attrs),
396
+ "init_self_leak": self.init_self_leak,
397
+ }
398
+
399
+ @classmethod
400
+ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR:
401
+ fullname = data["module_name"] + "." + data["name"]
402
+ assert fullname in ctx.classes, "Class %s not in deser class map" % fullname
403
+ ir = ctx.classes[fullname]
404
+
405
+ ir.is_trait = data["is_trait"]
406
+ ir.is_generated = data["is_generated"]
407
+ ir.is_abstract = data["is_abstract"]
408
+ ir.is_ext_class = data["is_ext_class"]
409
+ ir.is_augmented = data["is_augmented"]
410
+ ir.is_final_class = data["is_final_class"]
411
+ ir.inherits_python = data["inherits_python"]
412
+ ir.has_dict = data["has_dict"]
413
+ ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"]
414
+ ir.needs_getseters = data["needs_getseters"]
415
+ ir._serializable = data["_serializable"]
416
+ ir.builtin_base = data["builtin_base"]
417
+ ir.ctor = FuncDecl.deserialize(data["ctor"], ctx)
418
+ ir.attributes = {k: deserialize_type(t, ctx) for k, t in data["attributes"]}
419
+ ir.method_decls = {
420
+ k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)
421
+ for k, v in data["method_decls"]
422
+ }
423
+ ir.methods = {k: ctx.functions[v] for k, v in data["methods"]}
424
+ ir.glue_methods = {
425
+ (ctx.classes[c], k): ctx.functions[v] for (c, k), v in data["glue_methods"]
426
+ }
427
+ ir.property_types = {k: deserialize_type(t, ctx) for k, t in data["property_types"]}
428
+ ir.properties = {
429
+ k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data["properties"]
430
+ }
431
+
432
+ ir.vtable = data["vtable"]
433
+ ir.vtable_entries = deserialize_vtable(data["vtable_entries"], ctx)
434
+ ir.trait_vtables = {
435
+ ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data["trait_vtables"]
436
+ }
437
+
438
+ base = data["base"]
439
+ ir.base = ctx.classes[base] if base else None
440
+ ir.traits = [ctx.classes[s] for s in data["traits"]]
441
+ ir.mro = [ctx.classes[s] for s in data["mro"]]
442
+ ir.base_mro = [ctx.classes[s] for s in data["base_mro"]]
443
+ ir.children = data["children"] and [ctx.classes[s] for s in data["children"]]
444
+ ir.deletable = data["deletable"]
445
+ ir.attrs_with_defaults = set(data["attrs_with_defaults"])
446
+ ir._always_initialized_attrs = set(data["_always_initialized_attrs"])
447
+ ir._sometimes_initialized_attrs = set(data["_sometimes_initialized_attrs"])
448
+ ir.init_self_leak = data["init_self_leak"]
449
+
450
+ return ir
451
+
452
+
453
+ class NonExtClassInfo:
454
+ """Information needed to construct a non-extension class (Python class).
455
+
456
+ Includes the class dictionary, a tuple of base classes,
457
+ the class annotations dictionary, and the metaclass.
458
+ """
459
+
460
+ def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None:
461
+ self.dict = dict
462
+ self.bases = bases
463
+ self.anns = anns
464
+ self.metaclass = metaclass
465
+
466
+
467
+ def serialize_vtable_entry(entry: VTableMethod) -> JsonDict:
468
+ return {
469
+ ".class": "VTableMethod",
470
+ "cls": entry.cls.fullname,
471
+ "name": entry.name,
472
+ "method": entry.method.decl.id,
473
+ "shadow_method": entry.shadow_method.decl.id if entry.shadow_method else None,
474
+ }
475
+
476
+
477
+ def serialize_vtable(vtable: VTableEntries) -> list[JsonDict]:
478
+ return [serialize_vtable_entry(v) for v in vtable]
479
+
480
+
481
+ def deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod:
482
+ if data[".class"] == "VTableMethod":
483
+ return VTableMethod(
484
+ ctx.classes[data["cls"]],
485
+ data["name"],
486
+ ctx.functions[data["method"]],
487
+ ctx.functions[data["shadow_method"]] if data["shadow_method"] else None,
488
+ )
489
+ assert False, "Bogus vtable .class: %s" % data[".class"]
490
+
491
+
492
+ def deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries:
493
+ return [deserialize_vtable_entry(x, ctx) for x in data]
494
+
495
+
496
+ def all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None:
497
+ """Return all concrete classes among the class itself and its subclasses."""
498
+ concrete = class_ir.concrete_subclasses()
499
+ if concrete is None:
500
+ return None
501
+ if not (class_ir.is_abstract or class_ir.is_trait):
502
+ concrete.append(class_ir)
503
+ return concrete
openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for pretty-printing IR in a human-readable form."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from typing import Any, Final, Sequence, Union
7
+
8
+ from mypyc.common import short_name
9
+ from mypyc.ir.func_ir import FuncIR, all_values_full
10
+ from mypyc.ir.module_ir import ModuleIRs
11
+ from mypyc.ir.ops import (
12
+ ERR_NEVER,
13
+ Assign,
14
+ AssignMulti,
15
+ BasicBlock,
16
+ Box,
17
+ Branch,
18
+ Call,
19
+ CallC,
20
+ Cast,
21
+ ComparisonOp,
22
+ ControlOp,
23
+ DecRef,
24
+ Extend,
25
+ Float,
26
+ FloatComparisonOp,
27
+ FloatNeg,
28
+ FloatOp,
29
+ GetAttr,
30
+ GetElementPtr,
31
+ Goto,
32
+ IncRef,
33
+ InitStatic,
34
+ Integer,
35
+ IntOp,
36
+ KeepAlive,
37
+ LoadAddress,
38
+ LoadErrorValue,
39
+ LoadGlobal,
40
+ LoadLiteral,
41
+ LoadMem,
42
+ LoadStatic,
43
+ MethodCall,
44
+ Op,
45
+ OpVisitor,
46
+ PrimitiveOp,
47
+ RaiseStandardError,
48
+ Register,
49
+ Return,
50
+ SetAttr,
51
+ SetMem,
52
+ Truncate,
53
+ TupleGet,
54
+ TupleSet,
55
+ Unborrow,
56
+ Unbox,
57
+ Unreachable,
58
+ Value,
59
+ )
60
+ from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive
61
+
62
+ ErrorSource = Union[BasicBlock, Op]
63
+
64
+
65
+ class IRPrettyPrintVisitor(OpVisitor[str]):
66
+ """Internal visitor that pretty-prints ops."""
67
+
68
+ def __init__(self, names: dict[Value, str]) -> None:
69
+ # This should contain a name for all values that are shown as
70
+ # registers in the output. This is not just for Register
71
+ # instances -- all Ops that produce values need (generated) names.
72
+ self.names = names
73
+
74
+ def visit_goto(self, op: Goto) -> str:
75
+ return self.format("goto %l", op.label)
76
+
77
+ branch_op_names: Final = {Branch.BOOL: ("%r", "bool"), Branch.IS_ERROR: ("is_error(%r)", "")}
78
+
79
+ def visit_branch(self, op: Branch) -> str:
80
+ fmt, typ = self.branch_op_names[op.op]
81
+ if op.negated:
82
+ fmt = f"not {fmt}"
83
+
84
+ cond = self.format(fmt, op.value)
85
+ tb = ""
86
+ if op.traceback_entry:
87
+ tb = " (error at %s:%d)" % op.traceback_entry
88
+ fmt = f"if {cond} goto %l{tb} else goto %l"
89
+ if typ:
90
+ fmt += f" :: {typ}"
91
+ return self.format(fmt, op.true, op.false)
92
+
93
+ def visit_return(self, op: Return) -> str:
94
+ return self.format("return %r", op.value)
95
+
96
+ def visit_unreachable(self, op: Unreachable) -> str:
97
+ return "unreachable"
98
+
99
+ def visit_assign(self, op: Assign) -> str:
100
+ return self.format("%r = %r", op.dest, op.src)
101
+
102
+ def visit_assign_multi(self, op: AssignMulti) -> str:
103
+ return self.format("%r = [%s]", op.dest, ", ".join(self.format("%r", v) for v in op.src))
104
+
105
+ def visit_load_error_value(self, op: LoadErrorValue) -> str:
106
+ return self.format("%r = <error> :: %s", op, op.type)
107
+
108
+ def visit_load_literal(self, op: LoadLiteral) -> str:
109
+ prefix = ""
110
+ # For values that have a potential unboxed representation, make
111
+ # it explicit that this is a Python object.
112
+ if isinstance(op.value, int):
113
+ prefix = "object "
114
+
115
+ rvalue = repr(op.value)
116
+ if isinstance(op.value, frozenset):
117
+ # We need to generate a string representation that won't vary
118
+ # run-to-run because sets are unordered, otherwise we may get
119
+ # spurious irbuild test failures.
120
+ #
121
+ # Sorting by the item's string representation is a bit of a
122
+ # hack, but it's stable and won't cause TypeErrors.
123
+ formatted_items = [repr(i) for i in sorted(op.value, key=str)]
124
+ rvalue = "frozenset({" + ", ".join(formatted_items) + "})"
125
+ return self.format("%r = %s%s", op, prefix, rvalue)
126
+
127
+ def visit_get_attr(self, op: GetAttr) -> str:
128
+ return self.format("%r = %s%r.%s", op, self.borrow_prefix(op), op.obj, op.attr)
129
+
130
+ def borrow_prefix(self, op: Op) -> str:
131
+ if op.is_borrowed:
132
+ return "borrow "
133
+ return ""
134
+
135
+ def visit_set_attr(self, op: SetAttr) -> str:
136
+ if op.is_init:
137
+ assert op.error_kind == ERR_NEVER
138
+ if op.error_kind == ERR_NEVER:
139
+ # Initialization and direct struct access can never fail
140
+ return self.format("%r.%s = %r", op.obj, op.attr, op.src)
141
+ else:
142
+ return self.format("%r.%s = %r; %r = is_error", op.obj, op.attr, op.src, op)
143
+
144
+ def visit_load_static(self, op: LoadStatic) -> str:
145
+ ann = f" ({repr(op.ann)})" if op.ann else ""
146
+ name = op.identifier
147
+ if op.module_name is not None:
148
+ name = f"{op.module_name}.{name}"
149
+ return self.format("%r = %s :: %s%s", op, name, op.namespace, ann)
150
+
151
+ def visit_init_static(self, op: InitStatic) -> str:
152
+ name = op.identifier
153
+ if op.module_name is not None:
154
+ name = f"{op.module_name}.{name}"
155
+ return self.format("%s = %r :: %s", name, op.value, op.namespace)
156
+
157
+ def visit_tuple_get(self, op: TupleGet) -> str:
158
+ return self.format("%r = %s%r[%d]", op, self.borrow_prefix(op), op.src, op.index)
159
+
160
+ def visit_tuple_set(self, op: TupleSet) -> str:
161
+ item_str = ", ".join(self.format("%r", item) for item in op.items)
162
+ return self.format("%r = (%s)", op, item_str)
163
+
164
+ def visit_inc_ref(self, op: IncRef) -> str:
165
+ s = self.format("inc_ref %r", op.src)
166
+ # TODO: Remove bool check (it's unboxed)
167
+ if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
168
+ s += f" :: {short_name(op.src.type.name)}"
169
+ return s
170
+
171
+ def visit_dec_ref(self, op: DecRef) -> str:
172
+ s = self.format("%sdec_ref %r", "x" if op.is_xdec else "", op.src)
173
+ # TODO: Remove bool check (it's unboxed)
174
+ if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
175
+ s += f" :: {short_name(op.src.type.name)}"
176
+ return s
177
+
178
+ def visit_call(self, op: Call) -> str:
179
+ args = ", ".join(self.format("%r", arg) for arg in op.args)
180
+ # TODO: Display long name?
181
+ short_name = op.fn.shortname
182
+ s = f"{short_name}({args})"
183
+ if not op.is_void:
184
+ s = self.format("%r = ", op) + s
185
+ return s
186
+
187
+ def visit_method_call(self, op: MethodCall) -> str:
188
+ args = ", ".join(self.format("%r", arg) for arg in op.args)
189
+ s = self.format("%r.%s(%s)", op.obj, op.method, args)
190
+ if not op.is_void:
191
+ s = self.format("%r = ", op) + s
192
+ return s
193
+
194
+ def visit_cast(self, op: Cast) -> str:
195
+ return self.format("%r = %scast(%s, %r)", op, self.borrow_prefix(op), op.type, op.src)
196
+
197
+ def visit_box(self, op: Box) -> str:
198
+ return self.format("%r = box(%s, %r)", op, op.src.type, op.src)
199
+
200
+ def visit_unbox(self, op: Unbox) -> str:
201
+ return self.format("%r = unbox(%s, %r)", op, op.type, op.src)
202
+
203
+ def visit_raise_standard_error(self, op: RaiseStandardError) -> str:
204
+ if op.value is not None:
205
+ if isinstance(op.value, str):
206
+ return self.format("%r = raise %s(%s)", op, op.class_name, repr(op.value))
207
+ elif isinstance(op.value, Value):
208
+ return self.format("%r = raise %s(%r)", op, op.class_name, op.value)
209
+ else:
210
+ assert False, "value type must be either str or Value"
211
+ else:
212
+ return self.format("%r = raise %s", op, op.class_name)
213
+
214
+ def visit_call_c(self, op: CallC) -> str:
215
+ args_str = ", ".join(self.format("%r", arg) for arg in op.args)
216
+ if op.is_void:
217
+ return self.format("%s(%s)", op.function_name, args_str)
218
+ else:
219
+ return self.format("%r = %s(%s)", op, op.function_name, args_str)
220
+
221
+ def visit_primitive_op(self, op: PrimitiveOp) -> str:
222
+ args = []
223
+ arg_index = 0
224
+ type_arg_index = 0
225
+ for arg_type in zip(op.desc.arg_types):
226
+ if arg_type:
227
+ args.append(self.format("%r", op.args[arg_index]))
228
+ arg_index += 1
229
+ else:
230
+ assert op.type_args
231
+ args.append(self.format("%r", op.type_args[type_arg_index]))
232
+ type_arg_index += 1
233
+
234
+ args_str = ", ".join(args)
235
+ if op.is_void:
236
+ return self.format("%s %s", op.desc.name, args_str)
237
+ else:
238
+ return self.format("%r = %s %s", op, op.desc.name, args_str)
239
+
240
+ def visit_truncate(self, op: Truncate) -> str:
241
+ return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type)
242
+
243
+ def visit_extend(self, op: Extend) -> str:
244
+ if op.signed:
245
+ extra = " signed"
246
+ else:
247
+ extra = ""
248
+ return self.format("%r = extend%s %r: %t to %t", op, extra, op.src, op.src_type, op.type)
249
+
250
+ def visit_load_global(self, op: LoadGlobal) -> str:
251
+ ann = f" ({repr(op.ann)})" if op.ann else ""
252
+ return self.format("%r = load_global %s :: static%s", op, op.identifier, ann)
253
+
254
+ def visit_int_op(self, op: IntOp) -> str:
255
+ return self.format("%r = %r %s %r", op, op.lhs, IntOp.op_str[op.op], op.rhs)
256
+
257
+ def visit_comparison_op(self, op: ComparisonOp) -> str:
258
+ if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):
259
+ sign_format = " :: signed"
260
+ elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):
261
+ sign_format = " :: unsigned"
262
+ else:
263
+ sign_format = ""
264
+ return self.format(
265
+ "%r = %r %s %r%s", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format
266
+ )
267
+
268
+ def visit_float_op(self, op: FloatOp) -> str:
269
+ return self.format("%r = %r %s %r", op, op.lhs, FloatOp.op_str[op.op], op.rhs)
270
+
271
+ def visit_float_neg(self, op: FloatNeg) -> str:
272
+ return self.format("%r = -%r", op, op.src)
273
+
274
+ def visit_float_comparison_op(self, op: FloatComparisonOp) -> str:
275
+ return self.format("%r = %r %s %r", op, op.lhs, op.op_str[op.op], op.rhs)
276
+
277
+ def visit_load_mem(self, op: LoadMem) -> str:
278
+ return self.format("%r = load_mem %r :: %t*", op, op.src, op.type)
279
+
280
+ def visit_set_mem(self, op: SetMem) -> str:
281
+ return self.format("set_mem %r, %r :: %t*", op.dest, op.src, op.dest_type)
282
+
283
+ def visit_get_element_ptr(self, op: GetElementPtr) -> str:
284
+ return self.format("%r = get_element_ptr %r %s :: %t", op, op.src, op.field, op.src_type)
285
+
286
+ def visit_load_address(self, op: LoadAddress) -> str:
287
+ if isinstance(op.src, Register):
288
+ return self.format("%r = load_address %r", op, op.src)
289
+ elif isinstance(op.src, LoadStatic):
290
+ name = op.src.identifier
291
+ if op.src.module_name is not None:
292
+ name = f"{op.src.module_name}.{name}"
293
+ return self.format("%r = load_address %s :: %s", op, name, op.src.namespace)
294
+ else:
295
+ return self.format("%r = load_address %s", op, op.src)
296
+
297
+ def visit_keep_alive(self, op: KeepAlive) -> str:
298
+ if op.steal:
299
+ steal = "steal "
300
+ else:
301
+ steal = ""
302
+ return self.format(
303
+ "keep_alive {}{}".format(steal, ", ".join(self.format("%r", v) for v in op.src))
304
+ )
305
+
306
+ def visit_unborrow(self, op: Unborrow) -> str:
307
+ return self.format("%r = unborrow %r", op, op.src)
308
+
309
+ # Helpers
310
+
311
+ def format(self, fmt: str, *args: Any) -> str:
312
+ """Helper for formatting strings.
313
+
314
+ These format sequences are supported in fmt:
315
+
316
+ %s: arbitrary object converted to string using str()
317
+ %r: name of IR value/register
318
+ %d: int
319
+ %f: float
320
+ %l: BasicBlock (formatted as label 'Ln')
321
+ %t: RType
322
+ """
323
+ result = []
324
+ i = 0
325
+ arglist = list(args)
326
+ while i < len(fmt):
327
+ n = fmt.find("%", i)
328
+ if n < 0:
329
+ n = len(fmt)
330
+ result.append(fmt[i:n])
331
+ if n < len(fmt):
332
+ typespec = fmt[n + 1]
333
+ arg = arglist.pop(0)
334
+ if typespec == "r":
335
+ # Register/value
336
+ assert isinstance(arg, Value)
337
+ if isinstance(arg, Integer):
338
+ result.append(str(arg.value))
339
+ elif isinstance(arg, Float):
340
+ result.append(repr(arg.value))
341
+ else:
342
+ result.append(self.names[arg])
343
+ elif typespec == "d":
344
+ # Integer
345
+ result.append("%d" % arg)
346
+ elif typespec == "f":
347
+ # Float
348
+ result.append("%f" % arg)
349
+ elif typespec == "l":
350
+ # Basic block (label)
351
+ assert isinstance(arg, BasicBlock)
352
+ result.append("L%s" % arg.label)
353
+ elif typespec == "t":
354
+ # RType
355
+ assert isinstance(arg, RType)
356
+ result.append(arg.name)
357
+ elif typespec == "s":
358
+ # String
359
+ result.append(str(arg))
360
+ else:
361
+ raise ValueError(f"Invalid format sequence %{typespec}")
362
+ i = n + 2
363
+ else:
364
+ i = n
365
+ return "".join(result)
366
+
367
+
368
+ def format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]:
369
+ result = []
370
+ i = 0
371
+ regs = all_values_full(func_ir.arg_regs, func_ir.blocks)
372
+ while i < len(regs):
373
+ i0 = i
374
+ group = [names[regs[i0]]]
375
+ while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type:
376
+ i += 1
377
+ group.append(names[regs[i]])
378
+ i += 1
379
+ result.append("{} :: {}".format(", ".join(group), regs[i0].type))
380
+ return result
381
+
382
+
383
+ def format_blocks(
384
+ blocks: list[BasicBlock],
385
+ names: dict[Value, str],
386
+ source_to_error: dict[ErrorSource, list[str]],
387
+ ) -> list[str]:
388
+ """Format a list of IR basic blocks into a human-readable form."""
389
+ # First label all of the blocks
390
+ for i, block in enumerate(blocks):
391
+ block.label = i
392
+
393
+ handler_map: dict[BasicBlock, list[BasicBlock]] = {}
394
+ for b in blocks:
395
+ if b.error_handler:
396
+ handler_map.setdefault(b.error_handler, []).append(b)
397
+
398
+ visitor = IRPrettyPrintVisitor(names)
399
+
400
+ lines = []
401
+ for i, block in enumerate(blocks):
402
+ handler_msg = ""
403
+ if block in handler_map:
404
+ labels = sorted("L%d" % b.label for b in handler_map[block])
405
+ handler_msg = " (handler for {})".format(", ".join(labels))
406
+
407
+ lines.append("L%d:%s" % (block.label, handler_msg))
408
+ if block in source_to_error:
409
+ for error in source_to_error[block]:
410
+ lines.append(f" ERR: {error}")
411
+ ops = block.ops
412
+ if (
413
+ isinstance(ops[-1], Goto)
414
+ and i + 1 < len(blocks)
415
+ and ops[-1].label == blocks[i + 1]
416
+ and not source_to_error.get(ops[-1], [])
417
+ ):
418
+ # Hide the last goto if it just goes to the next basic block,
419
+ # and there are no assocatiated errors with the op.
420
+ ops = ops[:-1]
421
+ for op in ops:
422
+ line = " " + op.accept(visitor)
423
+ lines.append(line)
424
+ if op in source_to_error:
425
+ for error in source_to_error[op]:
426
+ lines.append(f" ERR: {error}")
427
+
428
+ if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)):
429
+ # Each basic block needs to exit somewhere.
430
+ lines.append(" [MISSING BLOCK EXIT OPCODE]")
431
+ return lines
432
+
433
+
434
+ def format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]:
435
+ lines = []
436
+ cls_prefix = fn.class_name + "." if fn.class_name else ""
437
+ lines.append(
438
+ "def {}{}({}):".format(cls_prefix, fn.name, ", ".join(arg.name for arg in fn.args))
439
+ )
440
+ names = generate_names_for_ir(fn.arg_regs, fn.blocks)
441
+ for line in format_registers(fn, names):
442
+ lines.append(" " + line)
443
+
444
+ source_to_error = defaultdict(list)
445
+ for source, error in errors:
446
+ source_to_error[source].append(error)
447
+
448
+ code = format_blocks(fn.blocks, names, source_to_error)
449
+ lines.extend(code)
450
+ return lines
451
+
452
+
453
+ def format_modules(modules: ModuleIRs) -> list[str]:
454
+ ops = []
455
+ for module in modules.values():
456
+ for fn in module.functions:
457
+ ops.extend(format_func(fn))
458
+ ops.append("")
459
+ return ops
460
+
461
+
462
+ def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]:
463
+ """Generate unique names for IR values.
464
+
465
+ Give names such as 'r5' to temp values in IR which are useful when
466
+ pretty-printing or generating C. Ensure generated names are unique.
467
+ """
468
+ names: dict[Value, str] = {}
469
+ used_names = set()
470
+
471
+ temp_index = 0
472
+
473
+ for arg in args:
474
+ names[arg] = arg.name
475
+ used_names.add(arg.name)
476
+
477
+ for block in blocks:
478
+ for op in block.ops:
479
+ values = []
480
+
481
+ for source in op.sources():
482
+ if source not in names:
483
+ values.append(source)
484
+
485
+ if isinstance(op, (Assign, AssignMulti)):
486
+ values.append(op.dest)
487
+ elif isinstance(op, ControlOp) or op.is_void:
488
+ continue
489
+ elif op not in names:
490
+ values.append(op)
491
+
492
+ for value in values:
493
+ if value in names:
494
+ continue
495
+ if isinstance(value, Register) and value.name:
496
+ name = value.name
497
+ elif isinstance(value, (Integer, Float)):
498
+ continue
499
+ else:
500
+ name = "r%d" % temp_index
501
+ temp_index += 1
502
+
503
+ # Append _2, _3, ... if needed to make the name unique.
504
+ if name in used_names:
505
+ n = 2
506
+ while True:
507
+ candidate = "%s_%d" % (name, n)
508
+ if candidate not in used_names:
509
+ name = candidate
510
+ break
511
+ n += 1
512
+
513
+ names[value] = name
514
+ used_names.add(name)
515
+
516
+ return names
openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Types used in the intermediate representation.
2
+
3
+ These are runtime types (RTypes), as opposed to mypy Type objects.
4
+ The latter are only used during type checking and not directly used at
5
+ runtime. Runtime types are derived from mypy types, but there's no
6
+ simple one-to-one correspondence. (Here 'runtime' means 'runtime
7
+ checked'.)
8
+
9
+ The generated IR ensures some runtime type safety properties based on
10
+ RTypes. Compiled code can assume that the runtime value matches the
11
+ static RType of a value. If the RType of a register is 'builtins.str'
12
+ (str_rprimitive), for example, the generated IR will ensure that the
13
+ register will have a 'str' object.
14
+
15
+ RTypes are simpler and less expressive than mypy (or PEP 484)
16
+ types. For example, all mypy types of form 'list[T]' (for arbitrary T)
17
+ are erased to the single RType 'builtins.list' (list_rprimitive).
18
+
19
+ mypyc.irbuild.mapper.Mapper.type_to_rtype converts mypy Types to mypyc
20
+ RTypes.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from abc import abstractmethod
26
+ from typing import TYPE_CHECKING, ClassVar, Final, Generic, TypeVar
27
+ from typing_extensions import TypeGuard
28
+
29
+ from mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE, JsonDict, short_name
30
+ from mypyc.namegen import NameGenerator
31
+
32
+ if TYPE_CHECKING:
33
+ from mypyc.ir.class_ir import ClassIR
34
+ from mypyc.ir.ops import DeserMaps
35
+
36
+ T = TypeVar("T")
37
+
38
+
39
+ class RType:
40
+ """Abstract base class for runtime types (erased, only concrete; no generics)."""
41
+
42
+ name: str
43
+ # If True, the type has a special unboxed representation. If False, the
44
+ # type is represented as PyObject *. Even if True, the representation
45
+ # may contain pointers.
46
+ is_unboxed = False
47
+ # This is the C undefined value for this type. It's used for initialization
48
+ # if there's no value yet, and for function return value on error/exception.
49
+ #
50
+ # TODO: This shouldn't be specific to C or a string
51
+ c_undefined: str
52
+ # If unboxed: does the unboxed version use reference counting?
53
+ is_refcounted = True
54
+ # C type; use Emitter.ctype() to access
55
+ _ctype: str
56
+ # If True, error/undefined value overlaps with a valid value. To
57
+ # detect an exception, PyErr_Occurred() must be used in addition
58
+ # to checking for error value as the return value of a function.
59
+ #
60
+ # For example, no i64 value can be reserved for error value, so we
61
+ # pick an arbitrary value (e.g. -113) to signal error, but this is
62
+ # also a valid non-error value.
63
+ error_overlap = False
64
+
65
+ @abstractmethod
66
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
67
+ raise NotImplementedError()
68
+
69
+ def short_name(self) -> str:
70
+ return short_name(self.name)
71
+
72
+ def __str__(self) -> str:
73
+ return short_name(self.name)
74
+
75
+ def __repr__(self) -> str:
76
+ return "<%s>" % self.__class__.__name__
77
+
78
+ def serialize(self) -> JsonDict | str:
79
+ raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
80
+
81
+
82
+ def deserialize_type(data: JsonDict | str, ctx: DeserMaps) -> RType:
83
+ """Deserialize a JSON-serialized RType.
84
+
85
+ Arguments:
86
+ data: The decoded JSON of the serialized type
87
+ ctx: The deserialization maps to use
88
+ """
89
+ # Since there are so few types, we just case on them directly. If
90
+ # more get added we should switch to a system like mypy.types
91
+ # uses.
92
+ if isinstance(data, str):
93
+ if data in ctx.classes:
94
+ return RInstance(ctx.classes[data])
95
+ elif data in RPrimitive.primitive_map:
96
+ return RPrimitive.primitive_map[data]
97
+ elif data == "void":
98
+ return RVoid()
99
+ else:
100
+ assert False, f"Can't find class {data}"
101
+ elif data[".class"] == "RTuple":
102
+ return RTuple.deserialize(data, ctx)
103
+ elif data[".class"] == "RUnion":
104
+ return RUnion.deserialize(data, ctx)
105
+ raise NotImplementedError("unexpected .class {}".format(data[".class"]))
106
+
107
+
108
+ class RTypeVisitor(Generic[T]):
109
+ """Generic visitor over RTypes (uses the visitor design pattern)."""
110
+
111
+ @abstractmethod
112
+ def visit_rprimitive(self, typ: RPrimitive) -> T:
113
+ raise NotImplementedError
114
+
115
+ @abstractmethod
116
+ def visit_rinstance(self, typ: RInstance) -> T:
117
+ raise NotImplementedError
118
+
119
+ @abstractmethod
120
+ def visit_runion(self, typ: RUnion) -> T:
121
+ raise NotImplementedError
122
+
123
+ @abstractmethod
124
+ def visit_rtuple(self, typ: RTuple) -> T:
125
+ raise NotImplementedError
126
+
127
+ @abstractmethod
128
+ def visit_rstruct(self, typ: RStruct) -> T:
129
+ raise NotImplementedError
130
+
131
+ @abstractmethod
132
+ def visit_rarray(self, typ: RArray) -> T:
133
+ raise NotImplementedError
134
+
135
+ @abstractmethod
136
+ def visit_rvoid(self, typ: RVoid) -> T:
137
+ raise NotImplementedError
138
+
139
+
140
+ class RVoid(RType):
141
+ """The void type (no value).
142
+
143
+ This is a singleton -- use void_rtype (below) to refer to this instead of
144
+ constructing a new instance.
145
+ """
146
+
147
+ is_unboxed = False
148
+ name = "void"
149
+ ctype = "void"
150
+
151
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
152
+ return visitor.visit_rvoid(self)
153
+
154
+ def serialize(self) -> str:
155
+ return "void"
156
+
157
+ def __eq__(self, other: object) -> bool:
158
+ return isinstance(other, RVoid)
159
+
160
+ def __hash__(self) -> int:
161
+ return hash(RVoid)
162
+
163
+
164
+ # Singleton instance of RVoid
165
+ void_rtype: Final = RVoid()
166
+
167
+
168
+ class RPrimitive(RType):
169
+ """Primitive type such as 'object' or 'int'.
170
+
171
+ These often have custom ops associated with them. The 'object'
172
+ primitive type can be used to hold arbitrary Python objects.
173
+
174
+ Different primitive types have different representations, and
175
+ primitives may be unboxed or boxed. Primitive types don't need to
176
+ directly correspond to Python types, but most do.
177
+
178
+ NOTE: All supported primitive types are defined below
179
+ (e.g. object_rprimitive).
180
+ """
181
+
182
+ # Map from primitive names to primitive types and is used by deserialization
183
+ primitive_map: ClassVar[dict[str, RPrimitive]] = {}
184
+
185
+ def __init__(
186
+ self,
187
+ name: str,
188
+ *,
189
+ is_unboxed: bool,
190
+ is_refcounted: bool,
191
+ is_native_int: bool = False,
192
+ is_signed: bool = False,
193
+ ctype: str = "PyObject *",
194
+ size: int = PLATFORM_SIZE,
195
+ error_overlap: bool = False,
196
+ ) -> None:
197
+ RPrimitive.primitive_map[name] = self
198
+
199
+ self.name = name
200
+ self.is_unboxed = is_unboxed
201
+ self.is_refcounted = is_refcounted
202
+ self.is_native_int = is_native_int
203
+ self.is_signed = is_signed
204
+ self._ctype = ctype
205
+ self.size = size
206
+ self.error_overlap = error_overlap
207
+ if ctype == "CPyTagged":
208
+ self.c_undefined = "CPY_INT_TAG"
209
+ elif ctype in ("int16_t", "int32_t", "int64_t"):
210
+ # This is basically an arbitrary value that is pretty
211
+ # unlikely to overlap with a real value.
212
+ self.c_undefined = "-113"
213
+ elif ctype == "CPyPtr":
214
+ # TODO: Invent an overlapping error value?
215
+ self.c_undefined = "0"
216
+ elif ctype == "PyObject *":
217
+ # Boxed types use the null pointer as the error value.
218
+ self.c_undefined = "NULL"
219
+ elif ctype == "char":
220
+ self.c_undefined = "2"
221
+ elif ctype in ("PyObject **", "void *"):
222
+ self.c_undefined = "NULL"
223
+ elif ctype == "double":
224
+ self.c_undefined = "-113.0"
225
+ elif ctype in ("uint8_t", "uint16_t", "uint32_t", "uint64_t"):
226
+ self.c_undefined = "239" # An arbitrary number
227
+ else:
228
+ assert False, "Unrecognized ctype: %r" % ctype
229
+
230
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
231
+ return visitor.visit_rprimitive(self)
232
+
233
+ def serialize(self) -> str:
234
+ return self.name
235
+
236
+ def __repr__(self) -> str:
237
+ return "<RPrimitive %s>" % self.name
238
+
239
+ def __eq__(self, other: object) -> bool:
240
+ return isinstance(other, RPrimitive) and other.name == self.name
241
+
242
+ def __hash__(self) -> int:
243
+ return hash(self.name)
244
+
245
+
246
+ # NOTE: All the supported instances of RPrimitive are defined
247
+ # below. Use these instead of creating new instances.
248
+
249
+ # Used to represent arbitrary objects and dynamically typed (Any)
250
+ # values. There are various ops that let you perform generic, runtime
251
+ # checked operations on these (that match Python semantics). See the
252
+ # ops in mypyc.primitives.misc_ops, including py_getattr_op,
253
+ # py_call_op, and many others.
254
+ #
255
+ # If there is no more specific RType available for some value, we fall
256
+ # back to using this type.
257
+ #
258
+ # NOTE: Even though this is very flexible, this type should be used as
259
+ # little as possible, as generic ops are typically slow. Other types,
260
+ # including other primitive types and RInstance, are usually much
261
+ # faster.
262
+ object_rprimitive: Final = RPrimitive("builtins.object", is_unboxed=False, is_refcounted=True)
263
+
264
+ # represents a low level pointer of an object
265
+ object_pointer_rprimitive: Final = RPrimitive(
266
+ "object_ptr", is_unboxed=False, is_refcounted=False, ctype="PyObject **"
267
+ )
268
+
269
+ # Arbitrary-precision integer (corresponds to Python 'int'). Small
270
+ # enough values are stored unboxed, while large integers are
271
+ # represented as a tagged pointer to a Python 'int' PyObject. The
272
+ # lowest bit is used as the tag to decide whether it is a signed
273
+ # unboxed value (shifted left by one) or a PyObject * pointing to an
274
+ # 'int' object. Pointers have the least significant bit set.
275
+ #
276
+ # The undefined/error value is the null pointer (1 -- only the least
277
+ # significant bit is set)).
278
+ #
279
+ # This cannot represent a subclass of int. An instance of a subclass
280
+ # of int is coerced to the corresponding 'int' value.
281
+ int_rprimitive: Final = RPrimitive(
282
+ "builtins.int", is_unboxed=True, is_refcounted=True, ctype="CPyTagged"
283
+ )
284
+
285
+ # An unboxed integer. The representation is the same as for unboxed
286
+ # int_rprimitive (shifted left by one). These can be used when an
287
+ # integer is known to be small enough to fit size_t (CPyTagged).
288
+ short_int_rprimitive: Final = RPrimitive(
289
+ "short_int", is_unboxed=True, is_refcounted=False, ctype="CPyTagged"
290
+ )
291
+
292
+ # Low level integer types (correspond to C integer types)
293
+
294
+ int16_rprimitive: Final = RPrimitive(
295
+ "i16",
296
+ is_unboxed=True,
297
+ is_refcounted=False,
298
+ is_native_int=True,
299
+ is_signed=True,
300
+ ctype="int16_t",
301
+ size=2,
302
+ error_overlap=True,
303
+ )
304
+ int32_rprimitive: Final = RPrimitive(
305
+ "i32",
306
+ is_unboxed=True,
307
+ is_refcounted=False,
308
+ is_native_int=True,
309
+ is_signed=True,
310
+ ctype="int32_t",
311
+ size=4,
312
+ error_overlap=True,
313
+ )
314
+ int64_rprimitive: Final = RPrimitive(
315
+ "i64",
316
+ is_unboxed=True,
317
+ is_refcounted=False,
318
+ is_native_int=True,
319
+ is_signed=True,
320
+ ctype="int64_t",
321
+ size=8,
322
+ error_overlap=True,
323
+ )
324
+ uint8_rprimitive: Final = RPrimitive(
325
+ "u8",
326
+ is_unboxed=True,
327
+ is_refcounted=False,
328
+ is_native_int=True,
329
+ is_signed=False,
330
+ ctype="uint8_t",
331
+ size=1,
332
+ error_overlap=True,
333
+ )
334
+
335
+ # The following unsigned native int types (u16, u32, u64) are not
336
+ # exposed to the user. They are for internal use within mypyc only.
337
+
338
+ u16_rprimitive: Final = RPrimitive(
339
+ "u16",
340
+ is_unboxed=True,
341
+ is_refcounted=False,
342
+ is_native_int=True,
343
+ is_signed=False,
344
+ ctype="uint16_t",
345
+ size=2,
346
+ error_overlap=True,
347
+ )
348
+ uint32_rprimitive: Final = RPrimitive(
349
+ "u32",
350
+ is_unboxed=True,
351
+ is_refcounted=False,
352
+ is_native_int=True,
353
+ is_signed=False,
354
+ ctype="uint32_t",
355
+ size=4,
356
+ error_overlap=True,
357
+ )
358
+ uint64_rprimitive: Final = RPrimitive(
359
+ "u64",
360
+ is_unboxed=True,
361
+ is_refcounted=False,
362
+ is_native_int=True,
363
+ is_signed=False,
364
+ ctype="uint64_t",
365
+ size=8,
366
+ error_overlap=True,
367
+ )
368
+
369
+ # The C 'int' type
370
+ c_int_rprimitive = int32_rprimitive
371
+
372
+ if IS_32_BIT_PLATFORM:
373
+ c_size_t_rprimitive = uint32_rprimitive
374
+ c_pyssize_t_rprimitive = RPrimitive(
375
+ "native_int",
376
+ is_unboxed=True,
377
+ is_refcounted=False,
378
+ is_native_int=True,
379
+ is_signed=True,
380
+ ctype="int32_t",
381
+ size=4,
382
+ )
383
+ else:
384
+ c_size_t_rprimitive = uint64_rprimitive
385
+ c_pyssize_t_rprimitive = RPrimitive(
386
+ "native_int",
387
+ is_unboxed=True,
388
+ is_refcounted=False,
389
+ is_native_int=True,
390
+ is_signed=True,
391
+ ctype="int64_t",
392
+ size=8,
393
+ )
394
+
395
+ # Untyped pointer, represented as integer in the C backend
396
+ pointer_rprimitive: Final = RPrimitive("ptr", is_unboxed=True, is_refcounted=False, ctype="CPyPtr")
397
+
398
+ # Untyped pointer, represented as void * in the C backend
399
+ c_pointer_rprimitive: Final = RPrimitive(
400
+ "c_ptr", is_unboxed=False, is_refcounted=False, ctype="void *"
401
+ )
402
+
403
+ # The type corresponding to mypyc.common.BITMAP_TYPE
404
+ bitmap_rprimitive: Final = uint32_rprimitive
405
+
406
+ # Floats are represent as 'float' PyObject * values. (In the future
407
+ # we'll likely switch to a more efficient, unboxed representation.)
408
+ float_rprimitive: Final = RPrimitive(
409
+ "builtins.float",
410
+ is_unboxed=True,
411
+ is_refcounted=False,
412
+ ctype="double",
413
+ size=8,
414
+ error_overlap=True,
415
+ )
416
+
417
+ # An unboxed Python bool value. This actually has three possible values
418
+ # (0 -> False, 1 -> True, 2 -> error). If you only need True/False, use
419
+ # bit_rprimitive instead.
420
+ bool_rprimitive: Final = RPrimitive(
421
+ "builtins.bool", is_unboxed=True, is_refcounted=False, ctype="char", size=1
422
+ )
423
+
424
+ # A low-level boolean value with two possible values: 0 and 1. Any
425
+ # other value results in undefined behavior. Undefined or error values
426
+ # are not supported.
427
+ bit_rprimitive: Final = RPrimitive(
428
+ "bit", is_unboxed=True, is_refcounted=False, ctype="char", size=1
429
+ )
430
+
431
+ # The 'None' value. The possible values are 0 -> None and 2 -> error.
432
+ none_rprimitive: Final = RPrimitive(
433
+ "builtins.None", is_unboxed=True, is_refcounted=False, ctype="char", size=1
434
+ )
435
+
436
+ # Python list object (or an instance of a subclass of list).
437
+ list_rprimitive: Final = RPrimitive("builtins.list", is_unboxed=False, is_refcounted=True)
438
+
439
+ # Python dict object (or an instance of a subclass of dict).
440
+ dict_rprimitive: Final = RPrimitive("builtins.dict", is_unboxed=False, is_refcounted=True)
441
+
442
+ # Python set object (or an instance of a subclass of set).
443
+ set_rprimitive: Final = RPrimitive("builtins.set", is_unboxed=False, is_refcounted=True)
444
+
445
+ # Python str object. At the C layer, str is referred to as unicode
446
+ # (PyUnicode).
447
+ str_rprimitive: Final = RPrimitive("builtins.str", is_unboxed=False, is_refcounted=True)
448
+
449
+ # Python bytes object.
450
+ bytes_rprimitive: Final = RPrimitive("builtins.bytes", is_unboxed=False, is_refcounted=True)
451
+
452
+ # Tuple of an arbitrary length (corresponds to Tuple[t, ...], with
453
+ # explicit '...').
454
+ tuple_rprimitive: Final = RPrimitive("builtins.tuple", is_unboxed=False, is_refcounted=True)
455
+
456
+ # Python range object.
457
+ range_rprimitive: Final = RPrimitive("builtins.range", is_unboxed=False, is_refcounted=True)
458
+
459
+
460
+ def is_tagged(rtype: RType) -> bool:
461
+ return rtype is int_rprimitive or rtype is short_int_rprimitive
462
+
463
+
464
+ def is_int_rprimitive(rtype: RType) -> bool:
465
+ return rtype is int_rprimitive
466
+
467
+
468
+ def is_short_int_rprimitive(rtype: RType) -> bool:
469
+ return rtype is short_int_rprimitive
470
+
471
+
472
+ def is_int16_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
473
+ return rtype is int16_rprimitive
474
+
475
+
476
+ def is_int32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
477
+ return rtype is int32_rprimitive or (
478
+ rtype is c_pyssize_t_rprimitive and rtype._ctype == "int32_t"
479
+ )
480
+
481
+
482
+ def is_int64_rprimitive(rtype: RType) -> bool:
483
+ return rtype is int64_rprimitive or (
484
+ rtype is c_pyssize_t_rprimitive and rtype._ctype == "int64_t"
485
+ )
486
+
487
+
488
+ def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]:
489
+ return (
490
+ is_int64_rprimitive(rtype)
491
+ or is_int32_rprimitive(rtype)
492
+ or is_int16_rprimitive(rtype)
493
+ or is_uint8_rprimitive(rtype)
494
+ )
495
+
496
+
497
+ def is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:
498
+ return rtype is uint8_rprimitive
499
+
500
+
501
+ def is_uint32_rprimitive(rtype: RType) -> bool:
502
+ return rtype is uint32_rprimitive
503
+
504
+
505
+ def is_uint64_rprimitive(rtype: RType) -> bool:
506
+ return rtype is uint64_rprimitive
507
+
508
+
509
+ def is_c_py_ssize_t_rprimitive(rtype: RType) -> bool:
510
+ return rtype is c_pyssize_t_rprimitive
511
+
512
+
513
+ def is_pointer_rprimitive(rtype: RType) -> bool:
514
+ return rtype is pointer_rprimitive
515
+
516
+
517
+ def is_float_rprimitive(rtype: RType) -> bool:
518
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.float"
519
+
520
+
521
+ def is_bool_rprimitive(rtype: RType) -> bool:
522
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bool"
523
+
524
+
525
+ def is_bit_rprimitive(rtype: RType) -> bool:
526
+ return isinstance(rtype, RPrimitive) and rtype.name == "bit"
527
+
528
+
529
+ def is_object_rprimitive(rtype: RType) -> bool:
530
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.object"
531
+
532
+
533
+ def is_none_rprimitive(rtype: RType) -> bool:
534
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.None"
535
+
536
+
537
+ def is_list_rprimitive(rtype: RType) -> bool:
538
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.list"
539
+
540
+
541
+ def is_dict_rprimitive(rtype: RType) -> bool:
542
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.dict"
543
+
544
+
545
+ def is_set_rprimitive(rtype: RType) -> bool:
546
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.set"
547
+
548
+
549
+ def is_str_rprimitive(rtype: RType) -> bool:
550
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.str"
551
+
552
+
553
+ def is_bytes_rprimitive(rtype: RType) -> bool:
554
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytes"
555
+
556
+
557
+ def is_tuple_rprimitive(rtype: RType) -> bool:
558
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.tuple"
559
+
560
+
561
+ def is_range_rprimitive(rtype: RType) -> bool:
562
+ return isinstance(rtype, RPrimitive) and rtype.name == "builtins.range"
563
+
564
+
565
+ def is_sequence_rprimitive(rtype: RType) -> bool:
566
+ return isinstance(rtype, RPrimitive) and (
567
+ is_list_rprimitive(rtype) or is_tuple_rprimitive(rtype) or is_str_rprimitive(rtype)
568
+ )
569
+
570
+
571
+ class TupleNameVisitor(RTypeVisitor[str]):
572
+ """Produce a tuple name based on the concrete representations of types."""
573
+
574
+ def visit_rinstance(self, t: RInstance) -> str:
575
+ return "O"
576
+
577
+ def visit_runion(self, t: RUnion) -> str:
578
+ return "O"
579
+
580
+ def visit_rprimitive(self, t: RPrimitive) -> str:
581
+ if t._ctype == "CPyTagged":
582
+ return "I"
583
+ elif t._ctype == "char":
584
+ return "C"
585
+ elif t._ctype == "int64_t":
586
+ return "8" # "8 byte integer"
587
+ elif t._ctype == "int32_t":
588
+ return "4" # "4 byte integer"
589
+ elif t._ctype == "int16_t":
590
+ return "2" # "2 byte integer"
591
+ elif t._ctype == "uint8_t":
592
+ return "U1" # "1 byte unsigned integer"
593
+ elif t._ctype == "double":
594
+ return "F"
595
+ assert not t.is_unboxed, f"{t} unexpected unboxed type"
596
+ return "O"
597
+
598
+ def visit_rtuple(self, t: RTuple) -> str:
599
+ parts = [elem.accept(self) for elem in t.types]
600
+ return "T{}{}".format(len(parts), "".join(parts))
601
+
602
+ def visit_rstruct(self, t: RStruct) -> str:
603
+ assert False, "RStruct not supported in tuple"
604
+
605
+ def visit_rarray(self, t: RArray) -> str:
606
+ assert False, "RArray not supported in tuple"
607
+
608
+ def visit_rvoid(self, t: RVoid) -> str:
609
+ assert False, "rvoid in tuple?"
610
+
611
+
612
+ class RTuple(RType):
613
+ """Fixed-length unboxed tuple (represented as a C struct).
614
+
615
+ These are used to represent mypy TupleType values (fixed-length
616
+ Python tuples). Since this is unboxed, the identity of a tuple
617
+ object is not preserved within compiled code. If the identity of a
618
+ tuple is important, or there is a need to have multiple references
619
+ to a single tuple object, a variable-length tuple should be used
620
+ (tuple_rprimitive or Tuple[T, ...] with explicit '...'), as they
621
+ are boxed.
622
+
623
+ These aren't immutable. However, user code won't be able to mutate
624
+ individual tuple items.
625
+ """
626
+
627
+ is_unboxed = True
628
+
629
+ def __init__(self, types: list[RType]) -> None:
630
+ self.name = "tuple"
631
+ self.types = tuple(types)
632
+ self.is_refcounted = any(t.is_refcounted for t in self.types)
633
+ # Generate a unique id which is used in naming corresponding C identifiers.
634
+ # This is necessary since C does not have anonymous structural type equivalence
635
+ # in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool].
636
+ self.unique_id = self.accept(TupleNameVisitor())
637
+ # Nominally the max c length is 31 chars, but I'm not honestly worried about this.
638
+ self.struct_name = f"tuple_{self.unique_id}"
639
+ self._ctype = f"{self.struct_name}"
640
+ self.error_overlap = all(t.error_overlap for t in self.types) and bool(self.types)
641
+
642
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
643
+ return visitor.visit_rtuple(self)
644
+
645
+ def __str__(self) -> str:
646
+ return "tuple[%s]" % ", ".join(str(typ) for typ in self.types)
647
+
648
+ def __repr__(self) -> str:
649
+ return "<RTuple %s>" % ", ".join(repr(typ) for typ in self.types)
650
+
651
+ def __eq__(self, other: object) -> bool:
652
+ return isinstance(other, RTuple) and self.types == other.types
653
+
654
+ def __hash__(self) -> int:
655
+ return hash((self.name, self.types))
656
+
657
+ def serialize(self) -> JsonDict:
658
+ types = [x.serialize() for x in self.types]
659
+ return {".class": "RTuple", "types": types}
660
+
661
+ @classmethod
662
+ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTuple:
663
+ types = [deserialize_type(t, ctx) for t in data["types"]]
664
+ return RTuple(types)
665
+
666
+
667
+ # Exception tuple: (exception class, exception instance, traceback object)
668
+ exc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive])
669
+
670
+ # Dictionary iterator tuple: (should continue, internal offset, key, value)
671
+ # See mypyc.irbuild.for_helpers.ForDictionaryCommon for more details.
672
+ dict_next_rtuple_pair = RTuple(
673
+ [bool_rprimitive, short_int_rprimitive, object_rprimitive, object_rprimitive]
674
+ )
675
+ # Same as above but just for key or value.
676
+ dict_next_rtuple_single = RTuple([bool_rprimitive, short_int_rprimitive, object_rprimitive])
677
+
678
+
679
+ def compute_rtype_alignment(typ: RType) -> int:
680
+ """Compute alignment of a given type based on platform alignment rule"""
681
+ platform_alignment = PLATFORM_SIZE
682
+ if isinstance(typ, RPrimitive):
683
+ return typ.size
684
+ elif isinstance(typ, RInstance):
685
+ return platform_alignment
686
+ elif isinstance(typ, RUnion):
687
+ return platform_alignment
688
+ elif isinstance(typ, RArray):
689
+ return compute_rtype_alignment(typ.item_type)
690
+ else:
691
+ if isinstance(typ, RTuple):
692
+ items = list(typ.types)
693
+ elif isinstance(typ, RStruct):
694
+ items = typ.types
695
+ else:
696
+ assert False, "invalid rtype for computing alignment"
697
+ max_alignment = max(compute_rtype_alignment(item) for item in items)
698
+ return max_alignment
699
+
700
+
701
+ def compute_rtype_size(typ: RType) -> int:
702
+ """Compute unaligned size of rtype"""
703
+ if isinstance(typ, RPrimitive):
704
+ return typ.size
705
+ elif isinstance(typ, RTuple):
706
+ return compute_aligned_offsets_and_size(list(typ.types))[1]
707
+ elif isinstance(typ, RUnion):
708
+ return PLATFORM_SIZE
709
+ elif isinstance(typ, RStruct):
710
+ return compute_aligned_offsets_and_size(typ.types)[1]
711
+ elif isinstance(typ, RInstance):
712
+ return PLATFORM_SIZE
713
+ elif isinstance(typ, RArray):
714
+ alignment = compute_rtype_alignment(typ)
715
+ aligned_size = (compute_rtype_size(typ.item_type) + (alignment - 1)) & ~(alignment - 1)
716
+ return aligned_size * typ.length
717
+ else:
718
+ assert False, "invalid rtype for computing size"
719
+
720
+
721
+ def compute_aligned_offsets_and_size(types: list[RType]) -> tuple[list[int], int]:
722
+ """Compute offsets and total size of a list of types after alignment
723
+
724
+ Note that the types argument are types of values that are stored
725
+ sequentially with platform default alignment.
726
+ """
727
+ unaligned_sizes = [compute_rtype_size(typ) for typ in types]
728
+ alignments = [compute_rtype_alignment(typ) for typ in types]
729
+
730
+ current_offset = 0
731
+ offsets = []
732
+ final_size = 0
733
+ for i in range(len(unaligned_sizes)):
734
+ offsets.append(current_offset)
735
+ if i + 1 < len(unaligned_sizes):
736
+ cur_size = unaligned_sizes[i]
737
+ current_offset += cur_size
738
+ next_alignment = alignments[i + 1]
739
+ # compute aligned offset,
740
+ # check https://en.wikipedia.org/wiki/Data_structure_alignment for more information
741
+ current_offset = (current_offset + (next_alignment - 1)) & -next_alignment
742
+ else:
743
+ struct_alignment = max(alignments)
744
+ final_size = current_offset + unaligned_sizes[i]
745
+ final_size = (final_size + (struct_alignment - 1)) & -struct_alignment
746
+ return offsets, final_size
747
+
748
+
749
+ class RStruct(RType):
750
+ """C struct type"""
751
+
752
+ def __init__(self, name: str, names: list[str], types: list[RType]) -> None:
753
+ self.name = name
754
+ self.names = names
755
+ self.types = types
756
+ # generate dummy names
757
+ if len(self.names) < len(self.types):
758
+ for i in range(len(self.types) - len(self.names)):
759
+ self.names.append("_item" + str(i))
760
+ self.offsets, self.size = compute_aligned_offsets_and_size(types)
761
+ self._ctype = name
762
+
763
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
764
+ return visitor.visit_rstruct(self)
765
+
766
+ def __str__(self) -> str:
767
+ # if not tuple(unnamed structs)
768
+ return "{}{{{}}}".format(
769
+ self.name,
770
+ ", ".join(name + ":" + str(typ) for name, typ in zip(self.names, self.types)),
771
+ )
772
+
773
+ def __repr__(self) -> str:
774
+ return "<RStruct {}{{{}}}>".format(
775
+ self.name,
776
+ ", ".join(name + ":" + repr(typ) for name, typ in zip(self.names, self.types)),
777
+ )
778
+
779
+ def __eq__(self, other: object) -> bool:
780
+ return (
781
+ isinstance(other, RStruct)
782
+ and self.name == other.name
783
+ and self.names == other.names
784
+ and self.types == other.types
785
+ )
786
+
787
+ def __hash__(self) -> int:
788
+ return hash((self.name, tuple(self.names), tuple(self.types)))
789
+
790
+ def serialize(self) -> JsonDict:
791
+ assert False
792
+
793
+ @classmethod
794
+ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RStruct:
795
+ assert False
796
+
797
+
798
+ class RInstance(RType):
799
+ """Instance of user-defined class (compiled to C extension class).
800
+
801
+ The runtime representation is 'PyObject *', and these are always
802
+ boxed and thus reference-counted.
803
+
804
+ These support fast method calls and fast attribute access using
805
+ vtables, and they usually use a dict-free, struct-based
806
+ representation of attributes. Method calls and attribute access
807
+ can skip the vtable if we know that there is no overriding.
808
+
809
+ These are also sometimes called 'native' types, since these have
810
+ the most efficient representation and ops (along with certain
811
+ RPrimitive types and RTuple).
812
+ """
813
+
814
+ is_unboxed = False
815
+
816
+ def __init__(self, class_ir: ClassIR) -> None:
817
+ # name is used for formatting the name in messages and debug output
818
+ # so we want the fullname for precision.
819
+ self.name = class_ir.fullname
820
+ self.class_ir = class_ir
821
+ self._ctype = "PyObject *"
822
+
823
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
824
+ return visitor.visit_rinstance(self)
825
+
826
+ def struct_name(self, names: NameGenerator) -> str:
827
+ return self.class_ir.struct_name(names)
828
+
829
+ def getter_index(self, name: str) -> int:
830
+ return self.class_ir.vtable_entry(name)
831
+
832
+ def setter_index(self, name: str) -> int:
833
+ return self.getter_index(name) + 1
834
+
835
+ def method_index(self, name: str) -> int:
836
+ return self.class_ir.vtable_entry(name)
837
+
838
+ def attr_type(self, name: str) -> RType:
839
+ return self.class_ir.attr_type(name)
840
+
841
+ def __repr__(self) -> str:
842
+ return "<RInstance %s>" % self.name
843
+
844
+ def __eq__(self, other: object) -> bool:
845
+ return isinstance(other, RInstance) and other.name == self.name
846
+
847
+ def __hash__(self) -> int:
848
+ return hash(self.name)
849
+
850
+ def serialize(self) -> str:
851
+ return self.name
852
+
853
+
854
+ class RUnion(RType):
855
+ """union[x, ..., y]"""
856
+
857
+ is_unboxed = False
858
+
859
+ def __init__(self, items: list[RType]) -> None:
860
+ self.name = "union"
861
+ self.items = items
862
+ self.items_set = frozenset(items)
863
+ self._ctype = "PyObject *"
864
+
865
+ @staticmethod
866
+ def make_simplified_union(items: list[RType]) -> RType:
867
+ """Return a normalized union that covers the given items.
868
+
869
+ Flatten nested unions and remove duplicate items.
870
+
871
+ Overlapping items are *not* simplified. For example,
872
+ [object, str] will not be simplified.
873
+ """
874
+ items = flatten_nested_unions(items)
875
+ assert items
876
+
877
+ unique_items = dict.fromkeys(items)
878
+ if len(unique_items) > 1:
879
+ return RUnion(list(unique_items))
880
+ else:
881
+ return next(iter(unique_items))
882
+
883
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
884
+ return visitor.visit_runion(self)
885
+
886
+ def __repr__(self) -> str:
887
+ return "<RUnion %s>" % ", ".join(str(item) for item in self.items)
888
+
889
+ def __str__(self) -> str:
890
+ return "union[%s]" % ", ".join(str(item) for item in self.items)
891
+
892
+ # We compare based on the set because order in a union doesn't matter
893
+ def __eq__(self, other: object) -> bool:
894
+ return isinstance(other, RUnion) and self.items_set == other.items_set
895
+
896
+ def __hash__(self) -> int:
897
+ return hash(("union", self.items_set))
898
+
899
+ def serialize(self) -> JsonDict:
900
+ types = [x.serialize() for x in self.items]
901
+ return {".class": "RUnion", "types": types}
902
+
903
+ @classmethod
904
+ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion:
905
+ types = [deserialize_type(t, ctx) for t in data["types"]]
906
+ return RUnion(types)
907
+
908
+
909
+ def flatten_nested_unions(types: list[RType]) -> list[RType]:
910
+ if not any(isinstance(t, RUnion) for t in types):
911
+ return types # Fast path
912
+
913
+ flat_items: list[RType] = []
914
+ for t in types:
915
+ if isinstance(t, RUnion):
916
+ flat_items.extend(flatten_nested_unions(t.items))
917
+ else:
918
+ flat_items.append(t)
919
+ return flat_items
920
+
921
+
922
+ def optional_value_type(rtype: RType) -> RType | None:
923
+ """If rtype is the union of none_rprimitive and another type X, return X.
924
+
925
+ Otherwise return None.
926
+ """
927
+ if isinstance(rtype, RUnion) and len(rtype.items) == 2:
928
+ if rtype.items[0] == none_rprimitive:
929
+ return rtype.items[1]
930
+ elif rtype.items[1] == none_rprimitive:
931
+ return rtype.items[0]
932
+ return None
933
+
934
+
935
+ def is_optional_type(rtype: RType) -> bool:
936
+ """Is rtype an optional type with exactly two union items?"""
937
+ return optional_value_type(rtype) is not None
938
+
939
+
940
+ class RArray(RType):
941
+ """Fixed-length C array type (for example, int[5]).
942
+
943
+ Note that the implementation is a bit limited, and these can basically
944
+ be only used for local variables that are initialized in one location.
945
+ """
946
+
947
+ def __init__(self, item_type: RType, length: int) -> None:
948
+ self.item_type = item_type
949
+ # Number of items
950
+ self.length = length
951
+ self.is_refcounted = False
952
+
953
+ def accept(self, visitor: RTypeVisitor[T]) -> T:
954
+ return visitor.visit_rarray(self)
955
+
956
+ def __str__(self) -> str:
957
+ return f"{self.item_type}[{self.length}]"
958
+
959
+ def __repr__(self) -> str:
960
+ return f"<RArray {self.item_type!r}[{self.length}]>"
961
+
962
+ def __eq__(self, other: object) -> bool:
963
+ return (
964
+ isinstance(other, RArray)
965
+ and self.item_type == other.item_type
966
+ and self.length == other.length
967
+ )
968
+
969
+ def __hash__(self) -> int:
970
+ return hash((self.item_type, self.length))
971
+
972
+ def serialize(self) -> JsonDict:
973
+ assert False
974
+
975
+ @classmethod
976
+ def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RArray:
977
+ assert False
978
+
979
+
980
+ PyObject = RStruct(
981
+ name="PyObject",
982
+ names=["ob_refcnt", "ob_type"],
983
+ types=[c_pyssize_t_rprimitive, pointer_rprimitive],
984
+ )
985
+
986
+ PyVarObject = RStruct(
987
+ name="PyVarObject", names=["ob_base", "ob_size"], types=[PyObject, c_pyssize_t_rprimitive]
988
+ )
989
+
990
+ setentry = RStruct(
991
+ name="setentry", names=["key", "hash"], types=[pointer_rprimitive, c_pyssize_t_rprimitive]
992
+ )
993
+
994
+ smalltable = RStruct(name="smalltable", names=[], types=[setentry] * 8)
995
+
996
+ PySetObject = RStruct(
997
+ name="PySetObject",
998
+ names=[
999
+ "ob_base",
1000
+ "fill",
1001
+ "used",
1002
+ "mask",
1003
+ "table",
1004
+ "hash",
1005
+ "finger",
1006
+ "smalltable",
1007
+ "weakreflist",
1008
+ ],
1009
+ types=[
1010
+ PyObject,
1011
+ c_pyssize_t_rprimitive,
1012
+ c_pyssize_t_rprimitive,
1013
+ c_pyssize_t_rprimitive,
1014
+ pointer_rprimitive,
1015
+ c_pyssize_t_rprimitive,
1016
+ c_pyssize_t_rprimitive,
1017
+ smalltable,
1018
+ pointer_rprimitive,
1019
+ ],
1020
+ )
1021
+
1022
+ PyListObject = RStruct(
1023
+ name="PyListObject",
1024
+ names=["ob_base", "ob_item", "allocated"],
1025
+ types=[PyVarObject, pointer_rprimitive, c_pyssize_t_rprimitive],
1026
+ )
1027
+
1028
+
1029
+ def check_native_int_range(rtype: RPrimitive, n: int) -> bool:
1030
+ """Is n within the range of a native, fixed-width int type?
1031
+
1032
+ Assume the type is a fixed-width int type.
1033
+ """
1034
+ if not rtype.is_signed:
1035
+ return 0 <= n < (1 << (8 * rtype.size))
1036
+ else:
1037
+ limit = 1 << (rtype.size * 8 - 1)
1038
+ return -limit <= n < limit
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/__init__.py ADDED
File without changes
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.py ADDED
@@ -0,0 +1,1457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Builder class used to transform a mypy AST to the IR form.
2
+
3
+ The IRBuilder class maintains transformation state and provides access
4
+ to various helpers used to implement the transform.
5
+
6
+ The top-level transform control logic is in mypyc.irbuild.main.
7
+
8
+ mypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypy
9
+ AST node type to code that actually does the bulk of the work. For
10
+ example, expressions are transformed in mypyc.irbuild.expression and
11
+ functions are transformed in mypyc.irbuild.function.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from contextlib import contextmanager
17
+ from typing import Any, Callable, Final, Iterator, Sequence, Union
18
+ from typing_extensions import overload
19
+
20
+ from mypy.build import Graph
21
+ from mypy.maptype import map_instance_to_supertype
22
+ from mypy.nodes import (
23
+ ARG_NAMED,
24
+ ARG_POS,
25
+ GDEF,
26
+ LDEF,
27
+ PARAM_SPEC_KIND,
28
+ TYPE_VAR_KIND,
29
+ TYPE_VAR_TUPLE_KIND,
30
+ ArgKind,
31
+ CallExpr,
32
+ Decorator,
33
+ Expression,
34
+ FuncDef,
35
+ IndexExpr,
36
+ IntExpr,
37
+ Lvalue,
38
+ MemberExpr,
39
+ MypyFile,
40
+ NameExpr,
41
+ OpExpr,
42
+ OverloadedFuncDef,
43
+ RefExpr,
44
+ StarExpr,
45
+ Statement,
46
+ SymbolNode,
47
+ TupleExpr,
48
+ TypeAlias,
49
+ TypeInfo,
50
+ TypeParam,
51
+ UnaryExpr,
52
+ Var,
53
+ )
54
+ from mypy.types import (
55
+ AnyType,
56
+ DeletedType,
57
+ Instance,
58
+ ProperType,
59
+ TupleType,
60
+ Type,
61
+ TypedDictType,
62
+ TypeOfAny,
63
+ UninhabitedType,
64
+ UnionType,
65
+ get_proper_type,
66
+ )
67
+ from mypy.util import module_prefix, split_target
68
+ from mypy.visitor import ExpressionVisitor, StatementVisitor
69
+ from mypyc.common import BITMAP_BITS, SELF_NAME, TEMP_ATTR_NAME
70
+ from mypyc.crash import catch_errors
71
+ from mypyc.errors import Errors
72
+ from mypyc.ir.class_ir import ClassIR, NonExtClassInfo
73
+ from mypyc.ir.func_ir import INVALID_FUNC_DEF, FuncDecl, FuncIR, FuncSignature, RuntimeArg
74
+ from mypyc.ir.ops import (
75
+ NAMESPACE_MODULE,
76
+ NAMESPACE_TYPE_VAR,
77
+ Assign,
78
+ BasicBlock,
79
+ Branch,
80
+ ComparisonOp,
81
+ GetAttr,
82
+ InitStatic,
83
+ Integer,
84
+ IntOp,
85
+ LoadStatic,
86
+ Op,
87
+ PrimitiveDescription,
88
+ RaiseStandardError,
89
+ Register,
90
+ SetAttr,
91
+ TupleGet,
92
+ Unreachable,
93
+ Value,
94
+ )
95
+ from mypyc.ir.rtypes import (
96
+ RInstance,
97
+ RTuple,
98
+ RType,
99
+ RUnion,
100
+ bitmap_rprimitive,
101
+ c_pyssize_t_rprimitive,
102
+ dict_rprimitive,
103
+ int_rprimitive,
104
+ is_float_rprimitive,
105
+ is_list_rprimitive,
106
+ is_none_rprimitive,
107
+ is_object_rprimitive,
108
+ is_tagged,
109
+ is_tuple_rprimitive,
110
+ none_rprimitive,
111
+ object_rprimitive,
112
+ str_rprimitive,
113
+ )
114
+ from mypyc.irbuild.context import FuncInfo, ImplicitClass
115
+ from mypyc.irbuild.ll_builder import LowLevelIRBuilder
116
+ from mypyc.irbuild.mapper import Mapper
117
+ from mypyc.irbuild.nonlocalcontrol import (
118
+ BaseNonlocalControl,
119
+ GeneratorNonlocalControl,
120
+ LoopNonlocalControl,
121
+ NonlocalControl,
122
+ )
123
+ from mypyc.irbuild.prebuildvisitor import PreBuildVisitor
124
+ from mypyc.irbuild.prepare import RegisterImplInfo
125
+ from mypyc.irbuild.targets import (
126
+ AssignmentTarget,
127
+ AssignmentTargetAttr,
128
+ AssignmentTargetIndex,
129
+ AssignmentTargetRegister,
130
+ AssignmentTargetTuple,
131
+ )
132
+ from mypyc.irbuild.util import bytes_from_str, is_constant
133
+ from mypyc.options import CompilerOptions
134
+ from mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_op
135
+ from mypyc.primitives.generic_ops import iter_op, next_op, py_setattr_op
136
+ from mypyc.primitives.list_ops import list_get_item_unsafe_op, list_pop_last, to_list
137
+ from mypyc.primitives.misc_ops import check_unpack_count_op, get_module_dict_op, import_op
138
+ from mypyc.primitives.registry import CFunctionDescription, function_ops
139
+
140
+ # These int binary operations can borrow their operands safely, since the
141
+ # primitives take this into consideration.
142
+ int_borrow_friendly_op: Final = {"+", "-", "==", "!=", "<", "<=", ">", ">="}
143
+
144
+
145
+ class IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]):
146
+ pass
147
+
148
+
149
+ class UnsupportedException(Exception):
150
+ pass
151
+
152
+
153
+ SymbolTarget = Union[AssignmentTargetRegister, AssignmentTargetAttr]
154
+
155
+
156
+ class IRBuilder:
157
+ def __init__(
158
+ self,
159
+ current_module: str,
160
+ types: dict[Expression, Type],
161
+ graph: Graph,
162
+ errors: Errors,
163
+ mapper: Mapper,
164
+ pbv: PreBuildVisitor,
165
+ visitor: IRVisitor,
166
+ options: CompilerOptions,
167
+ singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]],
168
+ ) -> None:
169
+ self.builder = LowLevelIRBuilder(errors, options)
170
+ self.builders = [self.builder]
171
+ self.symtables: list[dict[SymbolNode, SymbolTarget]] = [{}]
172
+ self.runtime_args: list[list[RuntimeArg]] = [[]]
173
+ self.function_name_stack: list[str] = []
174
+ self.class_ir_stack: list[ClassIR] = []
175
+ # Keep track of whether the next statement in a block is reachable
176
+ # or not, separately for each block nesting level
177
+ self.block_reachable_stack: list[bool] = [True]
178
+
179
+ self.current_module = current_module
180
+ self.mapper = mapper
181
+ self.types = types
182
+ self.graph = graph
183
+ self.ret_types: list[RType] = []
184
+ self.functions: list[FuncIR] = []
185
+ self.function_names: set[tuple[str | None, str]] = set()
186
+ self.classes: list[ClassIR] = []
187
+ self.final_names: list[tuple[str, RType]] = []
188
+ self.type_var_names: list[str] = []
189
+ self.callable_class_names: set[str] = set()
190
+ self.options = options
191
+
192
+ # These variables keep track of the number of lambdas, implicit indices, and implicit
193
+ # iterators instantiated so we avoid name conflicts. The indices and iterators are
194
+ # instantiated from for-loops.
195
+ self.lambda_counter = 0
196
+ self.temp_counter = 0
197
+
198
+ # These variables are populated from the first-pass PreBuildVisitor.
199
+ self.free_variables = pbv.free_variables
200
+ self.prop_setters = pbv.prop_setters
201
+ self.encapsulating_funcs = pbv.encapsulating_funcs
202
+ self.nested_fitems = pbv.nested_funcs.keys()
203
+ self.fdefs_to_decorators = pbv.funcs_to_decorators
204
+ self.module_import_groups = pbv.module_import_groups
205
+
206
+ self.singledispatch_impls = singledispatch_impls
207
+
208
+ self.visitor = visitor
209
+
210
+ # This list operates similarly to a function call stack for nested functions. Whenever a
211
+ # function definition begins to be generated, a FuncInfo instance is added to the stack,
212
+ # and information about that function (e.g. whether it is nested, its environment class to
213
+ # be generated) is stored in that FuncInfo instance. When the function is done being
214
+ # generated, its corresponding FuncInfo is popped off the stack.
215
+ self.fn_info = FuncInfo(INVALID_FUNC_DEF, "", "")
216
+ self.fn_infos: list[FuncInfo] = [self.fn_info]
217
+
218
+ # This list operates as a stack of constructs that modify the
219
+ # behavior of nonlocal control flow constructs.
220
+ self.nonlocal_control: list[NonlocalControl] = []
221
+
222
+ self.errors = errors
223
+ # Notionally a list of all of the modules imported by the
224
+ # module being compiled, but stored as an OrderedDict so we
225
+ # can also do quick lookups.
226
+ self.imports: dict[str, None] = {}
227
+
228
+ self.can_borrow = False
229
+
230
+ # High-level control
231
+
232
+ def set_module(self, module_name: str, module_path: str) -> None:
233
+ """Set the name and path of the current module.
234
+
235
+ This must be called before transforming any AST nodes.
236
+ """
237
+ self.module_name = module_name
238
+ self.module_path = module_path
239
+ self.builder.set_module(module_name, module_path)
240
+
241
+ @overload
242
+ def accept(self, node: Expression, *, can_borrow: bool = False) -> Value: ...
243
+
244
+ @overload
245
+ def accept(self, node: Statement) -> None: ...
246
+
247
+ def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> Value | None:
248
+ """Transform an expression or a statement.
249
+
250
+ If can_borrow is true, prefer to generate a borrowed reference.
251
+ Borrowed references are faster since they don't require reference count
252
+ manipulation, but they are only safe to use in specific contexts.
253
+ """
254
+ with self.catch_errors(node.line):
255
+ if isinstance(node, Expression):
256
+ old_can_borrow = self.can_borrow
257
+ self.can_borrow = can_borrow
258
+ try:
259
+ res = node.accept(self.visitor)
260
+ res = self.coerce(res, self.node_type(node), node.line)
261
+ # If we hit an error during compilation, we want to
262
+ # keep trying, so we can produce more error
263
+ # messages. Generate a temp of the right type to keep
264
+ # from causing more downstream trouble.
265
+ except UnsupportedException:
266
+ res = Register(self.node_type(node))
267
+ self.can_borrow = old_can_borrow
268
+ if not can_borrow:
269
+ self.flush_keep_alives()
270
+ return res
271
+ else:
272
+ try:
273
+ node.accept(self.visitor)
274
+ except UnsupportedException:
275
+ pass
276
+ return None
277
+
278
+ def flush_keep_alives(self) -> None:
279
+ self.builder.flush_keep_alives()
280
+
281
+ # Pass through methods for the most common low-level builder ops, for convenience.
282
+
283
+ def add(self, op: Op) -> Value:
284
+ return self.builder.add(op)
285
+
286
+ def goto(self, target: BasicBlock) -> None:
287
+ self.builder.goto(target)
288
+
289
+ def activate_block(self, block: BasicBlock) -> None:
290
+ self.builder.activate_block(block)
291
+
292
+ def goto_and_activate(self, block: BasicBlock) -> None:
293
+ self.builder.goto_and_activate(block)
294
+
295
+ def self(self) -> Register:
296
+ return self.builder.self()
297
+
298
+ def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
299
+ return self.builder.py_get_attr(obj, attr, line)
300
+
301
+ def load_str(self, value: str) -> Value:
302
+ return self.builder.load_str(value)
303
+
304
+ def load_bytes_from_str_literal(self, value: str) -> Value:
305
+ """Load bytes object from a string literal.
306
+
307
+ The literal characters of BytesExpr (the characters inside b'')
308
+ are stored in BytesExpr.value, whose type is 'str' not 'bytes'.
309
+ Thus we perform a special conversion here.
310
+ """
311
+ return self.builder.load_bytes(bytes_from_str(value))
312
+
313
+ def load_int(self, value: int) -> Value:
314
+ return self.builder.load_int(value)
315
+
316
+ def load_float(self, value: float) -> Value:
317
+ return self.builder.load_float(value)
318
+
319
+ def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value:
320
+ return self.builder.unary_op(lreg, expr_op, line)
321
+
322
+ def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
323
+ return self.builder.binary_op(lreg, rreg, expr_op, line)
324
+
325
+ def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value:
326
+ return self.builder.coerce(src, target_type, line, force, can_borrow=self.can_borrow)
327
+
328
+ def none_object(self) -> Value:
329
+ return self.builder.none_object()
330
+
331
+ def none(self) -> Value:
332
+ return self.builder.none()
333
+
334
+ def true(self) -> Value:
335
+ return self.builder.true()
336
+
337
+ def false(self) -> Value:
338
+ return self.builder.false()
339
+
340
+ def new_list_op(self, values: list[Value], line: int) -> Value:
341
+ return self.builder.new_list_op(values, line)
342
+
343
+ def new_set_op(self, values: list[Value], line: int) -> Value:
344
+ return self.builder.new_set_op(values, line)
345
+
346
+ def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
347
+ return self.builder.translate_is_op(lreg, rreg, expr_op, line)
348
+
349
+ def py_call(
350
+ self,
351
+ function: Value,
352
+ arg_values: list[Value],
353
+ line: int,
354
+ arg_kinds: list[ArgKind] | None = None,
355
+ arg_names: Sequence[str | None] | None = None,
356
+ ) -> Value:
357
+ return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names)
358
+
359
+ def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
360
+ self.builder.add_bool_branch(value, true, false)
361
+
362
+ def load_native_type_object(self, fullname: str) -> Value:
363
+ return self.builder.load_native_type_object(fullname)
364
+
365
+ def gen_method_call(
366
+ self,
367
+ base: Value,
368
+ name: str,
369
+ arg_values: list[Value],
370
+ result_type: RType | None,
371
+ line: int,
372
+ arg_kinds: list[ArgKind] | None = None,
373
+ arg_names: list[str | None] | None = None,
374
+ ) -> Value:
375
+ return self.builder.gen_method_call(
376
+ base, name, arg_values, result_type, line, arg_kinds, arg_names, self.can_borrow
377
+ )
378
+
379
+ def load_module(self, name: str) -> Value:
380
+ return self.builder.load_module(name)
381
+
382
+ def call_c(self, desc: CFunctionDescription, args: list[Value], line: int) -> Value:
383
+ return self.builder.call_c(desc, args, line)
384
+
385
+ def primitive_op(self, desc: PrimitiveDescription, args: list[Value], line: int) -> Value:
386
+ return self.builder.primitive_op(desc, args, line)
387
+
388
+ def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value:
389
+ return self.builder.int_op(type, lhs, rhs, op, line)
390
+
391
+ def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
392
+ return self.builder.compare_tuples(lhs, rhs, op, line)
393
+
394
+ def builtin_len(self, val: Value, line: int) -> Value:
395
+ return self.builder.builtin_len(val, line)
396
+
397
+ def new_tuple(self, items: list[Value], line: int) -> Value:
398
+ return self.builder.new_tuple(items, line)
399
+
400
+ # Helpers for IR building
401
+
402
+ def add_to_non_ext_dict(
403
+ self, non_ext: NonExtClassInfo, key: str, val: Value, line: int
404
+ ) -> None:
405
+ # Add an attribute entry into the class dict of a non-extension class.
406
+ key_unicode = self.load_str(key)
407
+ self.primitive_op(dict_set_item_op, [non_ext.dict, key_unicode, val], line)
408
+
409
+ def gen_import(self, id: str, line: int) -> None:
410
+ self.imports[id] = None
411
+
412
+ needs_import, out = BasicBlock(), BasicBlock()
413
+ self.check_if_module_loaded(id, line, needs_import, out)
414
+
415
+ self.activate_block(needs_import)
416
+ value = self.call_c(import_op, [self.load_str(id)], line)
417
+ self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE))
418
+ self.goto_and_activate(out)
419
+
420
+ def check_if_module_loaded(
421
+ self, id: str, line: int, needs_import: BasicBlock, out: BasicBlock
422
+ ) -> None:
423
+ """Generate code that checks if the module `id` has been loaded yet.
424
+
425
+ Arguments:
426
+ id: name of module to check if imported
427
+ line: line number that the import occurs on
428
+ needs_import: the BasicBlock that is run if the module has not been loaded yet
429
+ out: the BasicBlock that is run if the module has already been loaded"""
430
+ first_load = self.load_module(id)
431
+ comparison = self.translate_is_op(first_load, self.none_object(), "is not", line)
432
+ self.add_bool_branch(comparison, out, needs_import)
433
+
434
+ def get_module(self, module: str, line: int) -> Value:
435
+ # Python 3.7 has a nice 'PyImport_GetModule' function that we can't use :(
436
+ mod_dict = self.call_c(get_module_dict_op, [], line)
437
+ # Get module object from modules dict.
438
+ return self.primitive_op(dict_get_item_op, [mod_dict, self.load_str(module)], line)
439
+
440
+ def get_module_attr(self, module: str, attr: str, line: int) -> Value:
441
+ """Look up an attribute of a module without storing it in the local namespace.
442
+
443
+ For example, get_module_attr('typing', 'TypedDict', line) results in
444
+ the value of 'typing.TypedDict'.
445
+
446
+ Import the module if needed.
447
+ """
448
+ self.gen_import(module, line)
449
+ module_obj = self.get_module(module, line)
450
+ return self.py_get_attr(module_obj, attr, line)
451
+
452
+ def assign_if_null(self, target: Register, get_val: Callable[[], Value], line: int) -> None:
453
+ """If target is NULL, assign value produced by get_val to it."""
454
+ error_block, body_block = BasicBlock(), BasicBlock()
455
+ self.add(Branch(target, error_block, body_block, Branch.IS_ERROR))
456
+ self.activate_block(error_block)
457
+ self.add(Assign(target, self.coerce(get_val(), target.type, line)))
458
+ self.goto(body_block)
459
+ self.activate_block(body_block)
460
+
461
+ def assign_if_bitmap_unset(
462
+ self, target: Register, get_val: Callable[[], Value], index: int, line: int
463
+ ) -> None:
464
+ error_block, body_block = BasicBlock(), BasicBlock()
465
+ o = self.int_op(
466
+ bitmap_rprimitive,
467
+ self.builder.args[-1 - index // BITMAP_BITS],
468
+ Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),
469
+ IntOp.AND,
470
+ line,
471
+ )
472
+ b = self.add(ComparisonOp(o, Integer(0, bitmap_rprimitive), ComparisonOp.EQ))
473
+ self.add(Branch(b, error_block, body_block, Branch.BOOL))
474
+ self.activate_block(error_block)
475
+ self.add(Assign(target, self.coerce(get_val(), target.type, line)))
476
+ self.goto(body_block)
477
+ self.activate_block(body_block)
478
+
479
+ def maybe_add_implicit_return(self) -> None:
480
+ if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]):
481
+ self.add_implicit_return()
482
+ else:
483
+ self.add_implicit_unreachable()
484
+
485
+ def add_implicit_return(self) -> None:
486
+ block = self.builder.blocks[-1]
487
+ if not block.terminated:
488
+ retval = self.coerce(self.builder.none(), self.ret_types[-1], -1)
489
+ self.nonlocal_control[-1].gen_return(self, retval, self.fn_info.fitem.line)
490
+
491
+ def add_implicit_unreachable(self) -> None:
492
+ block = self.builder.blocks[-1]
493
+ if not block.terminated:
494
+ self.add(Unreachable())
495
+
496
+ def disallow_class_assignments(self, lvalues: list[Lvalue], line: int) -> None:
497
+ # Some best-effort attempts to disallow assigning to class
498
+ # variables that aren't marked ClassVar, since we blatantly
499
+ # miscompile the interaction between instance and class
500
+ # variables.
501
+ for lvalue in lvalues:
502
+ if (
503
+ isinstance(lvalue, MemberExpr)
504
+ and isinstance(lvalue.expr, RefExpr)
505
+ and isinstance(lvalue.expr.node, TypeInfo)
506
+ ):
507
+ var = lvalue.expr.node[lvalue.name].node
508
+ if isinstance(var, Var) and not var.is_classvar:
509
+ self.error("Only class variables defined as ClassVar can be assigned to", line)
510
+
511
+ def non_function_scope(self) -> bool:
512
+ # Currently the stack always has at least two items: dummy and top-level.
513
+ return len(self.fn_infos) <= 2
514
+
515
+ def top_level_fn_info(self) -> FuncInfo | None:
516
+ if self.non_function_scope():
517
+ return None
518
+ return self.fn_infos[2]
519
+
520
+ def init_final_static(
521
+ self,
522
+ lvalue: Lvalue,
523
+ rvalue_reg: Value,
524
+ class_name: str | None = None,
525
+ *,
526
+ type_override: RType | None = None,
527
+ ) -> None:
528
+ assert isinstance(lvalue, NameExpr)
529
+ assert isinstance(lvalue.node, Var)
530
+ if lvalue.node.final_value is None:
531
+ if class_name is None:
532
+ name = lvalue.name
533
+ else:
534
+ name = f"{class_name}.{lvalue.name}"
535
+ assert name is not None, "Full name not set for variable"
536
+ coerced = self.coerce(rvalue_reg, type_override or self.node_type(lvalue), lvalue.line)
537
+ self.final_names.append((name, coerced.type))
538
+ self.add(InitStatic(coerced, name, self.module_name))
539
+
540
+ def load_final_static(
541
+ self, fullname: str, typ: RType, line: int, error_name: str | None = None
542
+ ) -> Value:
543
+ split_name = split_target(self.graph, fullname)
544
+ assert split_name is not None
545
+ module, name = split_name
546
+ return self.builder.load_static_checked(
547
+ typ,
548
+ name,
549
+ module,
550
+ line=line,
551
+ error_msg=f'value for final name "{error_name}" was not set',
552
+ )
553
+
554
+ def init_type_var(self, value: Value, name: str, line: int) -> None:
555
+ unique_name = name + "___" + str(line)
556
+ self.type_var_names.append(unique_name)
557
+ self.add(InitStatic(value, unique_name, self.module_name, namespace=NAMESPACE_TYPE_VAR))
558
+
559
+ def load_type_var(self, name: str, line: int) -> Value:
560
+ return self.add(
561
+ LoadStatic(
562
+ object_rprimitive,
563
+ name + "___" + str(line),
564
+ self.module_name,
565
+ namespace=NAMESPACE_TYPE_VAR,
566
+ )
567
+ )
568
+
569
+ def load_literal_value(self, val: int | str | bytes | float | complex | bool) -> Value:
570
+ """Load value of a final name, class-level attribute, or constant folded expression."""
571
+ if isinstance(val, bool):
572
+ if val:
573
+ return self.true()
574
+ else:
575
+ return self.false()
576
+ elif isinstance(val, int):
577
+ return self.builder.load_int(val)
578
+ elif isinstance(val, float):
579
+ return self.builder.load_float(val)
580
+ elif isinstance(val, str):
581
+ return self.builder.load_str(val)
582
+ elif isinstance(val, bytes):
583
+ return self.builder.load_bytes(val)
584
+ elif isinstance(val, complex):
585
+ return self.builder.load_complex(val)
586
+ else:
587
+ assert False, "Unsupported literal value"
588
+
589
+ def get_assignment_target(
590
+ self, lvalue: Lvalue, line: int = -1, *, for_read: bool = False
591
+ ) -> AssignmentTarget:
592
+ if line == -1:
593
+ line = lvalue.line
594
+ if isinstance(lvalue, NameExpr):
595
+ # If we are visiting a decorator, then the SymbolNode we really want to be looking at
596
+ # is the function that is decorated, not the entire Decorator node itself.
597
+ symbol = lvalue.node
598
+ if isinstance(symbol, Decorator):
599
+ symbol = symbol.func
600
+ if symbol is None:
601
+ # Semantic analyzer doesn't create ad-hoc Vars for special forms.
602
+ assert lvalue.is_special_form
603
+ symbol = Var(lvalue.name)
604
+ if not for_read and isinstance(symbol, Var) and symbol.is_cls:
605
+ self.error("Cannot assign to the first argument of classmethod", line)
606
+ if lvalue.kind == LDEF:
607
+ if symbol not in self.symtables[-1]:
608
+ if isinstance(symbol, Var) and not isinstance(symbol.type, DeletedType):
609
+ reg_type = self.type_to_rtype(symbol.type)
610
+ else:
611
+ reg_type = self.node_type(lvalue)
612
+ # If the function is a generator function, then first define a new variable
613
+ # in the current function's environment class. Next, define a target that
614
+ # refers to the newly defined variable in that environment class. Add the
615
+ # target to the table containing class environment variables, as well as the
616
+ # current environment.
617
+ if self.fn_info.is_generator:
618
+ return self.add_var_to_env_class(
619
+ symbol, reg_type, self.fn_info.generator_class, reassign=False
620
+ )
621
+
622
+ # Otherwise define a new local variable.
623
+ return self.add_local_reg(symbol, reg_type)
624
+ else:
625
+ # Assign to a previously defined variable.
626
+ return self.lookup(symbol)
627
+ elif lvalue.kind == GDEF:
628
+ globals_dict = self.load_globals_dict()
629
+ name = self.load_str(lvalue.name)
630
+ return AssignmentTargetIndex(globals_dict, name)
631
+ else:
632
+ assert False, lvalue.kind
633
+ elif isinstance(lvalue, IndexExpr):
634
+ # Indexed assignment x[y] = e
635
+ base = self.accept(lvalue.base)
636
+ index = self.accept(lvalue.index)
637
+ return AssignmentTargetIndex(base, index)
638
+ elif isinstance(lvalue, MemberExpr):
639
+ # Attribute assignment x.y = e
640
+ can_borrow = self.is_native_attr_ref(lvalue)
641
+ obj = self.accept(lvalue.expr, can_borrow=can_borrow)
642
+ return AssignmentTargetAttr(obj, lvalue.name, can_borrow=can_borrow)
643
+ elif isinstance(lvalue, TupleExpr):
644
+ # Multiple assignment a, ..., b = e
645
+ star_idx: int | None = None
646
+ lvalues = []
647
+ for idx, item in enumerate(lvalue.items):
648
+ targ = self.get_assignment_target(item)
649
+ lvalues.append(targ)
650
+ if isinstance(item, StarExpr):
651
+ if star_idx is not None:
652
+ self.error("Two starred expressions in assignment", line)
653
+ star_idx = idx
654
+
655
+ return AssignmentTargetTuple(lvalues, star_idx)
656
+
657
+ elif isinstance(lvalue, StarExpr):
658
+ return self.get_assignment_target(lvalue.expr)
659
+
660
+ assert False, "Unsupported lvalue: %r" % lvalue
661
+
662
+ def read(
663
+ self, target: Value | AssignmentTarget, line: int = -1, can_borrow: bool = False
664
+ ) -> Value:
665
+ if isinstance(target, Value):
666
+ return target
667
+ if isinstance(target, AssignmentTargetRegister):
668
+ return target.register
669
+ if isinstance(target, AssignmentTargetIndex):
670
+ reg = self.gen_method_call(
671
+ target.base, "__getitem__", [target.index], target.type, line
672
+ )
673
+ if reg is not None:
674
+ return reg
675
+ assert False, target.base.type
676
+ if isinstance(target, AssignmentTargetAttr):
677
+ if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class:
678
+ borrow = can_borrow and target.can_borrow
679
+ return self.add(GetAttr(target.obj, target.attr, line, borrow=borrow))
680
+ else:
681
+ return self.py_get_attr(target.obj, target.attr, line)
682
+
683
+ assert False, "Unsupported lvalue: %r" % target
684
+
685
+ def assign(self, target: Register | AssignmentTarget, rvalue_reg: Value, line: int) -> None:
686
+ if isinstance(target, Register):
687
+ self.add(Assign(target, self.coerce_rvalue(rvalue_reg, target.type, line)))
688
+ elif isinstance(target, AssignmentTargetRegister):
689
+ rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)
690
+ self.add(Assign(target.register, rvalue_reg))
691
+ elif isinstance(target, AssignmentTargetAttr):
692
+ if isinstance(target.obj_type, RInstance):
693
+ rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)
694
+ self.add(SetAttr(target.obj, target.attr, rvalue_reg, line))
695
+ else:
696
+ key = self.load_str(target.attr)
697
+ boxed_reg = self.builder.box(rvalue_reg)
698
+ self.primitive_op(py_setattr_op, [target.obj, key, boxed_reg], line)
699
+ elif isinstance(target, AssignmentTargetIndex):
700
+ target_reg2 = self.gen_method_call(
701
+ target.base, "__setitem__", [target.index, rvalue_reg], None, line
702
+ )
703
+ assert target_reg2 is not None, target.base.type
704
+ elif isinstance(target, AssignmentTargetTuple):
705
+ if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None:
706
+ rtypes = rvalue_reg.type.types
707
+ assert len(rtypes) == len(target.items)
708
+ for i in range(len(rtypes)):
709
+ item_value = self.add(TupleGet(rvalue_reg, i, line))
710
+ self.assign(target.items[i], item_value, line)
711
+ elif (
712
+ is_list_rprimitive(rvalue_reg.type) or is_tuple_rprimitive(rvalue_reg.type)
713
+ ) and target.star_idx is None:
714
+ self.process_sequence_assignment(target, rvalue_reg, line)
715
+ else:
716
+ self.process_iterator_tuple_assignment(target, rvalue_reg, line)
717
+ else:
718
+ assert False, "Unsupported assignment target"
719
+
720
+ def coerce_rvalue(self, rvalue: Value, rtype: RType, line: int) -> Value:
721
+ if is_float_rprimitive(rtype) and is_tagged(rvalue.type):
722
+ typename = rvalue.type.short_name()
723
+ if typename == "short_int":
724
+ typename = "int"
725
+ self.error(
726
+ "Incompatible value representations in assignment "
727
+ + f'(expression has type "{typename}", variable has type "float")',
728
+ line,
729
+ )
730
+ return self.coerce(rvalue, rtype, line)
731
+
732
+ def process_sequence_assignment(
733
+ self, target: AssignmentTargetTuple, rvalue: Value, line: int
734
+ ) -> None:
735
+ """Process assignment like 'x, y = s', where s is a variable-length list or tuple."""
736
+ # Check the length of sequence.
737
+ expected_len = Integer(len(target.items), c_pyssize_t_rprimitive)
738
+ self.builder.call_c(check_unpack_count_op, [rvalue, expected_len], line)
739
+
740
+ # Read sequence items.
741
+ values = []
742
+ for i in range(len(target.items)):
743
+ item = target.items[i]
744
+ index = self.builder.load_int(i)
745
+ if is_list_rprimitive(rvalue.type):
746
+ item_value = self.call_c(list_get_item_unsafe_op, [rvalue, index], line)
747
+ else:
748
+ item_value = self.builder.gen_method_call(
749
+ rvalue, "__getitem__", [index], item.type, line
750
+ )
751
+ values.append(item_value)
752
+
753
+ # Assign sequence items to the target lvalues.
754
+ for lvalue, value in zip(target.items, values):
755
+ self.assign(lvalue, value, line)
756
+
757
+ def process_iterator_tuple_assignment_helper(
758
+ self, litem: AssignmentTarget, ritem: Value, line: int
759
+ ) -> None:
760
+ error_block, ok_block = BasicBlock(), BasicBlock()
761
+ self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
762
+
763
+ self.activate_block(error_block)
764
+ self.add(
765
+ RaiseStandardError(RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line)
766
+ )
767
+ self.add(Unreachable())
768
+
769
+ self.activate_block(ok_block)
770
+ self.assign(litem, ritem, line)
771
+
772
+ def process_iterator_tuple_assignment(
773
+ self, target: AssignmentTargetTuple, rvalue_reg: Value, line: int
774
+ ) -> None:
775
+ iterator = self.primitive_op(iter_op, [rvalue_reg], line)
776
+
777
+ # This may be the whole lvalue list if there is no starred value
778
+ split_idx = target.star_idx if target.star_idx is not None else len(target.items)
779
+
780
+ # Assign values before the first starred value
781
+ for litem in target.items[:split_idx]:
782
+ ritem = self.call_c(next_op, [iterator], line)
783
+ error_block, ok_block = BasicBlock(), BasicBlock()
784
+ self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
785
+
786
+ self.activate_block(error_block)
787
+ self.add(
788
+ RaiseStandardError(
789
+ RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line
790
+ )
791
+ )
792
+ self.add(Unreachable())
793
+
794
+ self.activate_block(ok_block)
795
+
796
+ self.assign(litem, ritem, line)
797
+
798
+ # Assign the starred value and all values after it
799
+ if target.star_idx is not None:
800
+ post_star_vals = target.items[split_idx + 1 :]
801
+ iter_list = self.primitive_op(to_list, [iterator], line)
802
+ iter_list_len = self.builtin_len(iter_list, line)
803
+ post_star_len = Integer(len(post_star_vals))
804
+ condition = self.binary_op(post_star_len, iter_list_len, "<=", line)
805
+
806
+ error_block, ok_block = BasicBlock(), BasicBlock()
807
+ self.add(Branch(condition, ok_block, error_block, Branch.BOOL))
808
+
809
+ self.activate_block(error_block)
810
+ self.add(
811
+ RaiseStandardError(
812
+ RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line
813
+ )
814
+ )
815
+ self.add(Unreachable())
816
+
817
+ self.activate_block(ok_block)
818
+
819
+ for litem in reversed(post_star_vals):
820
+ ritem = self.primitive_op(list_pop_last, [iter_list], line)
821
+ self.assign(litem, ritem, line)
822
+
823
+ # Assign the starred value
824
+ self.assign(target.items[target.star_idx], iter_list, line)
825
+
826
+ # There is no starred value, so check if there are extra values in rhs that
827
+ # have not been assigned.
828
+ else:
829
+ extra = self.call_c(next_op, [iterator], line)
830
+ error_block, ok_block = BasicBlock(), BasicBlock()
831
+ self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR))
832
+
833
+ self.activate_block(error_block)
834
+ self.add(
835
+ RaiseStandardError(
836
+ RaiseStandardError.VALUE_ERROR, "too many values to unpack", line
837
+ )
838
+ )
839
+ self.add(Unreachable())
840
+
841
+ self.activate_block(ok_block)
842
+
843
+ def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None:
844
+ self.nonlocal_control.append(
845
+ LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block)
846
+ )
847
+
848
+ def pop_loop_stack(self) -> None:
849
+ self.nonlocal_control.pop()
850
+
851
+ def make_spill_target(self, type: RType) -> AssignmentTarget:
852
+ """Moves a given Value instance into the generator class' environment class."""
853
+ name = f"{TEMP_ATTR_NAME}{self.temp_counter}"
854
+ self.temp_counter += 1
855
+ target = self.add_var_to_env_class(Var(name), type, self.fn_info.generator_class)
856
+ return target
857
+
858
+ def spill(self, value: Value) -> AssignmentTarget:
859
+ """Moves a given Value instance into the generator class' environment class."""
860
+ target = self.make_spill_target(value.type)
861
+ # Shouldn't be able to fail, so -1 for line
862
+ self.assign(target, value, -1)
863
+ return target
864
+
865
+ def maybe_spill(self, value: Value) -> Value | AssignmentTarget:
866
+ """
867
+ Moves a given Value instance into the environment class for generator functions. For
868
+ non-generator functions, leaves the Value instance as it is.
869
+
870
+ Returns an AssignmentTarget associated with the Value for generator functions and the
871
+ original Value itself for non-generator functions.
872
+ """
873
+ if self.fn_info.is_generator:
874
+ return self.spill(value)
875
+ return value
876
+
877
+ def maybe_spill_assignable(self, value: Value) -> Register | AssignmentTarget:
878
+ """
879
+ Moves a given Value instance into the environment class for generator functions. For
880
+ non-generator functions, allocate a temporary Register.
881
+
882
+ Returns an AssignmentTarget associated with the Value for generator functions and an
883
+ assignable Register for non-generator functions.
884
+ """
885
+ if self.fn_info.is_generator:
886
+ return self.spill(value)
887
+
888
+ if isinstance(value, Register):
889
+ return value
890
+
891
+ # Allocate a temporary register for the assignable value.
892
+ reg = Register(value.type)
893
+ self.assign(reg, value, -1)
894
+ return reg
895
+
896
+ def extract_int(self, e: Expression) -> int | None:
897
+ if isinstance(e, IntExpr):
898
+ return e.value
899
+ elif isinstance(e, UnaryExpr) and e.op == "-" and isinstance(e.expr, IntExpr):
900
+ return -e.expr.value
901
+ else:
902
+ return None
903
+
904
+ def get_sequence_type(self, expr: Expression) -> RType:
905
+ return self.get_sequence_type_from_type(self.types[expr])
906
+
907
+ def get_sequence_type_from_type(self, target_type: Type) -> RType:
908
+ target_type = get_proper_type(target_type)
909
+ if isinstance(target_type, UnionType):
910
+ return RUnion.make_simplified_union(
911
+ [self.get_sequence_type_from_type(item) for item in target_type.items]
912
+ )
913
+ assert isinstance(target_type, Instance), target_type
914
+ if target_type.type.fullname == "builtins.str":
915
+ return str_rprimitive
916
+ else:
917
+ return self.type_to_rtype(target_type.args[0])
918
+
919
+ def get_dict_base_type(self, expr: Expression) -> list[Instance]:
920
+ """Find dict type of a dict-like expression.
921
+
922
+ This is useful for dict subclasses like SymbolTable.
923
+ """
924
+ target_type = get_proper_type(self.types[expr])
925
+ if isinstance(target_type, UnionType):
926
+ types = [get_proper_type(item) for item in target_type.items]
927
+ else:
928
+ types = [target_type]
929
+
930
+ dict_types = []
931
+ for t in types:
932
+ if isinstance(t, TypedDictType):
933
+ t = t.fallback
934
+ dict_base = next(base for base in t.type.mro if base.fullname == "typing.Mapping")
935
+ else:
936
+ assert isinstance(t, Instance), t
937
+ dict_base = next(base for base in t.type.mro if base.fullname == "builtins.dict")
938
+ dict_types.append(map_instance_to_supertype(t, dict_base))
939
+ return dict_types
940
+
941
+ def get_dict_key_type(self, expr: Expression) -> RType:
942
+ dict_base_types = self.get_dict_base_type(expr)
943
+ if len(dict_base_types) == 1:
944
+ return self.type_to_rtype(dict_base_types[0].args[0])
945
+ else:
946
+ rtypes = [self.type_to_rtype(t.args[0]) for t in dict_base_types]
947
+ return RUnion.make_simplified_union(rtypes)
948
+
949
+ def get_dict_value_type(self, expr: Expression) -> RType:
950
+ dict_base_types = self.get_dict_base_type(expr)
951
+ if len(dict_base_types) == 1:
952
+ return self.type_to_rtype(dict_base_types[0].args[1])
953
+ else:
954
+ rtypes = [self.type_to_rtype(t.args[1]) for t in dict_base_types]
955
+ return RUnion.make_simplified_union(rtypes)
956
+
957
+ def get_dict_item_type(self, expr: Expression) -> RType:
958
+ key_type = self.get_dict_key_type(expr)
959
+ value_type = self.get_dict_value_type(expr)
960
+ return RTuple([key_type, value_type])
961
+
962
+ def _analyze_iterable_item_type(self, expr: Expression) -> Type:
963
+ """Return the item type given by 'expr' in an iterable context."""
964
+ # This logic is copied from mypy's TypeChecker.analyze_iterable_item_type.
965
+ if expr not in self.types:
966
+ # Mypy thinks this is unreachable.
967
+ iterable: ProperType = AnyType(TypeOfAny.from_error)
968
+ else:
969
+ iterable = get_proper_type(self.types[expr])
970
+ echk = self.graph[self.module_name].type_checker().expr_checker
971
+ iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], expr)[0]
972
+
973
+ from mypy.join import join_types
974
+
975
+ if isinstance(iterable, TupleType):
976
+ joined: Type = UninhabitedType()
977
+ for item in iterable.items:
978
+ joined = join_types(joined, item)
979
+ return joined
980
+ else:
981
+ # Non-tuple iterable.
982
+ return echk.check_method_call_by_name("__next__", iterator, [], [], expr)[0]
983
+
984
+ def is_native_module(self, module: str) -> bool:
985
+ """Is the given module one compiled by mypyc?"""
986
+ return self.mapper.is_native_module(module)
987
+
988
+ def is_native_ref_expr(self, expr: RefExpr) -> bool:
989
+ return self.mapper.is_native_ref_expr(expr)
990
+
991
+ def is_native_module_ref_expr(self, expr: RefExpr) -> bool:
992
+ return self.mapper.is_native_module_ref_expr(expr)
993
+
994
+ def is_synthetic_type(self, typ: TypeInfo) -> bool:
995
+ """Is a type something other than just a class we've created?"""
996
+ return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not None
997
+
998
+ def get_final_ref(self, expr: MemberExpr) -> tuple[str, Var, bool] | None:
999
+ """Check if `expr` is a final attribute.
1000
+
1001
+ This needs to be done differently for class and module attributes to
1002
+ correctly determine fully qualified name. Return a tuple that consists of
1003
+ the qualified name, the corresponding Var node, and a flag indicating whether
1004
+ the final name was defined in a compiled module. Return None if `expr` does not
1005
+ refer to a final attribute.
1006
+ """
1007
+ final_var = None
1008
+ if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo):
1009
+ # a class attribute
1010
+ sym = expr.expr.node.get(expr.name)
1011
+ if sym and isinstance(sym.node, Var):
1012
+ # Enum attribute are treated as final since they are added to the global cache
1013
+ expr_fullname = expr.expr.node.bases[0].type.fullname
1014
+ is_final = sym.node.is_final or expr_fullname == "enum.Enum"
1015
+ if is_final:
1016
+ final_var = sym.node
1017
+ fullname = f"{sym.node.info.fullname}.{final_var.name}"
1018
+ native = self.is_native_module(expr.expr.node.module_name)
1019
+ elif self.is_module_member_expr(expr):
1020
+ # a module attribute
1021
+ if isinstance(expr.node, Var) and expr.node.is_final:
1022
+ final_var = expr.node
1023
+ fullname = expr.node.fullname
1024
+ native = self.is_native_ref_expr(expr)
1025
+ if final_var is not None:
1026
+ return fullname, final_var, native
1027
+ return None
1028
+
1029
+ def emit_load_final(
1030
+ self, final_var: Var, fullname: str, name: str, native: bool, typ: Type, line: int
1031
+ ) -> Value | None:
1032
+ """Emit code for loading value of a final name (if possible).
1033
+
1034
+ Args:
1035
+ final_var: Var corresponding to the final name
1036
+ fullname: its qualified name
1037
+ name: shorter name to show in errors
1038
+ native: whether the name was defined in a compiled module
1039
+ typ: its type
1040
+ line: line number where loading occurs
1041
+ """
1042
+ if final_var.final_value is not None: # this is safe even for non-native names
1043
+ return self.load_literal_value(final_var.final_value)
1044
+ elif native and module_prefix(self.graph, fullname):
1045
+ return self.load_final_static(fullname, self.mapper.type_to_rtype(typ), line, name)
1046
+ else:
1047
+ return None
1048
+
1049
+ def is_module_member_expr(self, expr: MemberExpr) -> bool:
1050
+ return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile)
1051
+
1052
+ def call_refexpr_with_args(
1053
+ self, expr: CallExpr, callee: RefExpr, arg_values: list[Value]
1054
+ ) -> Value:
1055
+ # Handle data-driven special-cased primitive call ops.
1056
+ if callee.fullname and expr.arg_kinds == [ARG_POS] * len(arg_values):
1057
+ fullname = get_call_target_fullname(callee)
1058
+ primitive_candidates = function_ops.get(fullname, [])
1059
+ target = self.builder.matching_primitive_op(
1060
+ primitive_candidates, arg_values, expr.line, self.node_type(expr)
1061
+ )
1062
+ if target:
1063
+ return target
1064
+
1065
+ # Standard native call if signature and fullname are good and all arguments are positional
1066
+ # or named.
1067
+ callee_node = callee.node
1068
+ if isinstance(callee_node, OverloadedFuncDef):
1069
+ callee_node = callee_node.impl
1070
+ # TODO: use native calls for any decorated functions which have all their decorators
1071
+ # removed, not just singledispatch functions (which we don't do now just in case those
1072
+ # decorated functions are callable classes or cannot be called without the python API for
1073
+ # some other reason)
1074
+ if (
1075
+ isinstance(callee_node, Decorator)
1076
+ and callee_node.func not in self.fdefs_to_decorators
1077
+ and callee_node.func in self.singledispatch_impls
1078
+ ):
1079
+ callee_node = callee_node.func
1080
+ if (
1081
+ callee_node is not None
1082
+ and callee.fullname
1083
+ and callee_node in self.mapper.func_to_decl
1084
+ and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)
1085
+ ):
1086
+ decl = self.mapper.func_to_decl[callee_node]
1087
+ return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line)
1088
+
1089
+ # Fall back to a Python call
1090
+ function = self.accept(callee)
1091
+ return self.py_call(
1092
+ function, arg_values, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names
1093
+ )
1094
+
1095
+ def shortcircuit_expr(self, expr: OpExpr) -> Value:
1096
+ return self.builder.shortcircuit_helper(
1097
+ expr.op,
1098
+ self.node_type(expr),
1099
+ lambda: self.accept(expr.left),
1100
+ lambda: self.accept(expr.right),
1101
+ expr.line,
1102
+ )
1103
+
1104
+ # Basic helpers
1105
+
1106
+ def flatten_classes(self, arg: RefExpr | TupleExpr) -> list[ClassIR] | None:
1107
+ """Flatten classes in isinstance(obj, (A, (B, C))).
1108
+
1109
+ If at least one item is not a reference to a native class, return None.
1110
+ """
1111
+ if isinstance(arg, RefExpr):
1112
+ if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg):
1113
+ ir = self.mapper.type_to_ir.get(arg.node)
1114
+ if ir:
1115
+ return [ir]
1116
+ return None
1117
+ else:
1118
+ res: list[ClassIR] = []
1119
+ for item in arg.items:
1120
+ if isinstance(item, (RefExpr, TupleExpr)):
1121
+ item_part = self.flatten_classes(item)
1122
+ if item_part is None:
1123
+ return None
1124
+ res.extend(item_part)
1125
+ else:
1126
+ return None
1127
+ return res
1128
+
1129
+ def enter(self, fn_info: FuncInfo | str = "") -> None:
1130
+ if isinstance(fn_info, str):
1131
+ fn_info = FuncInfo(name=fn_info)
1132
+ self.builder = LowLevelIRBuilder(self.errors, self.options)
1133
+ self.builder.set_module(self.module_name, self.module_path)
1134
+ self.builders.append(self.builder)
1135
+ self.symtables.append({})
1136
+ self.runtime_args.append([])
1137
+ self.fn_info = fn_info
1138
+ self.fn_infos.append(self.fn_info)
1139
+ self.ret_types.append(none_rprimitive)
1140
+ if fn_info.is_generator:
1141
+ self.nonlocal_control.append(GeneratorNonlocalControl())
1142
+ else:
1143
+ self.nonlocal_control.append(BaseNonlocalControl())
1144
+ self.activate_block(BasicBlock())
1145
+
1146
+ def leave(self) -> tuple[list[Register], list[RuntimeArg], list[BasicBlock], RType, FuncInfo]:
1147
+ builder = self.builders.pop()
1148
+ self.symtables.pop()
1149
+ runtime_args = self.runtime_args.pop()
1150
+ ret_type = self.ret_types.pop()
1151
+ fn_info = self.fn_infos.pop()
1152
+ self.nonlocal_control.pop()
1153
+ self.builder = self.builders[-1]
1154
+ self.fn_info = self.fn_infos[-1]
1155
+ return builder.args, runtime_args, builder.blocks, ret_type, fn_info
1156
+
1157
+ @contextmanager
1158
+ def enter_method(
1159
+ self,
1160
+ class_ir: ClassIR,
1161
+ name: str,
1162
+ ret_type: RType,
1163
+ fn_info: FuncInfo | str = "",
1164
+ self_type: RType | None = None,
1165
+ ) -> Iterator[None]:
1166
+ """Generate IR for a method.
1167
+
1168
+ If the method takes arguments, you should immediately afterwards call
1169
+ add_argument() for each non-self argument (self is created implicitly).
1170
+
1171
+ Args:
1172
+ class_ir: Add method to this class
1173
+ name: Short name of the method
1174
+ ret_type: Return type of the method
1175
+ fn_info: Optionally, additional information about the method
1176
+ self_type: If not None, override default type of the implicit 'self'
1177
+ argument (by default, derive type from class_ir)
1178
+ """
1179
+ self.enter(fn_info)
1180
+ self.function_name_stack.append(name)
1181
+ self.class_ir_stack.append(class_ir)
1182
+ self.ret_types[-1] = ret_type
1183
+ if self_type is None:
1184
+ self_type = RInstance(class_ir)
1185
+ self.add_argument(SELF_NAME, self_type)
1186
+ try:
1187
+ yield
1188
+ finally:
1189
+ arg_regs, args, blocks, ret_type, fn_info = self.leave()
1190
+ sig = FuncSignature(args, ret_type)
1191
+ name = self.function_name_stack.pop()
1192
+ class_ir = self.class_ir_stack.pop()
1193
+ decl = FuncDecl(name, class_ir.name, self.module_name, sig)
1194
+ ir = FuncIR(decl, arg_regs, blocks)
1195
+ class_ir.methods[name] = ir
1196
+ class_ir.method_decls[name] = ir.decl
1197
+ self.functions.append(ir)
1198
+
1199
+ def add_argument(self, var: str | Var, typ: RType, kind: ArgKind = ARG_POS) -> Register:
1200
+ """Declare an argument in the current function.
1201
+
1202
+ You should use this instead of directly calling add_local() in new code.
1203
+ """
1204
+ if isinstance(var, str):
1205
+ var = Var(var)
1206
+ reg = self.add_local(var, typ, is_arg=True)
1207
+ self.runtime_args[-1].append(RuntimeArg(var.name, typ, kind))
1208
+ return reg
1209
+
1210
+ def lookup(self, symbol: SymbolNode) -> SymbolTarget:
1211
+ return self.symtables[-1][symbol]
1212
+
1213
+ def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> Register:
1214
+ """Add register that represents a symbol to the symbol table.
1215
+
1216
+ Args:
1217
+ is_arg: is this a function argument
1218
+ """
1219
+ assert isinstance(symbol, SymbolNode)
1220
+ reg = Register(
1221
+ typ, remangle_redefinition_name(symbol.name), is_arg=is_arg, line=symbol.line
1222
+ )
1223
+ self.symtables[-1][symbol] = AssignmentTargetRegister(reg)
1224
+ if is_arg:
1225
+ self.builder.args.append(reg)
1226
+ return reg
1227
+
1228
+ def add_local_reg(
1229
+ self, symbol: SymbolNode, typ: RType, is_arg: bool = False
1230
+ ) -> AssignmentTargetRegister:
1231
+ """Like add_local, but return an assignment target instead of value."""
1232
+ self.add_local(symbol, typ, is_arg)
1233
+ target = self.symtables[-1][symbol]
1234
+ assert isinstance(target, AssignmentTargetRegister)
1235
+ return target
1236
+
1237
+ def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister:
1238
+ """Low-level function that adds a 'self' argument.
1239
+
1240
+ This is only useful if using enter() instead of enter_method().
1241
+ """
1242
+ return self.add_local_reg(Var(SELF_NAME), RInstance(cls), is_arg=True)
1243
+
1244
+ def add_target(self, symbol: SymbolNode, target: SymbolTarget) -> SymbolTarget:
1245
+ self.symtables[-1][symbol] = target
1246
+ return target
1247
+
1248
+ def type_to_rtype(self, typ: Type | None) -> RType:
1249
+ return self.mapper.type_to_rtype(typ)
1250
+
1251
+ def node_type(self, node: Expression) -> RType:
1252
+ if isinstance(node, IntExpr):
1253
+ # TODO: Don't special case IntExpr
1254
+ return int_rprimitive
1255
+ if node not in self.types:
1256
+ return object_rprimitive
1257
+ mypy_type = self.types[node]
1258
+ return self.type_to_rtype(mypy_type)
1259
+
1260
+ def add_var_to_env_class(
1261
+ self, var: SymbolNode, rtype: RType, base: FuncInfo | ImplicitClass, reassign: bool = False
1262
+ ) -> AssignmentTarget:
1263
+ # First, define the variable name as an attribute of the environment class, and then
1264
+ # construct a target for that attribute.
1265
+ name = remangle_redefinition_name(var.name)
1266
+ self.fn_info.env_class.attributes[name] = rtype
1267
+ attr_target = AssignmentTargetAttr(base.curr_env_reg, name)
1268
+
1269
+ if reassign:
1270
+ # Read the local definition of the variable, and set the corresponding attribute of
1271
+ # the environment class' variable to be that value.
1272
+ reg = self.read(self.lookup(var), self.fn_info.fitem.line)
1273
+ self.add(SetAttr(base.curr_env_reg, name, reg, self.fn_info.fitem.line))
1274
+
1275
+ # Override the local definition of the variable to instead point at the variable in
1276
+ # the environment class.
1277
+ return self.add_target(var, attr_target)
1278
+
1279
+ def is_builtin_ref_expr(self, expr: RefExpr) -> bool:
1280
+ assert expr.node, "RefExpr not resolved"
1281
+ return "." in expr.node.fullname and expr.node.fullname.split(".")[0] == "builtins"
1282
+
1283
+ def load_global(self, expr: NameExpr) -> Value:
1284
+ """Loads a Python-level global.
1285
+
1286
+ This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject *
1287
+ from the _globals dictionary in the C-generated code.
1288
+ """
1289
+ # If the global is from 'builtins', turn it into a module attr load instead
1290
+ if self.is_builtin_ref_expr(expr):
1291
+ assert expr.node, "RefExpr not resolved"
1292
+ return self.load_module_attr_by_fullname(expr.node.fullname, expr.line)
1293
+ if (
1294
+ self.is_native_module_ref_expr(expr)
1295
+ and isinstance(expr.node, TypeInfo)
1296
+ and not self.is_synthetic_type(expr.node)
1297
+ ):
1298
+ assert expr.fullname
1299
+ return self.load_native_type_object(expr.fullname)
1300
+ return self.load_global_str(expr.name, expr.line)
1301
+
1302
+ def load_global_str(self, name: str, line: int) -> Value:
1303
+ _globals = self.load_globals_dict()
1304
+ reg = self.load_str(name)
1305
+ return self.primitive_op(dict_get_item_op, [_globals, reg], line)
1306
+
1307
+ def load_globals_dict(self) -> Value:
1308
+ return self.add(LoadStatic(dict_rprimitive, "globals", self.module_name))
1309
+
1310
+ def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value:
1311
+ module, _, name = fullname.rpartition(".")
1312
+ left = self.load_module(module)
1313
+ return self.py_get_attr(left, name, line)
1314
+
1315
+ def is_native_attr_ref(self, expr: MemberExpr) -> bool:
1316
+ """Is expr a direct reference to a native (struct) attribute of an instance?"""
1317
+ obj_rtype = self.node_type(expr.expr)
1318
+ return (
1319
+ isinstance(obj_rtype, RInstance)
1320
+ and obj_rtype.class_ir.is_ext_class
1321
+ and obj_rtype.class_ir.has_attr(expr.name)
1322
+ and not obj_rtype.class_ir.get_method(expr.name)
1323
+ )
1324
+
1325
+ def mark_block_unreachable(self) -> None:
1326
+ """Mark statements in the innermost block being processed as unreachable.
1327
+
1328
+ This should be called after a statement that unconditionally leaves the
1329
+ block, such as 'break' or 'return'.
1330
+ """
1331
+ self.block_reachable_stack[-1] = False
1332
+
1333
+ # Lacks a good type because there wasn't a reasonable type in 3.5 :(
1334
+ def catch_errors(self, line: int) -> Any:
1335
+ return catch_errors(self.module_path, line)
1336
+
1337
+ def warning(self, msg: str, line: int) -> None:
1338
+ self.errors.warning(msg, self.module_path, line)
1339
+
1340
+ def error(self, msg: str, line: int) -> None:
1341
+ self.errors.error(msg, self.module_path, line)
1342
+
1343
+ def note(self, msg: str, line: int) -> None:
1344
+ self.errors.note(msg, self.module_path, line)
1345
+
1346
+ def add_function(self, func_ir: FuncIR, line: int) -> None:
1347
+ name = (func_ir.class_name, func_ir.name)
1348
+ if name in self.function_names:
1349
+ self.error(f'Duplicate definition of "{name[1]}" not supported by mypyc', line)
1350
+ return
1351
+ self.function_names.add(name)
1352
+ self.functions.append(func_ir)
1353
+
1354
+
1355
+ def gen_arg_defaults(builder: IRBuilder) -> None:
1356
+ """Generate blocks for arguments that have default values.
1357
+
1358
+ If the passed value is an error value, then assign the default
1359
+ value to the argument.
1360
+ """
1361
+ fitem = builder.fn_info.fitem
1362
+ nb = 0
1363
+ for arg in fitem.arguments:
1364
+ if arg.initializer:
1365
+ target = builder.lookup(arg.variable)
1366
+
1367
+ def get_default() -> Value:
1368
+ assert arg.initializer is not None
1369
+
1370
+ # If it is constant, don't bother storing it
1371
+ if is_constant(arg.initializer):
1372
+ return builder.accept(arg.initializer)
1373
+
1374
+ # Because gen_arg_defaults runs before calculate_arg_defaults, we
1375
+ # add the static/attribute to final_names/the class here.
1376
+ elif not builder.fn_info.is_nested:
1377
+ name = fitem.fullname + "." + arg.variable.name
1378
+ builder.final_names.append((name, target.type))
1379
+ return builder.add(LoadStatic(target.type, name, builder.module_name))
1380
+ else:
1381
+ name = arg.variable.name
1382
+ builder.fn_info.callable_class.ir.attributes[name] = target.type
1383
+ return builder.add(
1384
+ GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line)
1385
+ )
1386
+
1387
+ assert isinstance(target, AssignmentTargetRegister)
1388
+ reg = target.register
1389
+ if not reg.type.error_overlap:
1390
+ builder.assign_if_null(target.register, get_default, arg.initializer.line)
1391
+ else:
1392
+ builder.assign_if_bitmap_unset(
1393
+ target.register, get_default, nb, arg.initializer.line
1394
+ )
1395
+ nb += 1
1396
+
1397
+
1398
+ def remangle_redefinition_name(name: str) -> str:
1399
+ """Remangle names produced by mypy when allow-redefinition is used and a name
1400
+ is used with multiple types within a single block.
1401
+
1402
+ We only need to do this for locals, because the name is used as the name of the register;
1403
+ for globals, the name itself is stored in a register for the purpose of doing dict
1404
+ lookups.
1405
+ """
1406
+ return name.replace("'", "__redef__")
1407
+
1408
+
1409
+ def get_call_target_fullname(ref: RefExpr) -> str:
1410
+ if isinstance(ref.node, TypeAlias):
1411
+ # Resolve simple type aliases. In calls they evaluate to the type they point to.
1412
+ target = get_proper_type(ref.node.target)
1413
+ if isinstance(target, Instance):
1414
+ return target.type.fullname
1415
+ return ref.fullname
1416
+
1417
+
1418
+ def create_type_params(
1419
+ builder: IRBuilder, typing_mod: Value, type_args: list[TypeParam], line: int
1420
+ ) -> list[Value]:
1421
+ """Create objects representing various kinds of Python 3.12 type parameters.
1422
+
1423
+ The "typing_mod" argument is the "_typing" module object. The type objects
1424
+ are looked up from it.
1425
+
1426
+ The returned list has one item for each "type_args" item, in the same order.
1427
+ Each item is either a TypeVar, TypeVarTuple or ParamSpec instance.
1428
+ """
1429
+ tvs = []
1430
+ type_var_imported: Value | None = None
1431
+ for type_param in type_args:
1432
+ if type_param.kind == TYPE_VAR_KIND:
1433
+ if type_var_imported:
1434
+ # Reuse previously imported value as a minor optimization
1435
+ tvt = type_var_imported
1436
+ else:
1437
+ tvt = builder.py_get_attr(typing_mod, "TypeVar", line)
1438
+ type_var_imported = tvt
1439
+ elif type_param.kind == TYPE_VAR_TUPLE_KIND:
1440
+ tvt = builder.py_get_attr(typing_mod, "TypeVarTuple", line)
1441
+ else:
1442
+ assert type_param.kind == PARAM_SPEC_KIND
1443
+ tvt = builder.py_get_attr(typing_mod, "ParamSpec", line)
1444
+ if type_param.kind != TYPE_VAR_TUPLE_KIND:
1445
+ # To match runtime semantics, pass infer_variance=True
1446
+ tv = builder.py_call(
1447
+ tvt,
1448
+ [builder.load_str(type_param.name), builder.true()],
1449
+ line,
1450
+ arg_kinds=[ARG_POS, ARG_NAMED],
1451
+ arg_names=[None, "infer_variance"],
1452
+ )
1453
+ else:
1454
+ tv = builder.py_call(tvt, [builder.load_str(type_param.name)], line)
1455
+ builder.init_type_var(tv, type_param.name, line)
1456
+ tvs.append(tv)
1457
+ return tvs
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.py ADDED
The diff for this file is too large to render. See raw diff
 
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.42 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.py ADDED
File without changes
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (174 Bytes). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pyc ADDED
Binary file (3.45 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pyc ADDED
Binary file (1.77 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pyc ADDED
Binary file (4.71 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pyc ADDED
Binary file (4.48 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pyc ADDED
Binary file (3.39 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pyc ADDED
Binary file (3.39 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pyc ADDED
Binary file (2.96 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primitive bytes ops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from mypyc.ir.ops import ERR_MAGIC
6
+ from mypyc.ir.rtypes import (
7
+ RUnion,
8
+ bytes_rprimitive,
9
+ c_int_rprimitive,
10
+ c_pyssize_t_rprimitive,
11
+ dict_rprimitive,
12
+ int_rprimitive,
13
+ list_rprimitive,
14
+ object_rprimitive,
15
+ str_rprimitive,
16
+ )
17
+ from mypyc.primitives.registry import (
18
+ ERR_NEG_INT,
19
+ binary_op,
20
+ custom_op,
21
+ function_op,
22
+ load_address_op,
23
+ method_op,
24
+ )
25
+
26
+ # Get the 'bytes' type object.
27
+ load_address_op(name="builtins.bytes", type=object_rprimitive, src="PyBytes_Type")
28
+
29
+ # bytes(obj)
30
+ function_op(
31
+ name="builtins.bytes",
32
+ arg_types=[RUnion([list_rprimitive, dict_rprimitive, str_rprimitive])],
33
+ return_type=bytes_rprimitive,
34
+ c_function_name="PyBytes_FromObject",
35
+ error_kind=ERR_MAGIC,
36
+ )
37
+
38
+ # bytearray(obj)
39
+ function_op(
40
+ name="builtins.bytearray",
41
+ arg_types=[object_rprimitive],
42
+ return_type=bytes_rprimitive,
43
+ c_function_name="PyByteArray_FromObject",
44
+ error_kind=ERR_MAGIC,
45
+ )
46
+
47
+ # bytes ==/!= (return -1/0/1)
48
+ bytes_compare = custom_op(
49
+ arg_types=[bytes_rprimitive, bytes_rprimitive],
50
+ return_type=c_int_rprimitive,
51
+ c_function_name="CPyBytes_Compare",
52
+ error_kind=ERR_NEG_INT,
53
+ )
54
+
55
+ # bytes + bytes
56
+ # bytearray + bytearray
57
+ binary_op(
58
+ name="+",
59
+ arg_types=[bytes_rprimitive, bytes_rprimitive],
60
+ return_type=bytes_rprimitive,
61
+ c_function_name="CPyBytes_Concat",
62
+ error_kind=ERR_MAGIC,
63
+ steals=[True, False],
64
+ )
65
+
66
+ # bytes[begin:end]
67
+ bytes_slice_op = custom_op(
68
+ arg_types=[bytes_rprimitive, int_rprimitive, int_rprimitive],
69
+ return_type=bytes_rprimitive,
70
+ c_function_name="CPyBytes_GetSlice",
71
+ error_kind=ERR_MAGIC,
72
+ )
73
+
74
+ # bytes[index]
75
+ # bytearray[index]
76
+ method_op(
77
+ name="__getitem__",
78
+ arg_types=[bytes_rprimitive, int_rprimitive],
79
+ return_type=int_rprimitive,
80
+ c_function_name="CPyBytes_GetItem",
81
+ error_kind=ERR_MAGIC,
82
+ )
83
+
84
+ # bytes.join(obj)
85
+ method_op(
86
+ name="join",
87
+ arg_types=[bytes_rprimitive, object_rprimitive],
88
+ return_type=bytes_rprimitive,
89
+ c_function_name="CPyBytes_Join",
90
+ error_kind=ERR_MAGIC,
91
+ )
92
+
93
+ # Join bytes objects and return a new bytes.
94
+ # The first argument is the total number of the following bytes.
95
+ bytes_build_op = custom_op(
96
+ arg_types=[c_pyssize_t_rprimitive],
97
+ return_type=bytes_rprimitive,
98
+ c_function_name="CPyBytes_Build",
99
+ error_kind=ERR_MAGIC,
100
+ var_arg_type=bytes_rprimitive,
101
+ )
102
+
103
+ function_op(
104
+ name="builtins.ord",
105
+ arg_types=[bytes_rprimitive],
106
+ return_type=int_rprimitive,
107
+ c_function_name="CPyBytes_Ord",
108
+ error_kind=ERR_MAGIC,
109
+ )
openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primitive dict ops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER
6
+ from mypyc.ir.rtypes import (
7
+ bit_rprimitive,
8
+ bool_rprimitive,
9
+ c_int_rprimitive,
10
+ c_pyssize_t_rprimitive,
11
+ dict_next_rtuple_pair,
12
+ dict_next_rtuple_single,
13
+ dict_rprimitive,
14
+ int_rprimitive,
15
+ list_rprimitive,
16
+ object_rprimitive,
17
+ )
18
+ from mypyc.primitives.registry import (
19
+ ERR_NEG_INT,
20
+ binary_op,
21
+ custom_op,
22
+ function_op,
23
+ load_address_op,
24
+ method_op,
25
+ )
26
+
27
+ # Get the 'dict' type object.
28
+ load_address_op(name="builtins.dict", type=object_rprimitive, src="PyDict_Type")
29
+
30
+ # Construct an empty dictionary via dict().
31
+ function_op(
32
+ name="builtins.dict",
33
+ arg_types=[],
34
+ return_type=dict_rprimitive,
35
+ c_function_name="PyDict_New",
36
+ error_kind=ERR_MAGIC,
37
+ )
38
+
39
+ # Construct an empty dictionary.
40
+ dict_new_op = custom_op(
41
+ arg_types=[], return_type=dict_rprimitive, c_function_name="PyDict_New", error_kind=ERR_MAGIC
42
+ )
43
+
44
+ # Construct a dictionary from keys and values.
45
+ # Positional argument is the number of key-value pairs
46
+ # Variable arguments are (key1, value1, ..., keyN, valueN).
47
+ dict_build_op = custom_op(
48
+ arg_types=[c_pyssize_t_rprimitive],
49
+ return_type=dict_rprimitive,
50
+ c_function_name="CPyDict_Build",
51
+ error_kind=ERR_MAGIC,
52
+ var_arg_type=object_rprimitive,
53
+ )
54
+
55
+ # Construct a dictionary from another dictionary.
56
+ function_op(
57
+ name="builtins.dict",
58
+ arg_types=[dict_rprimitive],
59
+ return_type=dict_rprimitive,
60
+ c_function_name="PyDict_Copy",
61
+ error_kind=ERR_MAGIC,
62
+ priority=2,
63
+ )
64
+
65
+ # Generic one-argument dict constructor: dict(obj)
66
+ dict_copy = function_op(
67
+ name="builtins.dict",
68
+ arg_types=[object_rprimitive],
69
+ return_type=dict_rprimitive,
70
+ c_function_name="CPyDict_FromAny",
71
+ error_kind=ERR_MAGIC,
72
+ )
73
+
74
+ # dict[key]
75
+ dict_get_item_op = method_op(
76
+ name="__getitem__",
77
+ arg_types=[dict_rprimitive, object_rprimitive],
78
+ return_type=object_rprimitive,
79
+ c_function_name="CPyDict_GetItem",
80
+ error_kind=ERR_MAGIC,
81
+ )
82
+
83
+ # dict[key] = value
84
+ dict_set_item_op = method_op(
85
+ name="__setitem__",
86
+ arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],
87
+ return_type=c_int_rprimitive,
88
+ c_function_name="CPyDict_SetItem",
89
+ error_kind=ERR_NEG_INT,
90
+ )
91
+
92
+ # key in dict
93
+ binary_op(
94
+ name="in",
95
+ arg_types=[object_rprimitive, dict_rprimitive],
96
+ return_type=c_int_rprimitive,
97
+ c_function_name="PyDict_Contains",
98
+ error_kind=ERR_NEG_INT,
99
+ truncated_type=bool_rprimitive,
100
+ ordering=[1, 0],
101
+ )
102
+
103
+ # dict1.update(dict2)
104
+ dict_update_op = method_op(
105
+ name="update",
106
+ arg_types=[dict_rprimitive, dict_rprimitive],
107
+ return_type=c_int_rprimitive,
108
+ c_function_name="CPyDict_Update",
109
+ error_kind=ERR_NEG_INT,
110
+ priority=2,
111
+ )
112
+
113
+ # Operation used for **value in dict displays.
114
+ # This is mostly like dict.update(obj), but has customized error handling.
115
+ dict_update_in_display_op = custom_op(
116
+ arg_types=[dict_rprimitive, object_rprimitive],
117
+ return_type=c_int_rprimitive,
118
+ c_function_name="CPyDict_UpdateInDisplay",
119
+ error_kind=ERR_NEG_INT,
120
+ )
121
+
122
+ # dict.update(obj)
123
+ method_op(
124
+ name="update",
125
+ arg_types=[dict_rprimitive, object_rprimitive],
126
+ return_type=c_int_rprimitive,
127
+ c_function_name="CPyDict_UpdateFromAny",
128
+ error_kind=ERR_NEG_INT,
129
+ )
130
+
131
+ # dict.get(key, default)
132
+ method_op(
133
+ name="get",
134
+ arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],
135
+ return_type=object_rprimitive,
136
+ c_function_name="CPyDict_Get",
137
+ error_kind=ERR_MAGIC,
138
+ )
139
+
140
+ # dict.get(key)
141
+ dict_get_method_with_none = method_op(
142
+ name="get",
143
+ arg_types=[dict_rprimitive, object_rprimitive],
144
+ return_type=object_rprimitive,
145
+ c_function_name="CPyDict_GetWithNone",
146
+ error_kind=ERR_MAGIC,
147
+ )
148
+
149
+ # dict.setdefault(key, default)
150
+ dict_setdefault_op = method_op(
151
+ name="setdefault",
152
+ arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],
153
+ return_type=object_rprimitive,
154
+ c_function_name="CPyDict_SetDefault",
155
+ error_kind=ERR_MAGIC,
156
+ )
157
+
158
+ # dict.setdefault(key)
159
+ method_op(
160
+ name="setdefault",
161
+ arg_types=[dict_rprimitive, object_rprimitive],
162
+ return_type=object_rprimitive,
163
+ c_function_name="CPyDict_SetDefaultWithNone",
164
+ error_kind=ERR_MAGIC,
165
+ )
166
+
167
+ # dict.setdefault(key, empty tuple/list/set)
168
+ # The third argument marks the data type of the second argument.
169
+ # 1: list 2: dict 3: set
170
+ # Other number would lead to an error.
171
+ dict_setdefault_spec_init_op = custom_op(
172
+ arg_types=[dict_rprimitive, object_rprimitive, c_int_rprimitive],
173
+ return_type=object_rprimitive,
174
+ c_function_name="CPyDict_SetDefaultWithEmptyDatatype",
175
+ error_kind=ERR_MAGIC,
176
+ )
177
+
178
+ # dict.keys()
179
+ method_op(
180
+ name="keys",
181
+ arg_types=[dict_rprimitive],
182
+ return_type=object_rprimitive,
183
+ c_function_name="CPyDict_KeysView",
184
+ error_kind=ERR_MAGIC,
185
+ )
186
+
187
+ # dict.values()
188
+ method_op(
189
+ name="values",
190
+ arg_types=[dict_rprimitive],
191
+ return_type=object_rprimitive,
192
+ c_function_name="CPyDict_ValuesView",
193
+ error_kind=ERR_MAGIC,
194
+ )
195
+
196
+ # dict.items()
197
+ method_op(
198
+ name="items",
199
+ arg_types=[dict_rprimitive],
200
+ return_type=object_rprimitive,
201
+ c_function_name="CPyDict_ItemsView",
202
+ error_kind=ERR_MAGIC,
203
+ )
204
+
205
+ # dict.clear()
206
+ method_op(
207
+ name="clear",
208
+ arg_types=[dict_rprimitive],
209
+ return_type=bit_rprimitive,
210
+ c_function_name="CPyDict_Clear",
211
+ error_kind=ERR_FALSE,
212
+ )
213
+
214
+ # dict.copy()
215
+ method_op(
216
+ name="copy",
217
+ arg_types=[dict_rprimitive],
218
+ return_type=dict_rprimitive,
219
+ c_function_name="CPyDict_Copy",
220
+ error_kind=ERR_MAGIC,
221
+ )
222
+
223
+ # list(dict.keys())
224
+ dict_keys_op = custom_op(
225
+ arg_types=[dict_rprimitive],
226
+ return_type=list_rprimitive,
227
+ c_function_name="CPyDict_Keys",
228
+ error_kind=ERR_MAGIC,
229
+ )
230
+
231
+ # list(dict.values())
232
+ dict_values_op = custom_op(
233
+ arg_types=[dict_rprimitive],
234
+ return_type=list_rprimitive,
235
+ c_function_name="CPyDict_Values",
236
+ error_kind=ERR_MAGIC,
237
+ )
238
+
239
+ # list(dict.items())
240
+ dict_items_op = custom_op(
241
+ arg_types=[dict_rprimitive],
242
+ return_type=list_rprimitive,
243
+ c_function_name="CPyDict_Items",
244
+ error_kind=ERR_MAGIC,
245
+ )
246
+
247
+ # PyDict_Next() fast iteration
248
+ dict_key_iter_op = custom_op(
249
+ arg_types=[dict_rprimitive],
250
+ return_type=object_rprimitive,
251
+ c_function_name="CPyDict_GetKeysIter",
252
+ error_kind=ERR_MAGIC,
253
+ )
254
+
255
+ dict_value_iter_op = custom_op(
256
+ arg_types=[dict_rprimitive],
257
+ return_type=object_rprimitive,
258
+ c_function_name="CPyDict_GetValuesIter",
259
+ error_kind=ERR_MAGIC,
260
+ )
261
+
262
+ dict_item_iter_op = custom_op(
263
+ arg_types=[dict_rprimitive],
264
+ return_type=object_rprimitive,
265
+ c_function_name="CPyDict_GetItemsIter",
266
+ error_kind=ERR_MAGIC,
267
+ )
268
+
269
+ dict_next_key_op = custom_op(
270
+ arg_types=[object_rprimitive, int_rprimitive],
271
+ return_type=dict_next_rtuple_single,
272
+ c_function_name="CPyDict_NextKey",
273
+ error_kind=ERR_NEVER,
274
+ )
275
+
276
+ dict_next_value_op = custom_op(
277
+ arg_types=[object_rprimitive, int_rprimitive],
278
+ return_type=dict_next_rtuple_single,
279
+ c_function_name="CPyDict_NextValue",
280
+ error_kind=ERR_NEVER,
281
+ )
282
+
283
+ dict_next_item_op = custom_op(
284
+ arg_types=[object_rprimitive, int_rprimitive],
285
+ return_type=dict_next_rtuple_pair,
286
+ c_function_name="CPyDict_NextItem",
287
+ error_kind=ERR_NEVER,
288
+ )
289
+
290
+ # check that len(dict) == const during iteration
291
+ dict_check_size_op = custom_op(
292
+ arg_types=[dict_rprimitive, int_rprimitive],
293
+ return_type=bit_rprimitive,
294
+ c_function_name="CPyDict_CheckSize",
295
+ error_kind=ERR_FALSE,
296
+ )
297
+
298
+ dict_ssize_t_size_op = custom_op(
299
+ arg_types=[dict_rprimitive],
300
+ return_type=c_pyssize_t_rprimitive,
301
+ c_function_name="PyDict_Size",
302
+ error_kind=ERR_NEVER,
303
+ )
304
+
305
+ # Delete an item from a dict
306
+ dict_del_item = custom_op(
307
+ arg_types=[object_rprimitive, object_rprimitive],
308
+ return_type=c_int_rprimitive,
309
+ c_function_name="PyDict_DelItem",
310
+ error_kind=ERR_NEG_INT,
311
+ )
312
+
313
+ supports_mapping_protocol = custom_op(
314
+ arg_types=[object_rprimitive],
315
+ return_type=c_int_rprimitive,
316
+ c_function_name="CPyMapping_Check",
317
+ error_kind=ERR_NEVER,
318
+ )
319
+
320
+ mapping_has_key = custom_op(
321
+ arg_types=[object_rprimitive, object_rprimitive],
322
+ return_type=c_int_rprimitive,
323
+ c_function_name="PyMapping_HasKey",
324
+ error_kind=ERR_NEVER,
325
+ )
openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file
 
openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exception-related primitive ops."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from mypyc.ir.ops import ERR_ALWAYS, ERR_FALSE, ERR_NEVER
6
+ from mypyc.ir.rtypes import bit_rprimitive, exc_rtuple, object_rprimitive, void_rtype
7
+ from mypyc.primitives.registry import custom_op
8
+
9
+ # If the argument is a class, raise an instance of the class. Otherwise, assume
10
+ # that the argument is an exception object, and raise it.
11
+ raise_exception_op = custom_op(
12
+ arg_types=[object_rprimitive],
13
+ return_type=void_rtype,
14
+ c_function_name="CPy_Raise",
15
+ error_kind=ERR_ALWAYS,
16
+ )
17
+
18
+ # Raise StopIteration exception with the specified value (which can be NULL).
19
+ set_stop_iteration_value = custom_op(
20
+ arg_types=[object_rprimitive],
21
+ return_type=void_rtype,
22
+ c_function_name="CPyGen_SetStopIterationValue",
23
+ error_kind=ERR_ALWAYS,
24
+ )
25
+
26
+ # Raise exception with traceback.
27
+ # Arguments are (exception type, exception value, traceback).
28
+ raise_exception_with_tb_op = custom_op(
29
+ arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],
30
+ return_type=void_rtype,
31
+ c_function_name="CPyErr_SetObjectAndTraceback",
32
+ error_kind=ERR_ALWAYS,
33
+ )
34
+
35
+ # Reraise the currently raised exception.
36
+ reraise_exception_op = custom_op(
37
+ arg_types=[], return_type=void_rtype, c_function_name="CPy_Reraise", error_kind=ERR_ALWAYS
38
+ )
39
+
40
+ # Propagate exception if the CPython error indicator is set (an exception was raised).
41
+ no_err_occurred_op = custom_op(
42
+ arg_types=[],
43
+ return_type=bit_rprimitive,
44
+ c_function_name="CPy_NoErrOccured",
45
+ error_kind=ERR_FALSE,
46
+ )
47
+
48
+ err_occurred_op = custom_op(
49
+ arg_types=[],
50
+ return_type=object_rprimitive,
51
+ c_function_name="PyErr_Occurred",
52
+ error_kind=ERR_NEVER,
53
+ is_borrowed=True,
54
+ )
55
+
56
+ # Keep propagating a raised exception by unconditionally giving an error value.
57
+ # This doesn't actually raise an exception.
58
+ keep_propagating_op = custom_op(
59
+ arg_types=[],
60
+ return_type=bit_rprimitive,
61
+ c_function_name="CPy_KeepPropagating",
62
+ error_kind=ERR_FALSE,
63
+ )
64
+
65
+ # Catches a propagating exception and makes it the "currently
66
+ # handled exception" (by sticking it into sys.exc_info()). Returns the
67
+ # exception that was previously being handled, which must be restored
68
+ # later.
69
+ error_catch_op = custom_op(
70
+ arg_types=[], return_type=exc_rtuple, c_function_name="CPy_CatchError", error_kind=ERR_NEVER
71
+ )
72
+
73
+ # Restore an old "currently handled exception" returned from.
74
+ # error_catch (by sticking it into sys.exc_info())
75
+ restore_exc_info_op = custom_op(
76
+ arg_types=[exc_rtuple],
77
+ return_type=void_rtype,
78
+ c_function_name="CPy_RestoreExcInfo",
79
+ error_kind=ERR_NEVER,
80
+ )
81
+
82
+ # Checks whether the exception currently being handled matches a particular type.
83
+ exc_matches_op = custom_op(
84
+ arg_types=[object_rprimitive],
85
+ return_type=bit_rprimitive,
86
+ c_function_name="CPy_ExceptionMatches",
87
+ error_kind=ERR_NEVER,
88
+ )
89
+
90
+ # Get the value of the exception currently being handled.
91
+ get_exc_value_op = custom_op(
92
+ arg_types=[],
93
+ return_type=object_rprimitive,
94
+ c_function_name="CPy_GetExcValue",
95
+ error_kind=ERR_NEVER,
96
+ )
97
+
98
+ # Get exception info (exception type, exception instance, traceback object).
99
+ get_exc_info_op = custom_op(
100
+ arg_types=[], return_type=exc_rtuple, c_function_name="CPy_GetExcInfo", error_kind=ERR_NEVER
101
+ )
openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (8.43 kB). View file