hxrron commited on
Commit
5fd9823
·
verified ·
1 Parent(s): 93592af

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. python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/INSTALLER +1 -0
  2. python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/LICENSE.rst +21 -0
  3. python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/METADATA +195 -0
  4. python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/top_level.txt +1 -0
  5. python_embeded/Lib/site-packages/bs4/__init__.py +1170 -0
  6. python_embeded/Lib/site-packages/bs4/_deprecation.py +80 -0
  7. python_embeded/Lib/site-packages/bs4/_typing.py +196 -0
  8. python_embeded/Lib/site-packages/bs4/_warnings.py +98 -0
  9. python_embeded/Lib/site-packages/bs4/element.py +0 -0
  10. python_embeded/Lib/site-packages/bs4/filter.py +759 -0
  11. python_embeded/Lib/site-packages/bs4/formatter.py +276 -0
  12. python_embeded/Lib/site-packages/bs4/py.typed +0 -0
  13. python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/LICENSE +20 -0
  14. python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/METADATA +151 -0
  15. python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/RECORD +14 -0
  16. python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/WHEEL +5 -0
  17. python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/top_level.txt +1 -0
  18. python_embeded/Lib/site-packages/cachetools/__init__.py +738 -0
  19. python_embeded/Lib/site-packages/cachetools/_decorators.py +152 -0
  20. python_embeded/Lib/site-packages/cachetools/func.py +121 -0
  21. python_embeded/Lib/site-packages/cachetools/keys.py +62 -0
  22. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/INSTALLER +1 -0
  23. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/METADATA +77 -0
  24. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/RECORD +16 -0
  25. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/REQUESTED +0 -0
  26. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/WHEEL +5 -0
  27. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/direct_url.json +1 -0
  28. python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/top_level.txt +1 -0
  29. python_embeded/Lib/site-packages/certifi/__init__.py +4 -0
  30. python_embeded/Lib/site-packages/certifi/__main__.py +12 -0
  31. python_embeded/Lib/site-packages/certifi/cacert.pem +0 -0
  32. python_embeded/Lib/site-packages/certifi/core.py +83 -0
  33. python_embeded/Lib/site-packages/certifi/py.typed +0 -0
  34. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/INSTALLER +1 -0
  35. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/LICENSE +26 -0
  36. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/METADATA +40 -0
  37. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/RECORD +50 -0
  38. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/REQUESTED +0 -0
  39. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/WHEEL +5 -0
  40. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/direct_url.json +1 -0
  41. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/entry_points.txt +2 -0
  42. python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/top_level.txt +2 -0
  43. python_embeded/Lib/site-packages/cffi/__init__.py +14 -0
  44. python_embeded/Lib/site-packages/cffi/_cffi_errors.h +149 -0
  45. python_embeded/Lib/site-packages/cffi/_cffi_include.h +389 -0
  46. python_embeded/Lib/site-packages/cffi/_embedding.h +550 -0
  47. python_embeded/Lib/site-packages/cffi/_imp_emulation.py +83 -0
  48. python_embeded/Lib/site-packages/cffi/_shimmed_dist_utils.py +45 -0
  49. python_embeded/Lib/site-packages/cffi/api.py +967 -0
  50. python_embeded/Lib/site-packages/cffi/backend_ctypes.py +1121 -0
python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/LICENSE.rst ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Laurent LAPORTE
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/METADATA ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.2
2
+ Name: Deprecated
3
+ Version: 1.2.18
4
+ Summary: Python @deprecated decorator to deprecate old python classes, functions or methods.
5
+ Home-page: https://github.com/laurent-laporte-pro/deprecated
6
+ Author: Laurent LAPORTE
7
+ Author-email: laurent.laporte.pro@gmail.com
8
+ License: MIT
9
+ Project-URL: Documentation, https://deprecated.readthedocs.io/en/latest/
10
+ Project-URL: Source, https://github.com/laurent-laporte-pro/deprecated
11
+ Project-URL: Bug Tracker, https://github.com/laurent-laporte-pro/deprecated/issues
12
+ Keywords: deprecate,deprecated,deprecation,warning,warn,decorator
13
+ Platform: any
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Environment :: Web Environment
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python
20
+ Classifier: Programming Language :: Python :: 2
21
+ Classifier: Programming Language :: Python :: 2.7
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Programming Language :: Python :: 3.4
24
+ Classifier: Programming Language :: Python :: 3.5
25
+ Classifier: Programming Language :: Python :: 3.6
26
+ Classifier: Programming Language :: Python :: 3.7
27
+ Classifier: Programming Language :: Python :: 3.8
28
+ Classifier: Programming Language :: Python :: 3.9
29
+ Classifier: Programming Language :: Python :: 3.10
30
+ Classifier: Programming Language :: Python :: 3.11
31
+ Classifier: Programming Language :: Python :: 3.12
32
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
33
+ Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*
34
+ Description-Content-Type: text/x-rst
35
+ License-File: LICENSE.rst
36
+ Requires-Dist: wrapt<2,>=1.10
37
+ Provides-Extra: dev
38
+ Requires-Dist: tox; extra == "dev"
39
+ Requires-Dist: PyTest; extra == "dev"
40
+ Requires-Dist: PyTest-Cov; extra == "dev"
41
+ Requires-Dist: bump2version<1; extra == "dev"
42
+ Requires-Dist: setuptools; python_version >= "3.12" and extra == "dev"
43
+ Dynamic: author
44
+ Dynamic: author-email
45
+ Dynamic: classifier
46
+ Dynamic: description
47
+ Dynamic: description-content-type
48
+ Dynamic: home-page
49
+ Dynamic: keywords
50
+ Dynamic: license
51
+ Dynamic: platform
52
+ Dynamic: project-url
53
+ Dynamic: provides-extra
54
+ Dynamic: requires-dist
55
+ Dynamic: requires-python
56
+ Dynamic: summary
57
+
58
+
59
+ Deprecated Library
60
+ ------------------
61
+
62
+ Deprecated is Easy to Use
63
+ `````````````````````````
64
+
65
+ If you need to mark a function or a method as deprecated,
66
+ you can use the ``@deprecated`` decorator:
67
+
68
+ Save in a hello.py:
69
+
70
+ .. code:: python
71
+
72
+ from deprecated import deprecated
73
+
74
+
75
+ @deprecated(version='1.2.1', reason="You should use another function")
76
+ def some_old_function(x, y):
77
+ return x + y
78
+
79
+
80
+ class SomeClass(object):
81
+ @deprecated(version='1.3.0', reason="This method is deprecated")
82
+ def some_old_method(self, x, y):
83
+ return x + y
84
+
85
+
86
+ some_old_function(12, 34)
87
+ obj = SomeClass()
88
+ obj.some_old_method(5, 8)
89
+
90
+
91
+ And Easy to Setup
92
+ `````````````````
93
+
94
+ And run it:
95
+
96
+ .. code:: bash
97
+
98
+ $ pip install Deprecated
99
+ $ python hello.py
100
+ hello.py:15: DeprecationWarning: Call to deprecated function (or staticmethod) some_old_function.
101
+ (You should use another function) -- Deprecated since version 1.2.0.
102
+ some_old_function(12, 34)
103
+ hello.py:17: DeprecationWarning: Call to deprecated method some_old_method.
104
+ (This method is deprecated) -- Deprecated since version 1.3.0.
105
+ obj.some_old_method(5, 8)
106
+
107
+
108
+ You can document your code
109
+ ``````````````````````````
110
+
111
+ Have you ever wonder how to document that some functions, classes, methods, etc. are deprecated?
112
+ This is now possible with the integrated Sphinx directives:
113
+
114
+ For instance, in hello_sphinx.py:
115
+
116
+ .. code:: python
117
+
118
+ from deprecated.sphinx import deprecated
119
+ from deprecated.sphinx import versionadded
120
+ from deprecated.sphinx import versionchanged
121
+
122
+
123
+ @versionadded(version='1.0', reason="This function is new")
124
+ def function_one():
125
+ '''This is the function one'''
126
+
127
+
128
+ @versionchanged(version='1.0', reason="This function is modified")
129
+ def function_two():
130
+ '''This is the function two'''
131
+
132
+
133
+ @deprecated(version='1.0', reason="This function will be removed soon")
134
+ def function_three():
135
+ '''This is the function three'''
136
+
137
+
138
+ function_one()
139
+ function_two()
140
+ function_three() # warns
141
+
142
+ help(function_one)
143
+ help(function_two)
144
+ help(function_three)
145
+
146
+
147
+ The result it immediate
148
+ ```````````````````````
149
+
150
+ Run it:
151
+
152
+ .. code:: bash
153
+
154
+ $ python hello_sphinx.py
155
+
156
+ hello_sphinx.py:23: DeprecationWarning: Call to deprecated function (or staticmethod) function_three.
157
+ (This function will be removed soon) -- Deprecated since version 1.0.
158
+ function_three() # warns
159
+
160
+ Help on function function_one in module __main__:
161
+
162
+ function_one()
163
+ This is the function one
164
+
165
+ .. versionadded:: 1.0
166
+ This function is new
167
+
168
+ Help on function function_two in module __main__:
169
+
170
+ function_two()
171
+ This is the function two
172
+
173
+ .. versionchanged:: 1.0
174
+ This function is modified
175
+
176
+ Help on function function_three in module __main__:
177
+
178
+ function_three()
179
+ This is the function three
180
+
181
+ .. deprecated:: 1.0
182
+ This function will be removed soon
183
+
184
+
185
+ Links
186
+ `````
187
+
188
+ * `Python package index (PyPi) <https://pypi.org/project/Deprecated/>`_
189
+ * `GitHub website <https://github.com/laurent-laporte-pro/deprecated>`_
190
+ * `Read The Docs <https://readthedocs.org/projects/deprecated>`_
191
+ * `EBook on Lulu.com <http://www.lulu.com/commerce/index.php?fBuyContent=21305117>`_
192
+ * `StackOverFlow Q&A <https://stackoverflow.com/a/40301488/1513933>`_
193
+ * `Development version
194
+ <https://github.com/laurent-laporte-pro/deprecated/zipball/master#egg=Deprecated-dev>`_
195
+
python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ deprecated
python_embeded/Lib/site-packages/bs4/__init__.py ADDED
@@ -0,0 +1,1170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Beautiful Soup Elixir and Tonic - "The Screen-Scraper's Friend".
2
+
3
+ http://www.crummy.com/software/BeautifulSoup/
4
+
5
+ Beautiful Soup uses a pluggable XML or HTML parser to parse a
6
+ (possibly invalid) document into a tree representation. Beautiful Soup
7
+ provides methods and Pythonic idioms that make it easy to navigate,
8
+ search, and modify the parse tree.
9
+
10
+ Beautiful Soup works with Python 3.7 and up. It works better if lxml
11
+ and/or html5lib is installed, but they are not required.
12
+
13
+ For more than you ever wanted to know about Beautiful Soup, see the
14
+ documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/
15
+ """
16
+
17
+ __author__ = "Leonard Richardson (leonardr@segfault.org)"
18
+ __version__ = "4.13.4"
19
+ __copyright__ = "Copyright (c) 2004-2025 Leonard Richardson"
20
+ # Use of this source code is governed by the MIT license.
21
+ __license__ = "MIT"
22
+
23
+ __all__ = [
24
+ "AttributeResemblesVariableWarning",
25
+ "BeautifulSoup",
26
+ "Comment",
27
+ "Declaration",
28
+ "ProcessingInstruction",
29
+ "ResultSet",
30
+ "CSS",
31
+ "Script",
32
+ "Stylesheet",
33
+ "Tag",
34
+ "TemplateString",
35
+ "ElementFilter",
36
+ "UnicodeDammit",
37
+ "CData",
38
+ "Doctype",
39
+
40
+ # Exceptions
41
+ "FeatureNotFound",
42
+ "ParserRejectedMarkup",
43
+ "StopParsing",
44
+
45
+ # Warnings
46
+ "AttributeResemblesVariableWarning",
47
+ "GuessedAtParserWarning",
48
+ "MarkupResemblesLocatorWarning",
49
+ "UnusualUsageWarning",
50
+ "XMLParsedAsHTMLWarning",
51
+ ]
52
+
53
+ from collections import Counter
54
+ import sys
55
+ import warnings
56
+
57
+ # The very first thing we do is give a useful error if someone is
58
+ # running this code under Python 2.
59
+ if sys.version_info.major < 3:
60
+ raise ImportError(
61
+ "You are trying to use a Python 3-specific version of Beautiful Soup under Python 2. This will not work. The final version of Beautiful Soup to support Python 2 was 4.9.3."
62
+ )
63
+
64
+ from .builder import (
65
+ builder_registry,
66
+ TreeBuilder,
67
+ )
68
+ from .builder._htmlparser import HTMLParserTreeBuilder
69
+ from .dammit import UnicodeDammit
70
+ from .css import CSS
71
+ from ._deprecation import (
72
+ _deprecated,
73
+ )
74
+ from .element import (
75
+ CData,
76
+ Comment,
77
+ DEFAULT_OUTPUT_ENCODING,
78
+ Declaration,
79
+ Doctype,
80
+ NavigableString,
81
+ PageElement,
82
+ ProcessingInstruction,
83
+ PYTHON_SPECIFIC_ENCODINGS,
84
+ ResultSet,
85
+ Script,
86
+ Stylesheet,
87
+ Tag,
88
+ TemplateString,
89
+ )
90
+ from .formatter import Formatter
91
+ from .filter import (
92
+ ElementFilter,
93
+ SoupStrainer,
94
+ )
95
+ from typing import (
96
+ Any,
97
+ cast,
98
+ Counter as CounterType,
99
+ Dict,
100
+ Iterator,
101
+ List,
102
+ Sequence,
103
+ Optional,
104
+ Type,
105
+ Union,
106
+ )
107
+
108
+ from bs4._typing import (
109
+ _Encoding,
110
+ _Encodings,
111
+ _IncomingMarkup,
112
+ _InsertableElement,
113
+ _RawAttributeValue,
114
+ _RawAttributeValues,
115
+ _RawMarkup,
116
+ )
117
+
118
+ # Import all warnings and exceptions into the main package.
119
+ from bs4.exceptions import (
120
+ FeatureNotFound,
121
+ ParserRejectedMarkup,
122
+ StopParsing,
123
+ )
124
+ from bs4._warnings import (
125
+ AttributeResemblesVariableWarning,
126
+ GuessedAtParserWarning,
127
+ MarkupResemblesLocatorWarning,
128
+ UnusualUsageWarning,
129
+ XMLParsedAsHTMLWarning,
130
+ )
131
+
132
+
133
+ class BeautifulSoup(Tag):
134
+ """A data structure representing a parsed HTML or XML document.
135
+
136
+ Most of the methods you'll call on a BeautifulSoup object are inherited from
137
+ PageElement or Tag.
138
+
139
+ Internally, this class defines the basic interface called by the
140
+ tree builders when converting an HTML/XML document into a data
141
+ structure. The interface abstracts away the differences between
142
+ parsers. To write a new tree builder, you'll need to understand
143
+ these methods as a whole.
144
+
145
+ These methods will be called by the BeautifulSoup constructor:
146
+ * reset()
147
+ * feed(markup)
148
+
149
+ The tree builder may call these methods from its feed() implementation:
150
+ * handle_starttag(name, attrs) # See note about return value
151
+ * handle_endtag(name)
152
+ * handle_data(data) # Appends to the current data node
153
+ * endData(containerClass) # Ends the current data node
154
+
155
+ No matter how complicated the underlying parser is, you should be
156
+ able to build a tree using 'start tag' events, 'end tag' events,
157
+ 'data' events, and "done with data" events.
158
+
159
+ If you encounter an empty-element tag (aka a self-closing tag,
160
+ like HTML's <br> tag), call handle_starttag and then
161
+ handle_endtag.
162
+ """
163
+
164
+ #: Since `BeautifulSoup` subclasses `Tag`, it's possible to treat it as
165
+ #: a `Tag` with a `Tag.name`. Hoever, this name makes it clear the
166
+ #: `BeautifulSoup` object isn't a real markup tag.
167
+ ROOT_TAG_NAME: str = "[document]"
168
+
169
+ #: If the end-user gives no indication which tree builder they
170
+ #: want, look for one with these features.
171
+ DEFAULT_BUILDER_FEATURES: Sequence[str] = ["html", "fast"]
172
+
173
+ #: A string containing all ASCII whitespace characters, used in
174
+ #: during parsing to detect data chunks that seem 'empty'.
175
+ ASCII_SPACES: str = "\x20\x0a\x09\x0c\x0d"
176
+
177
+ # FUTURE PYTHON:
178
+ element_classes: Dict[Type[PageElement], Type[PageElement]] #: :meta private:
179
+ builder: TreeBuilder #: :meta private:
180
+ is_xml: bool
181
+ known_xml: Optional[bool]
182
+ parse_only: Optional[SoupStrainer] #: :meta private:
183
+
184
+ # These members are only used while parsing markup.
185
+ markup: Optional[_RawMarkup] #: :meta private:
186
+ current_data: List[str] #: :meta private:
187
+ currentTag: Optional[Tag] #: :meta private:
188
+ tagStack: List[Tag] #: :meta private:
189
+ open_tag_counter: CounterType[str] #: :meta private:
190
+ preserve_whitespace_tag_stack: List[Tag] #: :meta private:
191
+ string_container_stack: List[Tag] #: :meta private:
192
+ _most_recent_element: Optional[PageElement] #: :meta private:
193
+
194
+ #: Beautiful Soup's best guess as to the character encoding of the
195
+ #: original document.
196
+ original_encoding: Optional[_Encoding]
197
+
198
+ #: The character encoding, if any, that was explicitly defined
199
+ #: in the original document. This may or may not match
200
+ #: `BeautifulSoup.original_encoding`.
201
+ declared_html_encoding: Optional[_Encoding]
202
+
203
+ #: This is True if the markup that was parsed contains
204
+ #: U+FFFD REPLACEMENT_CHARACTER characters which were not present
205
+ #: in the original markup. These mark character sequences that
206
+ #: could not be represented in Unicode.
207
+ contains_replacement_characters: bool
208
+
209
+ def __init__(
210
+ self,
211
+ markup: _IncomingMarkup = "",
212
+ features: Optional[Union[str, Sequence[str]]] = None,
213
+ builder: Optional[Union[TreeBuilder, Type[TreeBuilder]]] = None,
214
+ parse_only: Optional[SoupStrainer] = None,
215
+ from_encoding: Optional[_Encoding] = None,
216
+ exclude_encodings: Optional[_Encodings] = None,
217
+ element_classes: Optional[Dict[Type[PageElement], Type[PageElement]]] = None,
218
+ **kwargs: Any,
219
+ ):
220
+ """Constructor.
221
+
222
+ :param markup: A string or a file-like object representing
223
+ markup to be parsed.
224
+
225
+ :param features: Desirable features of the parser to be
226
+ used. This may be the name of a specific parser ("lxml",
227
+ "lxml-xml", "html.parser", or "html5lib") or it may be the
228
+ type of markup to be used ("html", "html5", "xml"). It's
229
+ recommended that you name a specific parser, so that
230
+ Beautiful Soup gives you the same results across platforms
231
+ and virtual environments.
232
+
233
+ :param builder: A TreeBuilder subclass to instantiate (or
234
+ instance to use) instead of looking one up based on
235
+ `features`. You only need to use this if you've implemented a
236
+ custom TreeBuilder.
237
+
238
+ :param parse_only: A SoupStrainer. Only parts of the document
239
+ matching the SoupStrainer will be considered. This is useful
240
+ when parsing part of a document that would otherwise be too
241
+ large to fit into memory.
242
+
243
+ :param from_encoding: A string indicating the encoding of the
244
+ document to be parsed. Pass this in if Beautiful Soup is
245
+ guessing wrongly about the document's encoding.
246
+
247
+ :param exclude_encodings: A list of strings indicating
248
+ encodings known to be wrong. Pass this in if you don't know
249
+ the document's encoding but you know Beautiful Soup's guess is
250
+ wrong.
251
+
252
+ :param element_classes: A dictionary mapping BeautifulSoup
253
+ classes like Tag and NavigableString, to other classes you'd
254
+ like to be instantiated instead as the parse tree is
255
+ built. This is useful for subclassing Tag or NavigableString
256
+ to modify default behavior.
257
+
258
+ :param kwargs: For backwards compatibility purposes, the
259
+ constructor accepts certain keyword arguments used in
260
+ Beautiful Soup 3. None of these arguments do anything in
261
+ Beautiful Soup 4; they will result in a warning and then be
262
+ ignored.
263
+
264
+ Apart from this, any keyword arguments passed into the
265
+ BeautifulSoup constructor are propagated to the TreeBuilder
266
+ constructor. This makes it possible to configure a
267
+ TreeBuilder by passing in arguments, not just by saying which
268
+ one to use.
269
+ """
270
+ if "convertEntities" in kwargs:
271
+ del kwargs["convertEntities"]
272
+ warnings.warn(
273
+ "BS4 does not respect the convertEntities argument to the "
274
+ "BeautifulSoup constructor. Entities are always converted "
275
+ "to Unicode characters."
276
+ )
277
+
278
+ if "markupMassage" in kwargs:
279
+ del kwargs["markupMassage"]
280
+ warnings.warn(
281
+ "BS4 does not respect the markupMassage argument to the "
282
+ "BeautifulSoup constructor. The tree builder is responsible "
283
+ "for any necessary markup massage."
284
+ )
285
+
286
+ if "smartQuotesTo" in kwargs:
287
+ del kwargs["smartQuotesTo"]
288
+ warnings.warn(
289
+ "BS4 does not respect the smartQuotesTo argument to the "
290
+ "BeautifulSoup constructor. Smart quotes are always converted "
291
+ "to Unicode characters."
292
+ )
293
+
294
+ if "selfClosingTags" in kwargs:
295
+ del kwargs["selfClosingTags"]
296
+ warnings.warn(
297
+ "Beautiful Soup 4 does not respect the selfClosingTags argument to the "
298
+ "BeautifulSoup constructor. The tree builder is responsible "
299
+ "for understanding self-closing tags."
300
+ )
301
+
302
+ if "isHTML" in kwargs:
303
+ del kwargs["isHTML"]
304
+ warnings.warn(
305
+ "Beautiful Soup 4 does not respect the isHTML argument to the "
306
+ "BeautifulSoup constructor. Suggest you use "
307
+ "features='lxml' for HTML and features='lxml-xml' for "
308
+ "XML."
309
+ )
310
+
311
+ def deprecated_argument(old_name: str, new_name: str) -> Optional[Any]:
312
+ if old_name in kwargs:
313
+ warnings.warn(
314
+ 'The "%s" argument to the BeautifulSoup constructor '
315
+ 'was renamed to "%s" in Beautiful Soup 4.0.0'
316
+ % (old_name, new_name),
317
+ DeprecationWarning,
318
+ stacklevel=3,
319
+ )
320
+ return kwargs.pop(old_name)
321
+ return None
322
+
323
+ parse_only = parse_only or deprecated_argument("parseOnlyThese", "parse_only")
324
+ if parse_only is not None:
325
+ # Issue a warning if we can tell in advance that
326
+ # parse_only will exclude the entire tree.
327
+ if parse_only.excludes_everything:
328
+ warnings.warn(
329
+ f"The given value for parse_only will exclude everything: {parse_only}",
330
+ UserWarning,
331
+ stacklevel=3,
332
+ )
333
+
334
+ from_encoding = from_encoding or deprecated_argument(
335
+ "fromEncoding", "from_encoding"
336
+ )
337
+
338
+ if from_encoding and isinstance(markup, str):
339
+ warnings.warn(
340
+ "You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored."
341
+ )
342
+ from_encoding = None
343
+
344
+ self.element_classes = element_classes or dict()
345
+
346
+ # We need this information to track whether or not the builder
347
+ # was specified well enough that we can omit the 'you need to
348
+ # specify a parser' warning.
349
+ original_builder = builder
350
+ original_features = features
351
+
352
+ builder_class: Type[TreeBuilder]
353
+ if isinstance(builder, type):
354
+ # A builder class was passed in; it needs to be instantiated.
355
+ builder_class = builder
356
+ builder = None
357
+ elif builder is None:
358
+ if isinstance(features, str):
359
+ features = [features]
360
+ if features is None or len(features) == 0:
361
+ features = self.DEFAULT_BUILDER_FEATURES
362
+ possible_builder_class = builder_registry.lookup(*features)
363
+ if possible_builder_class is None:
364
+ raise FeatureNotFound(
365
+ "Couldn't find a tree builder with the features you "
366
+ "requested: %s. Do you need to install a parser library?"
367
+ % ",".join(features)
368
+ )
369
+ builder_class = possible_builder_class
370
+
371
+ # At this point either we have a TreeBuilder instance in
372
+ # builder, or we have a builder_class that we can instantiate
373
+ # with the remaining **kwargs.
374
+ if builder is None:
375
+ builder = builder_class(**kwargs)
376
+ if (
377
+ not original_builder
378
+ and not (
379
+ original_features == builder.NAME
380
+ or (
381
+ isinstance(original_features, str)
382
+ and original_features in builder.ALTERNATE_NAMES
383
+ )
384
+ )
385
+ and markup
386
+ ):
387
+ # The user did not tell us which TreeBuilder to use,
388
+ # and we had to guess. Issue a warning.
389
+ if builder.is_xml:
390
+ markup_type = "XML"
391
+ else:
392
+ markup_type = "HTML"
393
+
394
+ # This code adapted from warnings.py so that we get the same line
395
+ # of code as our warnings.warn() call gets, even if the answer is wrong
396
+ # (as it may be in a multithreading situation).
397
+ caller = None
398
+ try:
399
+ caller = sys._getframe(1)
400
+ except ValueError:
401
+ pass
402
+ if caller:
403
+ globals = caller.f_globals
404
+ line_number = caller.f_lineno
405
+ else:
406
+ globals = sys.__dict__
407
+ line_number = 1
408
+ filename = globals.get("__file__")
409
+ if filename:
410
+ fnl = filename.lower()
411
+ if fnl.endswith((".pyc", ".pyo")):
412
+ filename = filename[:-1]
413
+ if filename:
414
+ # If there is no filename at all, the user is most likely in a REPL,
415
+ # and the warning is not necessary.
416
+ values = dict(
417
+ filename=filename,
418
+ line_number=line_number,
419
+ parser=builder.NAME,
420
+ markup_type=markup_type,
421
+ )
422
+ warnings.warn(
423
+ GuessedAtParserWarning.MESSAGE % values,
424
+ GuessedAtParserWarning,
425
+ stacklevel=2,
426
+ )
427
+ else:
428
+ if kwargs:
429
+ warnings.warn(
430
+ "Keyword arguments to the BeautifulSoup constructor will be ignored. These would normally be passed into the TreeBuilder constructor, but a TreeBuilder instance was passed in as `builder`."
431
+ )
432
+
433
+ self.builder = builder
434
+ self.is_xml = builder.is_xml
435
+ self.known_xml = self.is_xml
436
+ self._namespaces = dict()
437
+ self.parse_only = parse_only
438
+
439
+ if hasattr(markup, "read"): # It's a file-type object.
440
+ markup = markup.read()
441
+ elif not isinstance(markup, (bytes, str)) and not hasattr(markup, "__len__"):
442
+ raise TypeError(
443
+ f"Incoming markup is of an invalid type: {markup!r}. Markup must be a string, a bytestring, or an open filehandle."
444
+ )
445
+ elif len(markup) <= 256 and (
446
+ (isinstance(markup, bytes) and b"<" not in markup and b"\n" not in markup)
447
+ or (isinstance(markup, str) and "<" not in markup and "\n" not in markup)
448
+ ):
449
+ # Issue warnings for a couple beginner problems
450
+ # involving passing non-markup to Beautiful Soup.
451
+ # Beautiful Soup will still parse the input as markup,
452
+ # since that is sometimes the intended behavior.
453
+ if not self._markup_is_url(markup):
454
+ self._markup_resembles_filename(markup)
455
+
456
+ # At this point we know markup is a string or bytestring. If
457
+ # it was a file-type object, we've read from it.
458
+ markup = cast(_RawMarkup, markup)
459
+
460
+ rejections = []
461
+ success = False
462
+ for (
463
+ self.markup,
464
+ self.original_encoding,
465
+ self.declared_html_encoding,
466
+ self.contains_replacement_characters,
467
+ ) in self.builder.prepare_markup(
468
+ markup, from_encoding, exclude_encodings=exclude_encodings
469
+ ):
470
+ self.reset()
471
+ self.builder.initialize_soup(self)
472
+ try:
473
+ self._feed()
474
+ success = True
475
+ break
476
+ except ParserRejectedMarkup as e:
477
+ rejections.append(e)
478
+ pass
479
+
480
+ if not success:
481
+ other_exceptions = [str(e) for e in rejections]
482
+ raise ParserRejectedMarkup(
483
+ "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.\n\nOriginal exception(s) from parser:\n "
484
+ + "\n ".join(other_exceptions)
485
+ )
486
+
487
+ # Clear out the markup and remove the builder's circular
488
+ # reference to this object.
489
+ self.markup = None
490
+ self.builder.soup = None
491
+
492
+ def copy_self(self) -> "BeautifulSoup":
493
+ """Create a new BeautifulSoup object with the same TreeBuilder,
494
+ but not associated with any markup.
495
+
496
+ This is the first step of the deepcopy process.
497
+ """
498
+ clone = type(self)("", None, self.builder)
499
+
500
+ # Keep track of the encoding of the original document,
501
+ # since we won't be parsing it again.
502
+ clone.original_encoding = self.original_encoding
503
+ return clone
504
+
505
+ def __getstate__(self) -> Dict[str, Any]:
506
+ # Frequently a tree builder can't be pickled.
507
+ d = dict(self.__dict__)
508
+ if "builder" in d and d["builder"] is not None and not self.builder.picklable:
509
+ d["builder"] = type(self.builder)
510
+ # Store the contents as a Unicode string.
511
+ d["contents"] = []
512
+ d["markup"] = self.decode()
513
+
514
+ # If _most_recent_element is present, it's a Tag object left
515
+ # over from initial parse. It might not be picklable and we
516
+ # don't need it.
517
+ if "_most_recent_element" in d:
518
+ del d["_most_recent_element"]
519
+ return d
520
+
521
+ def __setstate__(self, state: Dict[str, Any]) -> None:
522
+ # If necessary, restore the TreeBuilder by looking it up.
523
+ self.__dict__ = state
524
+ if isinstance(self.builder, type):
525
+ self.builder = self.builder()
526
+ elif not self.builder:
527
+ # We don't know which builder was used to build this
528
+ # parse tree, so use a default we know is always available.
529
+ self.builder = HTMLParserTreeBuilder()
530
+ self.builder.soup = self
531
+ self.reset()
532
+ self._feed()
533
+
534
+ @classmethod
535
+ @_deprecated(
536
+ replaced_by="nothing (private method, will be removed)", version="4.13.0"
537
+ )
538
+ def _decode_markup(cls, markup: _RawMarkup) -> str:
539
+ """Ensure `markup` is Unicode so it's safe to send into warnings.warn.
540
+
541
+ warnings.warn had this problem back in 2010 but fortunately
542
+ not anymore. This has not been used for a long time; I just
543
+ noticed that fact while working on 4.13.0.
544
+ """
545
+ if isinstance(markup, bytes):
546
+ decoded = markup.decode("utf-8", "replace")
547
+ else:
548
+ decoded = markup
549
+ return decoded
550
+
551
+ @classmethod
552
+ def _markup_is_url(cls, markup: _RawMarkup) -> bool:
553
+ """Error-handling method to raise a warning if incoming markup looks
554
+ like a URL.
555
+
556
+ :param markup: A string of markup.
557
+ :return: Whether or not the markup resembled a URL
558
+ closely enough to justify issuing a warning.
559
+ """
560
+ problem: bool = False
561
+ if isinstance(markup, bytes):
562
+ problem = (
563
+ any(markup.startswith(prefix) for prefix in (b"http:", b"https:"))
564
+ and b" " not in markup
565
+ )
566
+ elif isinstance(markup, str):
567
+ problem = (
568
+ any(markup.startswith(prefix) for prefix in ("http:", "https:"))
569
+ and " " not in markup
570
+ )
571
+ else:
572
+ return False
573
+
574
+ if not problem:
575
+ return False
576
+ warnings.warn(
577
+ MarkupResemblesLocatorWarning.URL_MESSAGE % dict(what="URL"),
578
+ MarkupResemblesLocatorWarning,
579
+ stacklevel=3,
580
+ )
581
+ return True
582
+
583
+ @classmethod
584
+ def _markup_resembles_filename(cls, markup: _RawMarkup) -> bool:
585
+ """Error-handling method to issue a warning if incoming markup
586
+ resembles a filename.
587
+
588
+ :param markup: A string of markup.
589
+ :return: Whether or not the markup resembled a filename
590
+ closely enough to justify issuing a warning.
591
+ """
592
+ markup_b: bytes
593
+
594
+ # We're only checking ASCII characters, so rather than write
595
+ # the same tests twice, convert Unicode to a bytestring and
596
+ # operate on the bytestring.
597
+ if isinstance(markup, str):
598
+ markup_b = markup.encode("utf8")
599
+ else:
600
+ markup_b = markup
601
+
602
+ # Step 1: does it end with a common textual file extension?
603
+ filelike = False
604
+ lower = markup_b.lower()
605
+ extensions = [b".html", b".htm", b".xml", b".xhtml", b".txt"]
606
+ if any(lower.endswith(ext) for ext in extensions):
607
+ filelike = True
608
+ if not filelike:
609
+ return False
610
+
611
+ # Step 2: it _might_ be a file, but there are a few things
612
+ # we can look for that aren't very common in filenames.
613
+
614
+ # Characters that have special meaning to Unix shells. (< was
615
+ # excluded before this method was called.)
616
+ #
617
+ # Many of these are also reserved characters that cannot
618
+ # appear in Windows filenames.
619
+ for byte in markup_b:
620
+ if byte in b"?*#&;>$|":
621
+ return False
622
+
623
+ # Two consecutive forward slashes (as seen in a URL) or two
624
+ # consecutive spaces (as seen in fixed-width data).
625
+ #
626
+ # (Paths to Windows network shares contain consecutive
627
+ # backslashes, so checking that doesn't seem as helpful.)
628
+ if b"//" in markup_b:
629
+ return False
630
+ if b" " in markup_b:
631
+ return False
632
+
633
+ # A colon in any position other than position 1 (e.g. after a
634
+ # Windows drive letter).
635
+ if markup_b.startswith(b":"):
636
+ return False
637
+ colon_i = markup_b.rfind(b":")
638
+ if colon_i not in (-1, 1):
639
+ return False
640
+
641
+ # Step 3: If it survived all of those checks, it's similar
642
+ # enough to a file to justify issuing a warning.
643
+ warnings.warn(
644
+ MarkupResemblesLocatorWarning.FILENAME_MESSAGE % dict(what="filename"),
645
+ MarkupResemblesLocatorWarning,
646
+ stacklevel=3,
647
+ )
648
+ return True
649
+
650
+ def _feed(self) -> None:
651
+ """Internal method that parses previously set markup, creating a large
652
+ number of Tag and NavigableString objects.
653
+ """
654
+ # Convert the document to Unicode.
655
+ self.builder.reset()
656
+
657
+ if self.markup is not None:
658
+ self.builder.feed(self.markup)
659
+ # Close out any unfinished strings and close all the open tags.
660
+ self.endData()
661
+ while (
662
+ self.currentTag is not None and self.currentTag.name != self.ROOT_TAG_NAME
663
+ ):
664
+ self.popTag()
665
+
666
+ def reset(self) -> None:
667
+ """Reset this object to a state as though it had never parsed any
668
+ markup.
669
+ """
670
+ Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME)
671
+ self.hidden = True
672
+ self.builder.reset()
673
+ self.current_data = []
674
+ self.currentTag = None
675
+ self.tagStack = []
676
+ self.open_tag_counter = Counter()
677
+ self.preserve_whitespace_tag_stack = []
678
+ self.string_container_stack = []
679
+ self._most_recent_element = None
680
+ self.pushTag(self)
681
+
682
+ def new_tag(
683
+ self,
684
+ name: str,
685
+ namespace: Optional[str] = None,
686
+ nsprefix: Optional[str] = None,
687
+ attrs: Optional[_RawAttributeValues] = None,
688
+ sourceline: Optional[int] = None,
689
+ sourcepos: Optional[int] = None,
690
+ string: Optional[str] = None,
691
+ **kwattrs: _RawAttributeValue,
692
+ ) -> Tag:
693
+ """Create a new Tag associated with this BeautifulSoup object.
694
+
695
+ :param name: The name of the new Tag.
696
+ :param namespace: The URI of the new Tag's XML namespace, if any.
697
+ :param prefix: The prefix for the new Tag's XML namespace, if any.
698
+ :param attrs: A dictionary of this Tag's attribute values; can
699
+ be used instead of ``kwattrs`` for attributes like 'class'
700
+ that are reserved words in Python.
701
+ :param sourceline: The line number where this tag was
702
+ (purportedly) found in its source document.
703
+ :param sourcepos: The character position within ``sourceline`` where this
704
+ tag was (purportedly) found.
705
+ :param string: String content for the new Tag, if any.
706
+ :param kwattrs: Keyword arguments for the new Tag's attribute values.
707
+
708
+ """
709
+ attr_container = self.builder.attribute_dict_class(**kwattrs)
710
+ if attrs is not None:
711
+ attr_container.update(attrs)
712
+ tag_class = self.element_classes.get(Tag, Tag)
713
+
714
+ # Assume that this is either Tag or a subclass of Tag. If not,
715
+ # the user brought type-unsafety upon themselves.
716
+ tag_class = cast(Type[Tag], tag_class)
717
+ tag = tag_class(
718
+ None,
719
+ self.builder,
720
+ name,
721
+ namespace,
722
+ nsprefix,
723
+ attr_container,
724
+ sourceline=sourceline,
725
+ sourcepos=sourcepos,
726
+ )
727
+
728
+ if string is not None:
729
+ tag.string = string
730
+ return tag
731
+
732
+ def string_container(
733
+ self, base_class: Optional[Type[NavigableString]] = None
734
+ ) -> Type[NavigableString]:
735
+ """Find the class that should be instantiated to hold a given kind of
736
+ string.
737
+
738
+ This may be a built-in Beautiful Soup class or a custom class passed
739
+ in to the BeautifulSoup constructor.
740
+ """
741
+ container = base_class or NavigableString
742
+
743
+ # The user may want us to use some other class (hopefully a
744
+ # custom subclass) instead of the one we'd use normally.
745
+ container = cast(
746
+ Type[NavigableString], self.element_classes.get(container, container)
747
+ )
748
+
749
+ # On top of that, we may be inside a tag that needs a special
750
+ # container class.
751
+ if self.string_container_stack and container is NavigableString:
752
+ container = self.builder.string_containers.get(
753
+ self.string_container_stack[-1].name, container
754
+ )
755
+ return container
756
+
757
+ def new_string(
758
+ self, s: str, subclass: Optional[Type[NavigableString]] = None
759
+ ) -> NavigableString:
760
+ """Create a new `NavigableString` associated with this `BeautifulSoup`
761
+ object.
762
+
763
+ :param s: The string content of the `NavigableString`
764
+ :param subclass: The subclass of `NavigableString`, if any, to
765
+ use. If a document is being processed, an appropriate
766
+ subclass for the current location in the document will
767
+ be determined automatically.
768
+ """
769
+ container = self.string_container(subclass)
770
+ return container(s)
771
+
772
+ def insert_before(self, *args: _InsertableElement) -> List[PageElement]:
773
+ """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement
774
+ it because there is nothing before or after it in the parse tree.
775
+ """
776
+ raise NotImplementedError(
777
+ "BeautifulSoup objects don't support insert_before()."
778
+ )
779
+
780
+ def insert_after(self, *args: _InsertableElement) -> List[PageElement]:
781
+ """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement
782
+ it because there is nothing before or after it in the parse tree.
783
+ """
784
+ raise NotImplementedError("BeautifulSoup objects don't support insert_after().")
785
+
786
+ def popTag(self) -> Optional[Tag]:
787
+ """Internal method called by _popToTag when a tag is closed.
788
+
789
+ :meta private:
790
+ """
791
+ if not self.tagStack:
792
+ # Nothing to pop. This shouldn't happen.
793
+ return None
794
+ tag = self.tagStack.pop()
795
+ if tag.name in self.open_tag_counter:
796
+ self.open_tag_counter[tag.name] -= 1
797
+ if (
798
+ self.preserve_whitespace_tag_stack
799
+ and tag == self.preserve_whitespace_tag_stack[-1]
800
+ ):
801
+ self.preserve_whitespace_tag_stack.pop()
802
+ if self.string_container_stack and tag == self.string_container_stack[-1]:
803
+ self.string_container_stack.pop()
804
+ # print("Pop", tag.name)
805
+ if self.tagStack:
806
+ self.currentTag = self.tagStack[-1]
807
+ return self.currentTag
808
+
809
+ def pushTag(self, tag: Tag) -> None:
810
+ """Internal method called by handle_starttag when a tag is opened.
811
+
812
+ :meta private:
813
+ """
814
+ # print("Push", tag.name)
815
+ if self.currentTag is not None:
816
+ self.currentTag.contents.append(tag)
817
+ self.tagStack.append(tag)
818
+ self.currentTag = self.tagStack[-1]
819
+ if tag.name != self.ROOT_TAG_NAME:
820
+ self.open_tag_counter[tag.name] += 1
821
+ if tag.name in self.builder.preserve_whitespace_tags:
822
+ self.preserve_whitespace_tag_stack.append(tag)
823
+ if tag.name in self.builder.string_containers:
824
+ self.string_container_stack.append(tag)
825
+
826
+ def endData(self, containerClass: Optional[Type[NavigableString]] = None) -> None:
827
+ """Method called by the TreeBuilder when the end of a data segment
828
+ occurs.
829
+
830
+ :param containerClass: The class to use when incorporating the
831
+ data segment into the parse tree.
832
+
833
+ :meta private:
834
+ """
835
+ if self.current_data:
836
+ current_data = "".join(self.current_data)
837
+ # If whitespace is not preserved, and this string contains
838
+ # nothing but ASCII spaces, replace it with a single space
839
+ # or newline.
840
+ if not self.preserve_whitespace_tag_stack:
841
+ strippable = True
842
+ for i in current_data:
843
+ if i not in self.ASCII_SPACES:
844
+ strippable = False
845
+ break
846
+ if strippable:
847
+ if "\n" in current_data:
848
+ current_data = "\n"
849
+ else:
850
+ current_data = " "
851
+
852
+ # Reset the data collector.
853
+ self.current_data = []
854
+
855
+ # Should we add this string to the tree at all?
856
+ if (
857
+ self.parse_only
858
+ and len(self.tagStack) <= 1
859
+ and (not self.parse_only.allow_string_creation(current_data))
860
+ ):
861
+ return
862
+
863
+ containerClass = self.string_container(containerClass)
864
+ o = containerClass(current_data)
865
+ self.object_was_parsed(o)
866
+
867
+ def object_was_parsed(
868
+ self,
869
+ o: PageElement,
870
+ parent: Optional[Tag] = None,
871
+ most_recent_element: Optional[PageElement] = None,
872
+ ) -> None:
873
+ """Method called by the TreeBuilder to integrate an object into the
874
+ parse tree.
875
+
876
+ :meta private:
877
+ """
878
+ if parent is None:
879
+ parent = self.currentTag
880
+ assert parent is not None
881
+ previous_element: Optional[PageElement]
882
+ if most_recent_element is not None:
883
+ previous_element = most_recent_element
884
+ else:
885
+ previous_element = self._most_recent_element
886
+
887
+ next_element = previous_sibling = next_sibling = None
888
+ if isinstance(o, Tag):
889
+ next_element = o.next_element
890
+ next_sibling = o.next_sibling
891
+ previous_sibling = o.previous_sibling
892
+ if previous_element is None:
893
+ previous_element = o.previous_element
894
+
895
+ fix = parent.next_element is not None
896
+
897
+ o.setup(parent, previous_element, next_element, previous_sibling, next_sibling)
898
+
899
+ self._most_recent_element = o
900
+ parent.contents.append(o)
901
+
902
+ # Check if we are inserting into an already parsed node.
903
+ if fix:
904
+ self._linkage_fixer(parent)
905
+
906
+ def _linkage_fixer(self, el: Tag) -> None:
907
+ """Make sure linkage of this fragment is sound."""
908
+
909
+ first = el.contents[0]
910
+ child = el.contents[-1]
911
+ descendant: PageElement = child
912
+
913
+ if child is first and el.parent is not None:
914
+ # Parent should be linked to first child
915
+ el.next_element = child
916
+ # We are no longer linked to whatever this element is
917
+ prev_el = child.previous_element
918
+ if prev_el is not None and prev_el is not el:
919
+ prev_el.next_element = None
920
+ # First child should be linked to the parent, and no previous siblings.
921
+ child.previous_element = el
922
+ child.previous_sibling = None
923
+
924
+ # We have no sibling as we've been appended as the last.
925
+ child.next_sibling = None
926
+
927
+ # This index is a tag, dig deeper for a "last descendant"
928
+ if isinstance(child, Tag) and child.contents:
929
+ # _last_decendant is typed as returning Optional[PageElement],
930
+ # but the value can't be None here, because el is a Tag
931
+ # which we know has contents.
932
+ descendant = cast(PageElement, child._last_descendant(False))
933
+
934
+ # As the final step, link last descendant. It should be linked
935
+ # to the parent's next sibling (if found), else walk up the chain
936
+ # and find a parent with a sibling. It should have no next sibling.
937
+ descendant.next_element = None
938
+ descendant.next_sibling = None
939
+
940
+ target: Optional[Tag] = el
941
+ while True:
942
+ if target is None:
943
+ break
944
+ elif target.next_sibling is not None:
945
+ descendant.next_element = target.next_sibling
946
+ target.next_sibling.previous_element = child
947
+ break
948
+ target = target.parent
949
+
950
+ def _popToTag(
951
+ self, name: str, nsprefix: Optional[str] = None, inclusivePop: bool = True
952
+ ) -> Optional[Tag]:
953
+ """Pops the tag stack up to and including the most recent
954
+ instance of the given tag.
955
+
956
+ If there are no open tags with the given name, nothing will be
957
+ popped.
958
+
959
+ :param name: Pop up to the most recent tag with this name.
960
+ :param nsprefix: The namespace prefix that goes with `name`.
961
+ :param inclusivePop: It this is false, pops the tag stack up
962
+ to but *not* including the most recent instqance of the
963
+ given tag.
964
+
965
+ :meta private:
966
+ """
967
+ # print("Popping to %s" % name)
968
+ if name == self.ROOT_TAG_NAME:
969
+ # The BeautifulSoup object itself can never be popped.
970
+ return None
971
+
972
+ most_recently_popped = None
973
+
974
+ stack_size = len(self.tagStack)
975
+ for i in range(stack_size - 1, 0, -1):
976
+ if not self.open_tag_counter.get(name):
977
+ break
978
+ t = self.tagStack[i]
979
+ if name == t.name and nsprefix == t.prefix:
980
+ if inclusivePop:
981
+ most_recently_popped = self.popTag()
982
+ break
983
+ most_recently_popped = self.popTag()
984
+
985
+ return most_recently_popped
986
+
987
+ def handle_starttag(
988
+ self,
989
+ name: str,
990
+ namespace: Optional[str],
991
+ nsprefix: Optional[str],
992
+ attrs: _RawAttributeValues,
993
+ sourceline: Optional[int] = None,
994
+ sourcepos: Optional[int] = None,
995
+ namespaces: Optional[Dict[str, str]] = None,
996
+ ) -> Optional[Tag]:
997
+ """Called by the tree builder when a new tag is encountered.
998
+
999
+ :param name: Name of the tag.
1000
+ :param nsprefix: Namespace prefix for the tag.
1001
+ :param attrs: A dictionary of attribute values. Note that
1002
+ attribute values are expected to be simple strings; processing
1003
+ of multi-valued attributes such as "class" comes later.
1004
+ :param sourceline: The line number where this tag was found in its
1005
+ source document.
1006
+ :param sourcepos: The character position within `sourceline` where this
1007
+ tag was found.
1008
+ :param namespaces: A dictionary of all namespace prefix mappings
1009
+ currently in scope in the document.
1010
+
1011
+ If this method returns None, the tag was rejected by an active
1012
+ `ElementFilter`. You should proceed as if the tag had not occurred
1013
+ in the document. For instance, if this was a self-closing tag,
1014
+ don't call handle_endtag.
1015
+
1016
+ :meta private:
1017
+ """
1018
+ # print("Start tag %s: %s" % (name, attrs))
1019
+ self.endData()
1020
+
1021
+ if (
1022
+ self.parse_only
1023
+ and len(self.tagStack) <= 1
1024
+ and not self.parse_only.allow_tag_creation(nsprefix, name, attrs)
1025
+ ):
1026
+ return None
1027
+
1028
+ tag_class = self.element_classes.get(Tag, Tag)
1029
+ # Assume that this is either Tag or a subclass of Tag. If not,
1030
+ # the user brought type-unsafety upon themselves.
1031
+ tag_class = cast(Type[Tag], tag_class)
1032
+ tag = tag_class(
1033
+ self,
1034
+ self.builder,
1035
+ name,
1036
+ namespace,
1037
+ nsprefix,
1038
+ attrs,
1039
+ self.currentTag,
1040
+ self._most_recent_element,
1041
+ sourceline=sourceline,
1042
+ sourcepos=sourcepos,
1043
+ namespaces=namespaces,
1044
+ )
1045
+ if tag is None:
1046
+ return tag
1047
+ if self._most_recent_element is not None:
1048
+ self._most_recent_element.next_element = tag
1049
+ self._most_recent_element = tag
1050
+ self.pushTag(tag)
1051
+ return tag
1052
+
1053
+ def handle_endtag(self, name: str, nsprefix: Optional[str] = None) -> None:
1054
+ """Called by the tree builder when an ending tag is encountered.
1055
+
1056
+ :param name: Name of the tag.
1057
+ :param nsprefix: Namespace prefix for the tag.
1058
+
1059
+ :meta private:
1060
+ """
1061
+ # print("End tag: " + name)
1062
+ self.endData()
1063
+ self._popToTag(name, nsprefix)
1064
+
1065
+ def handle_data(self, data: str) -> None:
1066
+ """Called by the tree builder when a chunk of textual data is
1067
+ encountered.
1068
+
1069
+ :meta private:
1070
+ """
1071
+ self.current_data.append(data)
1072
+
1073
+ def decode(
1074
+ self,
1075
+ indent_level: Optional[int] = None,
1076
+ eventual_encoding: _Encoding = DEFAULT_OUTPUT_ENCODING,
1077
+ formatter: Union[Formatter, str] = "minimal",
1078
+ iterator: Optional[Iterator[PageElement]] = None,
1079
+ **kwargs: Any,
1080
+ ) -> str:
1081
+ """Returns a string representation of the parse tree
1082
+ as a full HTML or XML document.
1083
+
1084
+ :param indent_level: Each line of the rendering will be
1085
+ indented this many levels. (The ``formatter`` decides what a
1086
+ 'level' means, in terms of spaces or other characters
1087
+ output.) This is used internally in recursive calls while
1088
+ pretty-printing.
1089
+ :param eventual_encoding: The encoding of the final document.
1090
+ If this is None, the document will be a Unicode string.
1091
+ :param formatter: Either a `Formatter` object, or a string naming one of
1092
+ the standard formatters.
1093
+ :param iterator: The iterator to use when navigating over the
1094
+ parse tree. This is only used by `Tag.decode_contents` and
1095
+ you probably won't need to use it.
1096
+ """
1097
+ if self.is_xml:
1098
+ # Print the XML declaration
1099
+ encoding_part = ""
1100
+ declared_encoding: Optional[str] = eventual_encoding
1101
+ if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS:
1102
+ # This is a special Python encoding; it can't actually
1103
+ # go into an XML document because it means nothing
1104
+ # outside of Python.
1105
+ declared_encoding = None
1106
+ if declared_encoding is not None:
1107
+ encoding_part = ' encoding="%s"' % declared_encoding
1108
+ prefix = '<?xml version="1.0"%s?>\n' % encoding_part
1109
+ else:
1110
+ prefix = ""
1111
+
1112
+ # Prior to 4.13.0, the first argument to this method was a
1113
+ # bool called pretty_print, which gave the method a different
1114
+ # signature from its superclass implementation, Tag.decode.
1115
+ #
1116
+ # The signatures of the two methods now match, but just in
1117
+ # case someone is still passing a boolean in as the first
1118
+ # argument to this method (or a keyword argument with the old
1119
+ # name), we can handle it and put out a DeprecationWarning.
1120
+ warning: Optional[str] = None
1121
+ if isinstance(indent_level, bool):
1122
+ if indent_level is True:
1123
+ indent_level = 0
1124
+ elif indent_level is False:
1125
+ indent_level = None
1126
+ warning = f"As of 4.13.0, the first argument to BeautifulSoup.decode has been changed from bool to int, to match Tag.decode. Pass in a value of {indent_level} instead."
1127
+ else:
1128
+ pretty_print = kwargs.pop("pretty_print", None)
1129
+ assert not kwargs
1130
+ if pretty_print is not None:
1131
+ if pretty_print is True:
1132
+ indent_level = 0
1133
+ elif pretty_print is False:
1134
+ indent_level = None
1135
+ warning = f"As of 4.13.0, the pretty_print argument to BeautifulSoup.decode has been removed, to match Tag.decode. Pass in a value of indent_level={indent_level} instead."
1136
+
1137
+ if warning:
1138
+ warnings.warn(warning, DeprecationWarning, stacklevel=2)
1139
+ elif indent_level is False or pretty_print is False:
1140
+ indent_level = None
1141
+ return prefix + super(BeautifulSoup, self).decode(
1142
+ indent_level, eventual_encoding, formatter, iterator
1143
+ )
1144
+
1145
+
1146
+ # Aliases to make it easier to get started quickly, e.g. 'from bs4 import _soup'
1147
+ _s = BeautifulSoup
1148
+ _soup = BeautifulSoup
1149
+
1150
+
1151
+ class BeautifulStoneSoup(BeautifulSoup):
1152
+ """Deprecated interface to an XML parser."""
1153
+
1154
+ def __init__(self, *args: Any, **kwargs: Any):
1155
+ kwargs["features"] = "xml"
1156
+ warnings.warn(
1157
+ "The BeautifulStoneSoup class was deprecated in version 4.0.0. Instead of using "
1158
+ 'it, pass features="xml" into the BeautifulSoup constructor.',
1159
+ DeprecationWarning,
1160
+ stacklevel=2,
1161
+ )
1162
+ super(BeautifulStoneSoup, self).__init__(*args, **kwargs)
1163
+
1164
+
1165
+ # If this file is run as a script, act as an HTML pretty-printer.
1166
+ if __name__ == "__main__":
1167
+ import sys
1168
+
1169
+ soup = BeautifulSoup(sys.stdin)
1170
+ print((soup.prettify()))
python_embeded/Lib/site-packages/bs4/_deprecation.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper functions for deprecation.
2
+
3
+ This interface is itself unstable and may change without warning. Do
4
+ not use these functions yourself, even as a joke. The underscores are
5
+ there for a reason. No support will be given.
6
+
7
+ In particular, most of this will go away without warning once
8
+ Beautiful Soup drops support for Python 3.11, since Python 3.12
9
+ defines a `@typing.deprecated()
10
+ decorator. <https://peps.python.org/pep-0702/>`_
11
+ """
12
+
13
+ import functools
14
+ import warnings
15
+
16
+ from typing import (
17
+ Any,
18
+ Callable,
19
+ )
20
+
21
+
22
+ def _deprecated_alias(old_name: str, new_name: str, version: str):
23
+ """Alias one attribute name to another for backward compatibility
24
+
25
+ :meta private:
26
+ """
27
+
28
+ @property
29
+ def alias(self) -> Any:
30
+ ":meta private:"
31
+ warnings.warn(
32
+ f"Access to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
33
+ DeprecationWarning,
34
+ stacklevel=2,
35
+ )
36
+ return getattr(self, new_name)
37
+
38
+ @alias.setter
39
+ def alias(self, value: str) -> None:
40
+ ":meta private:"
41
+ warnings.warn(
42
+ f"Write to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
43
+ DeprecationWarning,
44
+ stacklevel=2,
45
+ )
46
+ return setattr(self, new_name, value)
47
+
48
+ return alias
49
+
50
+
51
+ def _deprecated_function_alias(
52
+ old_name: str, new_name: str, version: str
53
+ ) -> Callable[[Any], Any]:
54
+ def alias(self, *args: Any, **kwargs: Any) -> Any:
55
+ ":meta private:"
56
+ warnings.warn(
57
+ f"Call to deprecated method {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.",
58
+ DeprecationWarning,
59
+ stacklevel=2,
60
+ )
61
+ return getattr(self, new_name)(*args, **kwargs)
62
+
63
+ return alias
64
+
65
+
66
+ def _deprecated(replaced_by: str, version: str) -> Callable:
67
+ def deprecate(func: Callable) -> Callable:
68
+ @functools.wraps(func)
69
+ def with_warning(*args: Any, **kwargs: Any) -> Any:
70
+ ":meta private:"
71
+ warnings.warn(
72
+ f"Call to deprecated method {func.__name__}. (Replaced by {replaced_by}) -- Deprecated since version {version}.",
73
+ DeprecationWarning,
74
+ stacklevel=2,
75
+ )
76
+ return func(*args, **kwargs)
77
+
78
+ return with_warning
79
+
80
+ return deprecate
python_embeded/Lib/site-packages/bs4/_typing.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Custom type aliases used throughout Beautiful Soup to improve readability.
2
+
3
+ # Notes on improvements to the type system in newer versions of Python
4
+ # that can be used once Beautiful Soup drops support for older
5
+ # versions:
6
+ #
7
+ # * ClassVar can be put on class variables now.
8
+ # * In 3.10, x|y is an accepted shorthand for Union[x,y].
9
+ # * In 3.10, TypeAlias gains capabilities that can be used to
10
+ # improve the tree matching types (I don't remember what, exactly).
11
+ # * In 3.9 it's possible to specialize the re.Match type,
12
+ # e.g. re.Match[str]. In 3.8 there's a typing.re namespace for this,
13
+ # but it's removed in 3.12, so to support the widest possible set of
14
+ # versions I'm not using it.
15
+
16
+ from typing_extensions import (
17
+ runtime_checkable,
18
+ Protocol,
19
+ TypeAlias,
20
+ )
21
+ from typing import (
22
+ Any,
23
+ Callable,
24
+ Dict,
25
+ IO,
26
+ Iterable,
27
+ Mapping,
28
+ Optional,
29
+ Pattern,
30
+ TYPE_CHECKING,
31
+ Union,
32
+ )
33
+
34
+ if TYPE_CHECKING:
35
+ from bs4.element import (
36
+ AttributeValueList,
37
+ NamespacedAttribute,
38
+ NavigableString,
39
+ PageElement,
40
+ ResultSet,
41
+ Tag,
42
+ )
43
+
44
+
45
+ @runtime_checkable
46
+ class _RegularExpressionProtocol(Protocol):
47
+ """A protocol object which can accept either Python's built-in
48
+ `re.Pattern` objects, or the similar ``Regex`` objects defined by the
49
+ third-party ``regex`` package.
50
+ """
51
+
52
+ def search(
53
+ self, string: str, pos: int = ..., endpos: int = ...
54
+ ) -> Optional[Any]: ...
55
+
56
+ @property
57
+ def pattern(self) -> str: ...
58
+
59
+
60
+ # Aliases for markup in various stages of processing.
61
+ #
62
+ #: The rawest form of markup: either a string, bytestring, or an open filehandle.
63
+ _IncomingMarkup: TypeAlias = Union[str, bytes, IO[str], IO[bytes]]
64
+
65
+ #: Markup that is in memory but has (potentially) yet to be converted
66
+ #: to Unicode.
67
+ _RawMarkup: TypeAlias = Union[str, bytes]
68
+
69
+ # Aliases for character encodings
70
+ #
71
+
72
+ #: A data encoding.
73
+ _Encoding: TypeAlias = str
74
+
75
+ #: One or more data encodings.
76
+ _Encodings: TypeAlias = Iterable[_Encoding]
77
+
78
+ # Aliases for XML namespaces
79
+ #
80
+
81
+ #: The prefix for an XML namespace.
82
+ _NamespacePrefix: TypeAlias = str
83
+
84
+ #: The URL of an XML namespace
85
+ _NamespaceURL: TypeAlias = str
86
+
87
+ #: A mapping of prefixes to namespace URLs.
88
+ _NamespaceMapping: TypeAlias = Dict[_NamespacePrefix, _NamespaceURL]
89
+
90
+ #: A mapping of namespace URLs to prefixes
91
+ _InvertedNamespaceMapping: TypeAlias = Dict[_NamespaceURL, _NamespacePrefix]
92
+
93
+ # Aliases for the attribute values associated with HTML/XML tags.
94
+ #
95
+
96
+ #: The value associated with an HTML or XML attribute. This is the
97
+ #: relatively unprocessed value Beautiful Soup expects to come from a
98
+ #: `TreeBuilder`.
99
+ _RawAttributeValue: TypeAlias = str
100
+
101
+ #: A dictionary of names to `_RawAttributeValue` objects. This is how
102
+ #: Beautiful Soup expects a `TreeBuilder` to represent a tag's
103
+ #: attribute values.
104
+ _RawAttributeValues: TypeAlias = (
105
+ "Mapping[Union[str, NamespacedAttribute], _RawAttributeValue]"
106
+ )
107
+
108
+ #: An attribute value in its final form, as stored in the
109
+ # `Tag` class, after it has been processed and (in some cases)
110
+ # split into a list of strings.
111
+ _AttributeValue: TypeAlias = Union[str, "AttributeValueList"]
112
+
113
+ #: A dictionary of names to :py:data:`_AttributeValue` objects. This is what
114
+ #: a tag's attributes look like after processing.
115
+ _AttributeValues: TypeAlias = Dict[str, _AttributeValue]
116
+
117
+ #: The methods that deal with turning :py:data:`_RawAttributeValue` into
118
+ #: :py:data:`_AttributeValue` may be called several times, even after the values
119
+ #: are already processed (e.g. when cloning a tag), so they need to
120
+ #: be able to acommodate both possibilities.
121
+ _RawOrProcessedAttributeValues: TypeAlias = Union[_RawAttributeValues, _AttributeValues]
122
+
123
+ #: A number of tree manipulation methods can take either a `PageElement` or a
124
+ #: normal Python string (which will be converted to a `NavigableString`).
125
+ _InsertableElement: TypeAlias = Union["PageElement", str]
126
+
127
+ # Aliases to represent the many possibilities for matching bits of a
128
+ # parse tree.
129
+ #
130
+ # This is very complicated because we're applying a formal type system
131
+ # to some very DWIM code. The types we end up with will be the types
132
+ # of the arguments to the SoupStrainer constructor and (more
133
+ # familiarly to Beautiful Soup users) the find* methods.
134
+
135
+ #: A function that takes a PageElement and returns a yes-or-no answer.
136
+ _PageElementMatchFunction: TypeAlias = Callable[["PageElement"], bool]
137
+
138
+ #: A function that takes the raw parsed ingredients of a markup tag
139
+ #: and returns a yes-or-no answer.
140
+ # Not necessary at the moment.
141
+ # _AllowTagCreationFunction:TypeAlias = Callable[[Optional[str], str, Optional[_RawAttributeValues]], bool]
142
+
143
+ #: A function that takes the raw parsed ingredients of a markup string node
144
+ #: and returns a yes-or-no answer.
145
+ # Not necessary at the moment.
146
+ # _AllowStringCreationFunction:TypeAlias = Callable[[Optional[str]], bool]
147
+
148
+ #: A function that takes a `Tag` and returns a yes-or-no answer.
149
+ #: A `TagNameMatchRule` expects this kind of function, if you're
150
+ #: going to pass it a function.
151
+ _TagMatchFunction: TypeAlias = Callable[["Tag"], bool]
152
+
153
+ #: A function that takes a single string and returns a yes-or-no
154
+ #: answer. An `AttributeValueMatchRule` expects this kind of function, if
155
+ #: you're going to pass it a function. So does a `StringMatchRule`.
156
+ _StringMatchFunction: TypeAlias = Callable[[str], bool]
157
+
158
+ #: Either a tag name, an attribute value or a string can be matched
159
+ #: against a string, bytestring, regular expression, or a boolean.
160
+ _BaseStrainable: TypeAlias = Union[str, bytes, Pattern[str], bool]
161
+
162
+ #: A tag can be matched either with the `_BaseStrainable` options, or
163
+ #: using a function that takes the `Tag` as its sole argument.
164
+ _BaseStrainableElement: TypeAlias = Union[_BaseStrainable, _TagMatchFunction]
165
+
166
+ #: A tag's attribute vgalue can be matched either with the
167
+ #: `_BaseStrainable` options, or using a function that takes that
168
+ #: value as its sole argument.
169
+ _BaseStrainableAttribute: TypeAlias = Union[_BaseStrainable, _StringMatchFunction]
170
+
171
+ #: A tag can be matched using either a single criterion or a list of
172
+ #: criteria.
173
+ _StrainableElement: TypeAlias = Union[
174
+ _BaseStrainableElement, Iterable[_BaseStrainableElement]
175
+ ]
176
+
177
+ #: An attribute value can be matched using either a single criterion
178
+ #: or a list of criteria.
179
+ _StrainableAttribute: TypeAlias = Union[
180
+ _BaseStrainableAttribute, Iterable[_BaseStrainableAttribute]
181
+ ]
182
+
183
+ #: An string can be matched using the same techniques as
184
+ #: an attribute value.
185
+ _StrainableString: TypeAlias = _StrainableAttribute
186
+
187
+ #: A dictionary may be used to match against multiple attribute vlaues at once.
188
+ _StrainableAttributes: TypeAlias = Dict[str, _StrainableAttribute]
189
+
190
+ #: Many Beautiful soup methods return a PageElement or an ResultSet of
191
+ #: PageElements. A PageElement is either a Tag or a NavigableString.
192
+ #: These convenience aliases make it easier for IDE users to see which methods
193
+ #: are available on the objects they're dealing with.
194
+ _OneElement: TypeAlias = Union["PageElement", "Tag", "NavigableString"]
195
+ _AtMostOneElement: TypeAlias = Optional[_OneElement]
196
+ _QueryResults: TypeAlias = "ResultSet[_OneElement]"
python_embeded/Lib/site-packages/bs4/_warnings.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Define some custom warnings."""
2
+
3
+
4
+ class GuessedAtParserWarning(UserWarning):
5
+ """The warning issued when BeautifulSoup has to guess what parser to
6
+ use -- probably because no parser was specified in the constructor.
7
+ """
8
+
9
+ MESSAGE: str = """No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system ("%(parser)s"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
10
+
11
+ The code that caused this warning is on line %(line_number)s of the file %(filename)s. To get rid of this warning, pass the additional argument 'features="%(parser)s"' to the BeautifulSoup constructor.
12
+ """
13
+
14
+
15
+ class UnusualUsageWarning(UserWarning):
16
+ """A superclass for warnings issued when Beautiful Soup sees
17
+ something that is typically the result of a mistake in the calling
18
+ code, but might be intentional on the part of the user. If it is
19
+ in fact intentional, you can filter the individual warning class
20
+ to get rid of the warning. If you don't like Beautiful Soup
21
+ second-guessing what you are doing, you can filter the
22
+ UnusualUsageWarningclass itself and get rid of these entirely.
23
+ """
24
+
25
+
26
+ class MarkupResemblesLocatorWarning(UnusualUsageWarning):
27
+ """The warning issued when BeautifulSoup is given 'markup' that
28
+ actually looks like a resource locator -- a URL or a path to a file
29
+ on disk.
30
+ """
31
+
32
+ #: :meta private:
33
+ GENERIC_MESSAGE: str = """
34
+
35
+ However, if you want to parse some data that happens to look like a %(what)s, then nothing has gone wrong: you are using Beautiful Soup correctly, and this warning is spurious and can be filtered. To make this warning go away, run this code before calling the BeautifulSoup constructor:
36
+
37
+ from bs4 import MarkupResemblesLocatorWarning
38
+ import warnings
39
+
40
+ warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning)
41
+ """
42
+
43
+ URL_MESSAGE: str = (
44
+ """The input passed in on this line looks more like a URL than HTML or XML.
45
+
46
+ If you meant to use Beautiful Soup to parse the web page found at a certain URL, then something has gone wrong. You should use an Python package like 'requests' to fetch the content behind the URL. Once you have the content as a string, you can feed that string into Beautiful Soup."""
47
+ + GENERIC_MESSAGE
48
+ )
49
+
50
+ FILENAME_MESSAGE: str = (
51
+ """The input passed in on this line looks more like a filename than HTML or XML.
52
+
53
+ If you meant to use Beautiful Soup to parse the contents of a file on disk, then something has gone wrong. You should open the file first, using code like this:
54
+
55
+ filehandle = open(your filename)
56
+
57
+ You can then feed the open filehandle into Beautiful Soup instead of using the filename."""
58
+ + GENERIC_MESSAGE
59
+ )
60
+
61
+
62
+ class AttributeResemblesVariableWarning(UnusualUsageWarning, SyntaxWarning):
63
+ """The warning issued when Beautiful Soup suspects a provided
64
+ attribute name may actually be the misspelled name of a Beautiful
65
+ Soup variable. Generally speaking, this is only used in cases like
66
+ "_class" where it's very unlikely the user would be referencing an
67
+ XML attribute with that name.
68
+ """
69
+
70
+ MESSAGE: str = """%(original)r is an unusual attribute name and is a common misspelling for %(autocorrect)r.
71
+
72
+ If you meant %(autocorrect)r, change your code to use it, and this warning will go away.
73
+
74
+ If you really did mean to check the %(original)r attribute, this warning is spurious and can be filtered. To make it go away, run this code before creating your BeautifulSoup object:
75
+
76
+ from bs4 import AttributeResemblesVariableWarning
77
+ import warnings
78
+
79
+ warnings.filterwarnings("ignore", category=AttributeResemblesVariableWarning)
80
+ """
81
+
82
+
83
+ class XMLParsedAsHTMLWarning(UnusualUsageWarning):
84
+ """The warning issued when an HTML parser is used to parse
85
+ XML that is not (as far as we can tell) XHTML.
86
+ """
87
+
88
+ MESSAGE: str = """It looks like you're using an HTML parser to parse an XML document.
89
+
90
+ Assuming this really is an XML document, what you're doing might work, but you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the Python package 'lxml' installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor.
91
+
92
+ If you want or need to use an HTML parser on this document, you can make this warning go away by filtering it. To do that, run this code before calling the BeautifulSoup constructor:
93
+
94
+ from bs4 import XMLParsedAsHTMLWarning
95
+ import warnings
96
+
97
+ warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
98
+ """
python_embeded/Lib/site-packages/bs4/element.py ADDED
The diff for this file is too large to render. See raw diff
 
python_embeded/Lib/site-packages/bs4/filter.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import defaultdict
3
+ import re
4
+ from typing import (
5
+ Any,
6
+ Callable,
7
+ cast,
8
+ Dict,
9
+ Iterator,
10
+ Iterable,
11
+ List,
12
+ Optional,
13
+ Sequence,
14
+ Type,
15
+ Union,
16
+ )
17
+ import warnings
18
+
19
+ from bs4._deprecation import _deprecated
20
+ from bs4.element import (
21
+ AttributeDict,
22
+ NavigableString,
23
+ PageElement,
24
+ ResultSet,
25
+ Tag,
26
+ )
27
+ from bs4._typing import (
28
+ _AtMostOneElement,
29
+ _AttributeValue,
30
+ _OneElement,
31
+ _PageElementMatchFunction,
32
+ _QueryResults,
33
+ _RawAttributeValues,
34
+ _RegularExpressionProtocol,
35
+ _StrainableAttribute,
36
+ _StrainableElement,
37
+ _StrainableString,
38
+ _StringMatchFunction,
39
+ _TagMatchFunction,
40
+ )
41
+
42
+
43
+ class ElementFilter(object):
44
+ """`ElementFilter` encapsulates the logic necessary to decide:
45
+
46
+ 1. whether a `PageElement` (a `Tag` or a `NavigableString`) matches a
47
+ user-specified query.
48
+
49
+ 2. whether a given sequence of markup found during initial parsing
50
+ should be turned into a `PageElement` at all, or simply discarded.
51
+
52
+ The base class is the simplest `ElementFilter`. By default, it
53
+ matches everything and allows all markup to become `PageElement`
54
+ objects. You can make it more selective by passing in a
55
+ user-defined match function, or defining a subclass.
56
+
57
+ Most users of Beautiful Soup will never need to use
58
+ `ElementFilter`, or its more capable subclass
59
+ `SoupStrainer`. Instead, they will use methods like
60
+ :py:meth:`Tag.find`, which will convert their arguments into
61
+ `SoupStrainer` objects and run them against the tree.
62
+
63
+ However, if you find yourself wanting to treat the arguments to
64
+ Beautiful Soup's find_*() methods as first-class objects, those
65
+ objects will be `SoupStrainer` objects. You can create them
66
+ yourself and then make use of functions like
67
+ `ElementFilter.filter()`.
68
+ """
69
+
70
+ match_function: Optional[_PageElementMatchFunction]
71
+
72
+ def __init__(self, match_function: Optional[_PageElementMatchFunction] = None):
73
+ """Pass in a match function to easily customize the behavior of
74
+ `ElementFilter.match` without needing to subclass.
75
+
76
+ :param match_function: A function that takes a `PageElement`
77
+ and returns `True` if that `PageElement` matches some criteria.
78
+ """
79
+ self.match_function = match_function
80
+
81
+ @property
82
+ def includes_everything(self) -> bool:
83
+ """Does this `ElementFilter` obviously include everything? If so,
84
+ the filter process can be made much faster.
85
+
86
+ The `ElementFilter` might turn out to include everything even
87
+ if this returns `False`, but it won't include everything in an
88
+ obvious way.
89
+
90
+ The base `ElementFilter` implementation includes things based on
91
+ the match function, so includes_everything is only true if
92
+ there is no match function.
93
+ """
94
+ return not self.match_function
95
+
96
+ @property
97
+ def excludes_everything(self) -> bool:
98
+ """Does this `ElementFilter` obviously exclude everything? If
99
+ so, Beautiful Soup will issue a warning if you try to use it
100
+ when parsing a document.
101
+
102
+ The `ElementFilter` might turn out to exclude everything even
103
+ if this returns `False`, but it won't exclude everything in an
104
+ obvious way.
105
+
106
+ The base `ElementFilter` implementation excludes things based
107
+ on a match function we can't inspect, so excludes_everything
108
+ is always false.
109
+ """
110
+ return False
111
+
112
+ def match(self, element: PageElement, _known_rules:bool=False) -> bool:
113
+ """Does the given PageElement match the rules set down by this
114
+ ElementFilter?
115
+
116
+ The base implementation delegates to the function passed in to
117
+ the constructor.
118
+
119
+ :param _known_rules: Defined for compatibility with
120
+ SoupStrainer._match(). Used more for consistency than because
121
+ we need the performance optimization.
122
+ """
123
+ if not _known_rules and self.includes_everything:
124
+ return True
125
+ if not self.match_function:
126
+ return True
127
+ return self.match_function(element)
128
+
129
+ def filter(self, generator: Iterator[PageElement]) -> Iterator[_OneElement]:
130
+ """The most generic search method offered by Beautiful Soup.
131
+
132
+ Acts like Python's built-in `filter`, using
133
+ `ElementFilter.match` as the filtering function.
134
+ """
135
+ # If there are no rules at all, don't bother filtering. Let
136
+ # anything through.
137
+ if self.includes_everything:
138
+ for i in generator:
139
+ yield i
140
+ while True:
141
+ try:
142
+ i = next(generator)
143
+ except StopIteration:
144
+ break
145
+ if i:
146
+ if self.match(i, _known_rules=True):
147
+ yield cast("_OneElement", i)
148
+
149
+ def find(self, generator: Iterator[PageElement]) -> _AtMostOneElement:
150
+ """A lower-level equivalent of :py:meth:`Tag.find`.
151
+
152
+ You can pass in your own generator for iterating over
153
+ `PageElement` objects. The first one that matches this
154
+ `ElementFilter` will be returned.
155
+
156
+ :param generator: A way of iterating over `PageElement`
157
+ objects.
158
+ """
159
+ for match in self.filter(generator):
160
+ return match
161
+ return None
162
+
163
+ def find_all(
164
+ self, generator: Iterator[PageElement], limit: Optional[int] = None
165
+ ) -> _QueryResults:
166
+ """A lower-level equivalent of :py:meth:`Tag.find_all`.
167
+
168
+ You can pass in your own generator for iterating over
169
+ `PageElement` objects. Only elements that match this
170
+ `ElementFilter` will be returned in the :py:class:`ResultSet`.
171
+
172
+ :param generator: A way of iterating over `PageElement`
173
+ objects.
174
+
175
+ :param limit: Stop looking after finding this many results.
176
+ """
177
+ results: _QueryResults = ResultSet(self)
178
+ for match in self.filter(generator):
179
+ results.append(match)
180
+ if limit is not None and len(results) >= limit:
181
+ break
182
+ return results
183
+
184
+ def allow_tag_creation(
185
+ self, nsprefix: Optional[str], name: str, attrs: Optional[_RawAttributeValues]
186
+ ) -> bool:
187
+ """Based on the name and attributes of a tag, see whether this
188
+ `ElementFilter` will allow a `Tag` object to even be created.
189
+
190
+ By default, all tags are parsed. To change this, subclass
191
+ `ElementFilter`.
192
+
193
+ :param name: The name of the prospective tag.
194
+ :param attrs: The attributes of the prospective tag.
195
+ """
196
+ return True
197
+
198
+ def allow_string_creation(self, string: str) -> bool:
199
+ """Based on the content of a string, see whether this
200
+ `ElementFilter` will allow a `NavigableString` object based on
201
+ this string to be added to the parse tree.
202
+
203
+ By default, all strings are processed into `NavigableString`
204
+ objects. To change this, subclass `ElementFilter`.
205
+
206
+ :param str: The string under consideration.
207
+ """
208
+ return True
209
+
210
+
211
+ class MatchRule(object):
212
+ """Each MatchRule encapsulates the logic behind a single argument
213
+ passed in to one of the Beautiful Soup find* methods.
214
+ """
215
+
216
+ string: Optional[str]
217
+ pattern: Optional[_RegularExpressionProtocol]
218
+ present: Optional[bool]
219
+ exclude_everything: Optional[bool]
220
+ # TODO-TYPING: All MatchRule objects also have an attribute
221
+ # ``function``, but the type of the function depends on the
222
+ # subclass.
223
+
224
+ def __init__(
225
+ self,
226
+ string: Optional[Union[str, bytes]] = None,
227
+ pattern: Optional[_RegularExpressionProtocol] = None,
228
+ function: Optional[Callable] = None,
229
+ present: Optional[bool] = None,
230
+ exclude_everything: Optional[bool] = None
231
+ ):
232
+ if isinstance(string, bytes):
233
+ string = string.decode("utf8")
234
+ self.string = string
235
+ if isinstance(pattern, bytes):
236
+ self.pattern = re.compile(pattern.decode("utf8"))
237
+ elif isinstance(pattern, str):
238
+ self.pattern = re.compile(pattern)
239
+ else:
240
+ self.pattern = pattern
241
+ self.function = function
242
+ self.present = present
243
+ self.exclude_everything = exclude_everything
244
+
245
+ values = [
246
+ x
247
+ for x in (self.string, self.pattern, self.function, self.present, self.exclude_everything)
248
+ if x is not None
249
+ ]
250
+ if len(values) == 0:
251
+ raise ValueError(
252
+ "Either string, pattern, function, present, or exclude_everything must be provided."
253
+ )
254
+ if len(values) > 1:
255
+ raise ValueError(
256
+ "At most one of string, pattern, function, present, and exclude_everything must be provided."
257
+ )
258
+
259
+ def _base_match(self, string: Optional[str]) -> Optional[bool]:
260
+ """Run the 'cheap' portion of a match, trying to get an answer without
261
+ calling a potentially expensive custom function.
262
+
263
+ :return: True or False if we have a (positive or negative)
264
+ match; None if we need to keep trying.
265
+ """
266
+ # self.exclude_everything matches nothing.
267
+ if self.exclude_everything:
268
+ return False
269
+
270
+ # self.present==True matches everything except None.
271
+ if self.present is True:
272
+ return string is not None
273
+
274
+ # self.present==False matches _only_ None.
275
+ if self.present is False:
276
+ return string is None
277
+
278
+ # self.string does an exact string match.
279
+ if self.string is not None:
280
+ # print(f"{self.string} ?= {string}")
281
+ return self.string == string
282
+
283
+ # self.pattern does a regular expression search.
284
+ if self.pattern is not None:
285
+ # print(f"{self.pattern} ?~ {string}")
286
+ if string is None:
287
+ return False
288
+ return self.pattern.search(string) is not None
289
+
290
+ return None
291
+
292
+ def matches_string(self, string: Optional[str]) -> bool:
293
+ _base_result = self._base_match(string)
294
+ if _base_result is not None:
295
+ # No need to invoke the test function.
296
+ return _base_result
297
+ if self.function is not None and not self.function(string):
298
+ # print(f"{self.function}({string}) == False")
299
+ return False
300
+ return True
301
+
302
+ def __repr__(self) -> str:
303
+ cls = type(self).__name__
304
+ return f"<{cls} string={self.string} pattern={self.pattern} function={self.function} present={self.present}>"
305
+
306
+ def __eq__(self, other: Any) -> bool:
307
+ return (
308
+ isinstance(other, MatchRule)
309
+ and self.string == other.string
310
+ and self.pattern == other.pattern
311
+ and self.function == other.function
312
+ and self.present == other.present
313
+ )
314
+
315
+
316
+ class TagNameMatchRule(MatchRule):
317
+ """A MatchRule implementing the rules for matches against tag name."""
318
+
319
+ function: Optional[_TagMatchFunction]
320
+
321
+ def matches_tag(self, tag: Tag) -> bool:
322
+ base_value = self._base_match(tag.name)
323
+ if base_value is not None:
324
+ return base_value
325
+
326
+ # The only remaining possibility is that the match is determined
327
+ # by a function call. Call the function.
328
+ function = cast(_TagMatchFunction, self.function)
329
+ if function(tag):
330
+ return True
331
+ return False
332
+
333
+
334
+ class AttributeValueMatchRule(MatchRule):
335
+ """A MatchRule implementing the rules for matches against attribute value."""
336
+
337
+ function: Optional[_StringMatchFunction]
338
+
339
+
340
+ class StringMatchRule(MatchRule):
341
+ """A MatchRule implementing the rules for matches against a NavigableString."""
342
+
343
+ function: Optional[_StringMatchFunction]
344
+
345
+
346
+ class SoupStrainer(ElementFilter):
347
+ """The `ElementFilter` subclass used internally by Beautiful Soup.
348
+
349
+ A `SoupStrainer` encapsulates the logic necessary to perform the
350
+ kind of matches supported by methods such as
351
+ :py:meth:`Tag.find`. `SoupStrainer` objects are primarily created
352
+ internally, but you can create one yourself and pass it in as
353
+ ``parse_only`` to the `BeautifulSoup` constructor, to parse a
354
+ subset of a large document.
355
+
356
+ Internally, `SoupStrainer` objects work by converting the
357
+ constructor arguments into `MatchRule` objects. Incoming
358
+ tags/markup are matched against those rules.
359
+
360
+ :param name: One or more restrictions on the tags found in a document.
361
+
362
+ :param attrs: A dictionary that maps attribute names to
363
+ restrictions on tags that use those attributes.
364
+
365
+ :param string: One or more restrictions on the strings found in a
366
+ document.
367
+
368
+ :param kwargs: A dictionary that maps attribute names to restrictions
369
+ on tags that use those attributes. These restrictions are additive to
370
+ any specified in ``attrs``.
371
+
372
+ """
373
+
374
+ name_rules: List[TagNameMatchRule]
375
+ attribute_rules: Dict[str, List[AttributeValueMatchRule]]
376
+ string_rules: List[StringMatchRule]
377
+
378
+ def __init__(
379
+ self,
380
+ name: Optional[_StrainableElement] = None,
381
+ attrs: Dict[str, _StrainableAttribute] = {},
382
+ string: Optional[_StrainableString] = None,
383
+ **kwargs: _StrainableAttribute,
384
+ ):
385
+ if string is None and "text" in kwargs:
386
+ string = cast(Optional[_StrainableString], kwargs.pop("text"))
387
+ warnings.warn(
388
+ "As of version 4.11.0, the 'text' argument to the SoupStrainer constructor is deprecated. Use 'string' instead.",
389
+ DeprecationWarning,
390
+ stacklevel=2,
391
+ )
392
+
393
+ if name is None and not attrs and not string and not kwargs:
394
+ # Special case for backwards compatibility. Instantiating
395
+ # a SoupStrainer with no arguments whatsoever gets you one
396
+ # that matches all Tags, and only Tags.
397
+ self.name_rules = [TagNameMatchRule(present=True)]
398
+ else:
399
+ self.name_rules = cast(
400
+ List[TagNameMatchRule], list(self._make_match_rules(name, TagNameMatchRule))
401
+ )
402
+ self.attribute_rules = defaultdict(list)
403
+
404
+ if not isinstance(attrs, dict):
405
+ # Passing something other than a dictionary as attrs is
406
+ # sugar for matching that thing against the 'class'
407
+ # attribute.
408
+ attrs = {"class": attrs}
409
+
410
+ for attrdict in attrs, kwargs:
411
+ for attr, value in attrdict.items():
412
+ if attr == "class_" and attrdict is kwargs:
413
+ # If you pass in 'class_' as part of kwargs, it's
414
+ # because class is a Python reserved word. If you
415
+ # pass it in as part of the attrs dict, it's
416
+ # because you really are looking for an attribute
417
+ # called 'class_'.
418
+ attr = "class"
419
+
420
+ if value is None:
421
+ value = False
422
+ for rule_obj in self._make_match_rules(value, AttributeValueMatchRule):
423
+ self.attribute_rules[attr].append(
424
+ cast(AttributeValueMatchRule, rule_obj)
425
+ )
426
+
427
+ self.string_rules = cast(
428
+ List[StringMatchRule], list(self._make_match_rules(string, StringMatchRule))
429
+ )
430
+
431
+ #: DEPRECATED 4.13.0: You shouldn't need to check this under
432
+ #: any name (.string or .text), and if you do, you're probably
433
+ #: not taking into account all of the types of values this
434
+ #: variable might have. Look at the .string_rules list instead.
435
+ self.__string = string
436
+
437
+ @property
438
+ def includes_everything(self) -> bool:
439
+ """Check whether the provided rules will obviously include
440
+ everything. (They might include everything even if this returns `False`,
441
+ but not in an obvious way.)
442
+ """
443
+ return not self.name_rules and not self.string_rules and not self.attribute_rules
444
+
445
+ @property
446
+ def excludes_everything(self) -> bool:
447
+ """Check whether the provided rules will obviously exclude
448
+ everything. (They might exclude everything even if this returns `False`,
449
+ but not in an obvious way.)
450
+ """
451
+ if (self.string_rules and (self.name_rules or self.attribute_rules)):
452
+ # This is self-contradictory, so the rules exclude everything.
453
+ return True
454
+
455
+ # If there's a rule that ended up treated as an "exclude everything"
456
+ # rule due to creating a logical inconsistency, then the rules
457
+ # exclude everything.
458
+ if any(x.exclude_everything for x in self.string_rules):
459
+ return True
460
+ if any(x.exclude_everything for x in self.name_rules):
461
+ return True
462
+ for ruleset in self.attribute_rules.values():
463
+ if any(x.exclude_everything for x in ruleset):
464
+ return True
465
+ return False
466
+
467
+ @property
468
+ def string(self) -> Optional[_StrainableString]:
469
+ ":meta private:"
470
+ warnings.warn(
471
+ "Access to deprecated property string. (Look at .string_rules instead) -- Deprecated since version 4.13.0.",
472
+ DeprecationWarning,
473
+ stacklevel=2,
474
+ )
475
+ return self.__string
476
+
477
+ @property
478
+ def text(self) -> Optional[_StrainableString]:
479
+ ":meta private:"
480
+ warnings.warn(
481
+ "Access to deprecated property text. (Look at .string_rules instead) -- Deprecated since version 4.13.0.",
482
+ DeprecationWarning,
483
+ stacklevel=2,
484
+ )
485
+ return self.__string
486
+
487
+ def __repr__(self) -> str:
488
+ return f"<{self.__class__.__name__} name={self.name_rules} attrs={self.attribute_rules} string={self.string_rules}>"
489
+
490
+ @classmethod
491
+ def _make_match_rules(
492
+ cls,
493
+ obj: Optional[Union[_StrainableElement, _StrainableAttribute]],
494
+ rule_class: Type[MatchRule],
495
+ ) -> Iterator[MatchRule]:
496
+ """Convert a vaguely-specific 'object' into one or more well-defined
497
+ `MatchRule` objects.
498
+
499
+ :param obj: Some kind of object that corresponds to one or more
500
+ matching rules.
501
+ :param rule_class: Create instances of this `MatchRule` subclass.
502
+ """
503
+ if obj is None:
504
+ return
505
+ if isinstance(obj, (str, bytes)):
506
+ yield rule_class(string=obj)
507
+ elif isinstance(obj, bool):
508
+ yield rule_class(present=obj)
509
+ elif callable(obj):
510
+ yield rule_class(function=obj)
511
+ elif isinstance(obj, _RegularExpressionProtocol):
512
+ yield rule_class(pattern=obj)
513
+ elif hasattr(obj, "__iter__"):
514
+ if not obj:
515
+ # The attribute is being matched against the null set,
516
+ # which means it should exclude everything.
517
+ yield rule_class(exclude_everything=True)
518
+ for o in obj:
519
+ if not isinstance(o, (bytes, str)) and hasattr(o, "__iter__"):
520
+ # This is almost certainly the user's
521
+ # mistake. This list contains another list, which
522
+ # opens up the possibility of infinite
523
+ # self-reference. In the interests of avoiding
524
+ # infinite recursion, we'll treat this as an
525
+ # impossible match and issue a rule that excludes
526
+ # everything, rather than looking inside.
527
+ warnings.warn(
528
+ f"Ignoring nested list {o} to avoid the possibility of infinite recursion.",
529
+ stacklevel=5,
530
+ )
531
+ yield rule_class(exclude_everything=True)
532
+ continue
533
+ for x in cls._make_match_rules(o, rule_class):
534
+ yield x
535
+ else:
536
+ yield rule_class(string=str(obj))
537
+
538
+ def matches_tag(self, tag: Tag) -> bool:
539
+ """Do the rules of this `SoupStrainer` trigger a match against the
540
+ given `Tag`?
541
+
542
+ If the `SoupStrainer` has any `TagNameMatchRule`, at least one
543
+ must match the `Tag` or its `Tag.name`.
544
+
545
+ If there are any `AttributeValueMatchRule` for a given
546
+ attribute, at least one of them must match the attribute
547
+ value.
548
+
549
+ If there are any `StringMatchRule`, at least one must match,
550
+ but a `SoupStrainer` that *only* contains `StringMatchRule`
551
+ cannot match a `Tag`, only a `NavigableString`.
552
+ """
553
+ # If there are no rules at all, let anything through.
554
+ #if self.includes_everything:
555
+ # return True
556
+
557
+ # String rules cannot not match a Tag on their own.
558
+ if not self.name_rules and not self.attribute_rules:
559
+ return False
560
+
561
+ # Optimization for a very common case where the user is
562
+ # searching for a tag with one specific name, and we're
563
+ # looking at a tag with a different name.
564
+ if (
565
+ not tag.prefix
566
+ and len(self.name_rules) == 1
567
+ and self.name_rules[0].string is not None
568
+ and tag.name != self.name_rules[0].string
569
+ ):
570
+ return False
571
+
572
+ # If there are name rules, at least one must match. It can
573
+ # match either the Tag object itself or the prefixed name of
574
+ # the tag.
575
+ prefixed_name = None
576
+ if tag.prefix:
577
+ prefixed_name = f"{tag.prefix}:{tag.name}"
578
+ if self.name_rules:
579
+ name_matches = False
580
+ for rule in self.name_rules:
581
+ # attrs = " ".join(
582
+ # [f"{k}={v}" for k, v in sorted(tag.attrs.items())]
583
+ # )
584
+ # print(f"Testing <{tag.name} {attrs}>{tag.string}</{tag.name}> against {rule}")
585
+
586
+ # If the rule contains a function, the function will be called
587
+ # with `tag`. It will not be called a second time with
588
+ # `prefixed_name`.
589
+ if rule.matches_tag(tag) or (
590
+ not rule.function and prefixed_name is not None and rule.matches_string(prefixed_name)
591
+ ):
592
+ name_matches = True
593
+ break
594
+
595
+ if not name_matches:
596
+ return False
597
+
598
+ # If there are attribute rules for a given attribute, at least
599
+ # one of them must match. If there are rules for multiple
600
+ # attributes, each attribute must have at least one match.
601
+ for attr, rules in self.attribute_rules.items():
602
+ attr_value = tag.get(attr, None)
603
+ this_attr_match = self._attribute_match(attr_value, rules)
604
+ if not this_attr_match:
605
+ return False
606
+
607
+ # If there are string rules, at least one must match.
608
+ if self.string_rules:
609
+ _str = tag.string
610
+ if _str is None:
611
+ return False
612
+ if not self.matches_any_string_rule(_str):
613
+ return False
614
+ return True
615
+
616
+ def _attribute_match(
617
+ self,
618
+ attr_value: Optional[_AttributeValue],
619
+ rules: Iterable[AttributeValueMatchRule],
620
+ ) -> bool:
621
+ attr_values: Sequence[Optional[str]]
622
+ if isinstance(attr_value, list):
623
+ attr_values = attr_value
624
+ else:
625
+ attr_values = [cast(str, attr_value)]
626
+
627
+ def _match_attribute_value_helper(attr_values: Sequence[Optional[str]]) -> bool:
628
+ for rule in rules:
629
+ for attr_value in attr_values:
630
+ if rule.matches_string(attr_value):
631
+ return True
632
+ return False
633
+
634
+ this_attr_match = _match_attribute_value_helper(attr_values)
635
+ if not this_attr_match and len(attr_values) > 1:
636
+ # This cast converts Optional[str] to plain str.
637
+ #
638
+ # We know if there's more than one value, there can't be
639
+ # any None in the list, because Beautiful Soup never uses
640
+ # None as a value of a multi-valued attribute, and if None
641
+ # is passed in as attr_value, it's turned into a list with
642
+ # a single element (thus len(attr_values) > 1 fails).
643
+ attr_values = cast(Sequence[str], attr_values)
644
+
645
+ # Try again but treat the attribute value
646
+ # as a single string.
647
+ joined_attr_value = " ".join(attr_values)
648
+ this_attr_match = _match_attribute_value_helper([joined_attr_value])
649
+ return this_attr_match
650
+
651
+ def allow_tag_creation(
652
+ self, nsprefix: Optional[str], name: str, attrs: Optional[_RawAttributeValues]
653
+ ) -> bool:
654
+ """Based on the name and attributes of a tag, see whether this
655
+ `SoupStrainer` will allow a `Tag` object to even be created.
656
+
657
+ :param name: The name of the prospective tag.
658
+ :param attrs: The attributes of the prospective tag.
659
+ """
660
+ if self.string_rules:
661
+ # A SoupStrainer that has string rules can't be used to
662
+ # manage tag creation, because the string rule can't be
663
+ # evaluated until after the tag and all of its contents
664
+ # have been parsed.
665
+ return False
666
+ prefixed_name = None
667
+ if nsprefix:
668
+ prefixed_name = f"{nsprefix}:{name}"
669
+ if self.name_rules:
670
+ # At least one name rule must match.
671
+ name_match = False
672
+ for rule in self.name_rules:
673
+ for x in name, prefixed_name:
674
+ if x is not None:
675
+ if rule.matches_string(x):
676
+ name_match = True
677
+ break
678
+ if not name_match:
679
+ return False
680
+
681
+ # For each attribute that has rules, at least one rule must
682
+ # match.
683
+ if attrs is None:
684
+ attrs = AttributeDict()
685
+ for attr, rules in self.attribute_rules.items():
686
+ attr_value = attrs.get(attr)
687
+ if not self._attribute_match(attr_value, rules):
688
+ return False
689
+
690
+ return True
691
+
692
+ def allow_string_creation(self, string: str) -> bool:
693
+ """Based on the content of a markup string, see whether this
694
+ `SoupStrainer` will allow it to be instantiated as a
695
+ `NavigableString` object, or whether it should be ignored.
696
+ """
697
+ if self.name_rules or self.attribute_rules:
698
+ # A SoupStrainer that has name or attribute rules won't
699
+ # match any strings; it's designed to match tags with
700
+ # certain properties.
701
+ return False
702
+ if not self.string_rules:
703
+ # A SoupStrainer with no string rules will match
704
+ # all strings.
705
+ return True
706
+ if not self.matches_any_string_rule(string):
707
+ return False
708
+ return True
709
+
710
+ def matches_any_string_rule(self, string: str) -> bool:
711
+ """See whether the content of a string matches any of
712
+ this `SoupStrainer`'s string rules.
713
+ """
714
+ if not self.string_rules:
715
+ return True
716
+ for string_rule in self.string_rules:
717
+ if string_rule.matches_string(string):
718
+ return True
719
+ return False
720
+
721
+ def match(self, element: PageElement, _known_rules: bool=False) -> bool:
722
+ """Does the given `PageElement` match the rules set down by this
723
+ `SoupStrainer`?
724
+
725
+ The find_* methods rely heavily on this method to find matches.
726
+
727
+ :param element: A `PageElement`.
728
+ :param _known_rules: Set to true in the common case where
729
+ we already checked and found at least one rule in this SoupStrainer
730
+ that might exclude a PageElement. Without this, we need
731
+ to check .includes_everything every time, just to be safe.
732
+ :return: `True` if the element matches this `SoupStrainer`'s rules; `False` otherwise.
733
+ """
734
+ # If there are no rules at all, let anything through.
735
+ if not _known_rules and self.includes_everything:
736
+ return True
737
+ if isinstance(element, Tag):
738
+ return self.matches_tag(element)
739
+ assert isinstance(element, NavigableString)
740
+ if not (self.name_rules or self.attribute_rules):
741
+ # A NavigableString can only match a SoupStrainer that
742
+ # does not define any name or attribute rules.
743
+ # Then it comes down to the string rules.
744
+ return self.matches_any_string_rule(element)
745
+ return False
746
+
747
+ @_deprecated("allow_tag_creation", "4.13.0")
748
+ def search_tag(self, name: str, attrs: Optional[_RawAttributeValues]) -> bool:
749
+ """A less elegant version of `allow_tag_creation`. Deprecated as of 4.13.0"""
750
+ ":meta private:"
751
+ return self.allow_tag_creation(None, name, attrs)
752
+
753
+ @_deprecated("match", "4.13.0")
754
+ def search(self, element: PageElement) -> Optional[PageElement]:
755
+ """A less elegant version of match(). Deprecated as of 4.13.0.
756
+
757
+ :meta private:
758
+ """
759
+ return element if self.match(element) else None
python_embeded/Lib/site-packages/bs4/formatter.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Callable, Dict, Iterable, Optional, Set, Tuple, TYPE_CHECKING, Union
3
+ from typing_extensions import TypeAlias
4
+ from bs4.dammit import EntitySubstitution
5
+
6
+ if TYPE_CHECKING:
7
+ from bs4._typing import _AttributeValue
8
+
9
+
10
+ class Formatter(EntitySubstitution):
11
+ """Describes a strategy to use when outputting a parse tree to a string.
12
+
13
+ Some parts of this strategy come from the distinction between
14
+ HTML4, HTML5, and XML. Others are configurable by the user.
15
+
16
+ Formatters are passed in as the `formatter` argument to methods
17
+ like `bs4.element.Tag.encode`. Most people won't need to
18
+ think about formatters, and most people who need to think about
19
+ them can pass in one of these predefined strings as `formatter`
20
+ rather than making a new Formatter object:
21
+
22
+ For HTML documents:
23
+ * 'html' - HTML entity substitution for generic HTML documents. (default)
24
+ * 'html5' - HTML entity substitution for HTML5 documents, as
25
+ well as some optimizations in the way tags are rendered.
26
+ * 'html5-4.12.0' - The version of the 'html5' formatter used prior to
27
+ Beautiful Soup 4.13.0.
28
+ * 'minimal' - Only make the substitutions necessary to guarantee
29
+ valid HTML.
30
+ * None - Do not perform any substitution. This will be faster
31
+ but may result in invalid markup.
32
+
33
+ For XML documents:
34
+ * 'html' - Entity substitution for XHTML documents.
35
+ * 'minimal' - Only make the substitutions necessary to guarantee
36
+ valid XML. (default)
37
+ * None - Do not perform any substitution. This will be faster
38
+ but may result in invalid markup.
39
+
40
+ """
41
+
42
+ #: Constant name denoting HTML markup
43
+ HTML: str = "html"
44
+
45
+ #: Constant name denoting XML markup
46
+ XML: str = "xml"
47
+
48
+ #: Default values for the various constructor options when the
49
+ #: markup language is HTML.
50
+ HTML_DEFAULTS: Dict[str, Set[str]] = dict(
51
+ cdata_containing_tags=set(["script", "style"]),
52
+ )
53
+
54
+ language: Optional[str] #: :meta private:
55
+ entity_substitution: Optional[_EntitySubstitutionFunction] #: :meta private:
56
+ void_element_close_prefix: str #: :meta private:
57
+ cdata_containing_tags: Set[str] #: :meta private:
58
+ indent: str #: :meta private:
59
+
60
+ #: If this is set to true by the constructor, then attributes whose
61
+ #: values are sent to the empty string will be treated as HTML
62
+ #: boolean attributes. (Attributes whose value is None are always
63
+ #: rendered this way.)
64
+ empty_attributes_are_booleans: bool
65
+
66
+ def _default(
67
+ self, language: str, value: Optional[Set[str]], kwarg: str
68
+ ) -> Set[str]:
69
+ if value is not None:
70
+ return value
71
+ if language == self.XML:
72
+ # When XML is the markup language in use, all of the
73
+ # defaults are the empty list.
74
+ return set()
75
+
76
+ # Otherwise, it depends on what's in HTML_DEFAULTS.
77
+ return self.HTML_DEFAULTS[kwarg]
78
+
79
+ def __init__(
80
+ self,
81
+ language: Optional[str] = None,
82
+ entity_substitution: Optional[_EntitySubstitutionFunction] = None,
83
+ void_element_close_prefix: str = "/",
84
+ cdata_containing_tags: Optional[Set[str]] = None,
85
+ empty_attributes_are_booleans: bool = False,
86
+ indent: Union[int,str] = 1,
87
+ ):
88
+ r"""Constructor.
89
+
90
+ :param language: This should be `Formatter.XML` if you are formatting
91
+ XML markup and `Formatter.HTML` if you are formatting HTML markup.
92
+
93
+ :param entity_substitution: A function to call to replace special
94
+ characters with XML/HTML entities. For examples, see
95
+ bs4.dammit.EntitySubstitution.substitute_html and substitute_xml.
96
+ :param void_element_close_prefix: By default, void elements
97
+ are represented as <tag/> (XML rules) rather than <tag>
98
+ (HTML rules). To get <tag>, pass in the empty string.
99
+ :param cdata_containing_tags: The set of tags that are defined
100
+ as containing CDATA in this dialect. For example, in HTML,
101
+ <script> and <style> tags are defined as containing CDATA,
102
+ and their contents should not be formatted.
103
+ :param empty_attributes_are_booleans: If this is set to true,
104
+ then attributes whose values are sent to the empty string
105
+ will be treated as `HTML boolean
106
+ attributes<https://dev.w3.org/html5/spec-LC/common-microsyntaxes.html#boolean-attributes>`_. (Attributes
107
+ whose value is None are always rendered this way.)
108
+ :param indent: If indent is a non-negative integer or string,
109
+ then the contents of elements will be indented
110
+ appropriately when pretty-printing. An indent level of 0,
111
+ negative, or "" will only insert newlines. Using a
112
+ positive integer indent indents that many spaces per
113
+ level. If indent is a string (such as "\t"), that string
114
+ is used to indent each level. The default behavior is to
115
+ indent one space per level.
116
+
117
+ """
118
+ self.language = language or self.HTML
119
+ self.entity_substitution = entity_substitution
120
+ self.void_element_close_prefix = void_element_close_prefix
121
+ self.cdata_containing_tags = self._default(
122
+ self.language, cdata_containing_tags, "cdata_containing_tags"
123
+ )
124
+ self.empty_attributes_are_booleans = empty_attributes_are_booleans
125
+ if indent is None:
126
+ indent = 0
127
+ indent_str: str
128
+ if isinstance(indent, int):
129
+ if indent < 0:
130
+ indent = 0
131
+ indent_str = " " * indent
132
+ elif isinstance(indent, str):
133
+ indent_str = indent
134
+ else:
135
+ indent_str = " "
136
+ self.indent = indent_str
137
+
138
+ def substitute(self, ns: str) -> str:
139
+ """Process a string that needs to undergo entity substitution.
140
+ This may be a string encountered in an attribute value or as
141
+ text.
142
+
143
+ :param ns: A string.
144
+ :return: The same string but with certain characters replaced by named
145
+ or numeric entities.
146
+ """
147
+ if not self.entity_substitution:
148
+ return ns
149
+ from .element import NavigableString
150
+
151
+ if (
152
+ isinstance(ns, NavigableString)
153
+ and ns.parent is not None
154
+ and ns.parent.name in self.cdata_containing_tags
155
+ ):
156
+ # Do nothing.
157
+ return ns
158
+ # Substitute.
159
+ return self.entity_substitution(ns)
160
+
161
+ def attribute_value(self, value: str) -> str:
162
+ """Process the value of an attribute.
163
+
164
+ :param ns: A string.
165
+ :return: A string with certain characters replaced by named
166
+ or numeric entities.
167
+ """
168
+ return self.substitute(value)
169
+
170
+ def attributes(
171
+ self, tag: bs4.element.Tag
172
+ ) -> Iterable[Tuple[str, Optional[_AttributeValue]]]:
173
+ """Reorder a tag's attributes however you want.
174
+
175
+ By default, attributes are sorted alphabetically. This makes
176
+ behavior consistent between Python 2 and Python 3, and preserves
177
+ backwards compatibility with older versions of Beautiful Soup.
178
+
179
+ If `empty_attributes_are_booleans` is True, then
180
+ attributes whose values are set to the empty string will be
181
+ treated as boolean attributes.
182
+ """
183
+ if tag.attrs is None:
184
+ return []
185
+
186
+ items: Iterable[Tuple[str, _AttributeValue]] = list(tag.attrs.items())
187
+ return sorted(
188
+ (k, (None if self.empty_attributes_are_booleans and v == "" else v))
189
+ for k, v in items
190
+ )
191
+
192
+
193
+ class HTMLFormatter(Formatter):
194
+ """A generic Formatter for HTML."""
195
+
196
+ REGISTRY: Dict[Optional[str], HTMLFormatter] = {}
197
+
198
+ def __init__(
199
+ self,
200
+ entity_substitution: Optional[_EntitySubstitutionFunction] = None,
201
+ void_element_close_prefix: str = "/",
202
+ cdata_containing_tags: Optional[Set[str]] = None,
203
+ empty_attributes_are_booleans: bool = False,
204
+ indent: Union[int,str] = 1,
205
+ ):
206
+ super(HTMLFormatter, self).__init__(
207
+ self.HTML,
208
+ entity_substitution,
209
+ void_element_close_prefix,
210
+ cdata_containing_tags,
211
+ empty_attributes_are_booleans,
212
+ indent=indent
213
+ )
214
+
215
+
216
+ class XMLFormatter(Formatter):
217
+ """A generic Formatter for XML."""
218
+
219
+ REGISTRY: Dict[Optional[str], XMLFormatter] = {}
220
+
221
+ def __init__(
222
+ self,
223
+ entity_substitution: Optional[_EntitySubstitutionFunction] = None,
224
+ void_element_close_prefix: str = "/",
225
+ cdata_containing_tags: Optional[Set[str]] = None,
226
+ empty_attributes_are_booleans: bool = False,
227
+ indent: Union[int,str] = 1,
228
+ ):
229
+ super(XMLFormatter, self).__init__(
230
+ self.XML,
231
+ entity_substitution,
232
+ void_element_close_prefix,
233
+ cdata_containing_tags,
234
+ empty_attributes_are_booleans,
235
+ indent=indent,
236
+ )
237
+
238
+
239
+ # Set up aliases for the default formatters.
240
+ HTMLFormatter.REGISTRY["html"] = HTMLFormatter(
241
+ entity_substitution=EntitySubstitution.substitute_html
242
+ )
243
+
244
+ HTMLFormatter.REGISTRY["html5"] = HTMLFormatter(
245
+ entity_substitution=EntitySubstitution.substitute_html5,
246
+ void_element_close_prefix="",
247
+ empty_attributes_are_booleans=True,
248
+ )
249
+ HTMLFormatter.REGISTRY["html5-4.12"] = HTMLFormatter(
250
+ entity_substitution=EntitySubstitution.substitute_html,
251
+ void_element_close_prefix="",
252
+ empty_attributes_are_booleans=True,
253
+ )
254
+ HTMLFormatter.REGISTRY["minimal"] = HTMLFormatter(
255
+ entity_substitution=EntitySubstitution.substitute_xml
256
+ )
257
+ HTMLFormatter.REGISTRY[None] = HTMLFormatter(entity_substitution=None)
258
+ XMLFormatter.REGISTRY["html"] = XMLFormatter(
259
+ entity_substitution=EntitySubstitution.substitute_html
260
+ )
261
+ XMLFormatter.REGISTRY["minimal"] = XMLFormatter(
262
+ entity_substitution=EntitySubstitution.substitute_xml
263
+ )
264
+
265
+ XMLFormatter.REGISTRY[None] = XMLFormatter(entity_substitution=None)
266
+
267
+ # Define type aliases to improve readability.
268
+ #
269
+
270
+ #: A function to call to replace special characters with XML or HTML
271
+ #: entities.
272
+ _EntitySubstitutionFunction: TypeAlias = Callable[[str], str]
273
+
274
+ # Many of the output-centered methods take an argument that can either
275
+ # be a Formatter object or the name of a Formatter to be looked up.
276
+ _FormatterOrName = Union[Formatter, str]
python_embeded/Lib/site-packages/bs4/py.typed ADDED
File without changes
python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014-2025 Thomas Kemmer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/METADATA ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.2
2
+ Name: cachetools
3
+ Version: 5.5.2
4
+ Summary: Extensible memoizing collections and decorators
5
+ Home-page: https://github.com/tkem/cachetools/
6
+ Author: Thomas Kemmer
7
+ Author-email: tkemmer@computer.org
8
+ License: MIT
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Environment :: Other Environment
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.7
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Requires-Python: >=3.7
25
+ License-File: LICENSE
26
+
27
+ cachetools
28
+ ========================================================================
29
+
30
+ .. image:: https://img.shields.io/pypi/v/cachetools
31
+ :target: https://pypi.org/project/cachetools/
32
+ :alt: Latest PyPI version
33
+
34
+ .. image:: https://img.shields.io/github/actions/workflow/status/tkem/cachetools/ci.yml
35
+ :target: https://github.com/tkem/cachetools/actions/workflows/ci.yml
36
+ :alt: CI build status
37
+
38
+ .. image:: https://img.shields.io/readthedocs/cachetools
39
+ :target: https://cachetools.readthedocs.io/
40
+ :alt: Documentation build status
41
+
42
+ .. image:: https://img.shields.io/codecov/c/github/tkem/cachetools/master.svg
43
+ :target: https://codecov.io/gh/tkem/cachetools
44
+ :alt: Test coverage
45
+
46
+ .. image:: https://img.shields.io/librariesio/sourcerank/pypi/cachetools
47
+ :target: https://libraries.io/pypi/cachetools
48
+ :alt: Libraries.io SourceRank
49
+
50
+ .. image:: https://img.shields.io/github/license/tkem/cachetools
51
+ :target: https://raw.github.com/tkem/cachetools/master/LICENSE
52
+ :alt: License
53
+
54
+ .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
55
+ :target: https://github.com/psf/black
56
+ :alt: Code style: black
57
+
58
+
59
+ This module provides various memoizing collections and decorators,
60
+ including variants of the Python Standard Library's `@lru_cache`_
61
+ function decorator.
62
+
63
+ .. code-block:: python
64
+
65
+ from cachetools import cached, LRUCache, TTLCache
66
+
67
+ # speed up calculating Fibonacci numbers with dynamic programming
68
+ @cached(cache={})
69
+ def fib(n):
70
+ return n if n < 2 else fib(n - 1) + fib(n - 2)
71
+
72
+ # cache least recently used Python Enhancement Proposals
73
+ @cached(cache=LRUCache(maxsize=32))
74
+ def get_pep(num):
75
+ url = 'http://www.python.org/dev/peps/pep-%04d/' % num
76
+ with urllib.request.urlopen(url) as s:
77
+ return s.read()
78
+
79
+ # cache weather data for no longer than ten minutes
80
+ @cached(cache=TTLCache(maxsize=1024, ttl=600))
81
+ def get_weather(place):
82
+ return owm.weather_at_place(place).get_weather()
83
+
84
+ For the purpose of this module, a *cache* is a mutable_ mapping_ of a
85
+ fixed maximum size. When the cache is full, i.e. by adding another
86
+ item the cache would exceed its maximum size, the cache must choose
87
+ which item(s) to discard based on a suitable `cache algorithm`_.
88
+
89
+ This module provides multiple cache classes based on different cache
90
+ algorithms, as well as decorators for easily memoizing function and
91
+ method calls.
92
+
93
+
94
+ Installation
95
+ ------------------------------------------------------------------------
96
+
97
+ cachetools is available from PyPI_ and can be installed by running::
98
+
99
+ pip install cachetools
100
+
101
+ Typing stubs for this package are provided by typeshed_ and can be
102
+ installed by running::
103
+
104
+ pip install types-cachetools
105
+
106
+
107
+ Project Resources
108
+ ------------------------------------------------------------------------
109
+
110
+ - `Documentation`_
111
+ - `Issue tracker`_
112
+ - `Source code`_
113
+ - `Change log`_
114
+
115
+
116
+ Related Projects
117
+ ------------------------------------------------------------------------
118
+
119
+ - asyncache_: Helpers to use cachetools with async functions
120
+ - cacheing_: Pure Python Cacheing Library
121
+ - CacheToolsUtils_: Cachetools Utilities
122
+ - kids.cache_: Kids caching library
123
+ - shelved-cache_: Persistent cache for Python cachetools
124
+
125
+
126
+ License
127
+ ------------------------------------------------------------------------
128
+
129
+ Copyright (c) 2014-2025 Thomas Kemmer.
130
+
131
+ Licensed under the `MIT License`_.
132
+
133
+
134
+ .. _@lru_cache: https://docs.python.org/3/library/functools.html#functools.lru_cache
135
+ .. _mutable: https://docs.python.org/dev/glossary.html#term-mutable
136
+ .. _mapping: https://docs.python.org/dev/glossary.html#term-mapping
137
+ .. _cache algorithm: https://en.wikipedia.org/wiki/Cache_algorithms
138
+
139
+ .. _PyPI: https://pypi.org/project/cachetools/
140
+ .. _typeshed: https://github.com/python/typeshed/
141
+ .. _Documentation: https://cachetools.readthedocs.io/
142
+ .. _Issue tracker: https://github.com/tkem/cachetools/issues/
143
+ .. _Source code: https://github.com/tkem/cachetools/
144
+ .. _Change log: https://github.com/tkem/cachetools/blob/master/CHANGELOG.rst
145
+ .. _MIT License: https://raw.github.com/tkem/cachetools/master/LICENSE
146
+
147
+ .. _asyncache: https://pypi.org/project/asyncache/
148
+ .. _cacheing: https://github.com/breid48/cacheing
149
+ .. _CacheToolsUtils: https://pypi.org/project/CacheToolsUtils/
150
+ .. _kids.cache: https://pypi.org/project/kids.cache/
151
+ .. _shelved-cache: https://pypi.org/project/shelved-cache/
python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cachetools-5.5.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ cachetools-5.5.2.dist-info/LICENSE,sha256=I8Tv96HAJ6l3oLecRJfhdYLDNMXxfvasjKC1LR59hBc,1085
3
+ cachetools-5.5.2.dist-info/METADATA,sha256=YY8fmEiV8he5oa9hC4S6sjLQKrDuoQhx2mQTI7Iqf5Y,5379
4
+ cachetools-5.5.2.dist-info/RECORD,,
5
+ cachetools-5.5.2.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
6
+ cachetools-5.5.2.dist-info/top_level.txt,sha256=ai2FH78TGwoBcCgVfoqbzk5IQCtnDukdSs4zKuVPvDs,11
7
+ cachetools/__init__.py,sha256=cutUU6fB1bIMih0ro_TVCPKJTPwM-qP4fS_PyNfQlWs,21803
8
+ cachetools/__pycache__/__init__.cpython-312.pyc,,
9
+ cachetools/__pycache__/_decorators.cpython-312.pyc,,
10
+ cachetools/__pycache__/func.cpython-312.pyc,,
11
+ cachetools/__pycache__/keys.cpython-312.pyc,,
12
+ cachetools/_decorators.py,sha256=4_u0GL89t2BOLGwnK8CueiFtyHKK2zydoHj9aqnsMM4,3832
13
+ cachetools/func.py,sha256=aOVfSkuNWMRADpkHZGK7LeJ_VZ8wljzbRwIAliOuhAg,3719
14
+ cachetools/keys.py,sha256=AOgfoi-oioBOnEEk115_9qs0HKISrYnbcV4F0hyZ1yk,1777
python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python_embeded/Lib/site-packages/cachetools-5.5.2.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ cachetools
python_embeded/Lib/site-packages/cachetools/__init__.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extensible memoizing collections and decorators."""
2
+
3
+ __all__ = (
4
+ "Cache",
5
+ "FIFOCache",
6
+ "LFUCache",
7
+ "LRUCache",
8
+ "MRUCache",
9
+ "RRCache",
10
+ "TLRUCache",
11
+ "TTLCache",
12
+ "cached",
13
+ "cachedmethod",
14
+ )
15
+
16
+ __version__ = "5.5.2"
17
+
18
+ import collections
19
+ import collections.abc
20
+ import functools
21
+ import heapq
22
+ import random
23
+ import time
24
+
25
+ from . import keys
26
+ from ._decorators import _cached_wrapper
27
+
28
+
29
+ class _DefaultSize:
30
+ __slots__ = ()
31
+
32
+ def __getitem__(self, _):
33
+ return 1
34
+
35
+ def __setitem__(self, _, value):
36
+ assert value == 1
37
+
38
+ def pop(self, _):
39
+ return 1
40
+
41
+
42
+ class Cache(collections.abc.MutableMapping):
43
+ """Mutable mapping to serve as a simple cache or cache base class."""
44
+
45
+ __marker = object()
46
+
47
+ __size = _DefaultSize()
48
+
49
+ def __init__(self, maxsize, getsizeof=None):
50
+ if getsizeof:
51
+ self.getsizeof = getsizeof
52
+ if self.getsizeof is not Cache.getsizeof:
53
+ self.__size = dict()
54
+ self.__data = dict()
55
+ self.__currsize = 0
56
+ self.__maxsize = maxsize
57
+
58
+ def __repr__(self):
59
+ return "%s(%s, maxsize=%r, currsize=%r)" % (
60
+ self.__class__.__name__,
61
+ repr(self.__data),
62
+ self.__maxsize,
63
+ self.__currsize,
64
+ )
65
+
66
+ def __getitem__(self, key):
67
+ try:
68
+ return self.__data[key]
69
+ except KeyError:
70
+ return self.__missing__(key)
71
+
72
+ def __setitem__(self, key, value):
73
+ maxsize = self.__maxsize
74
+ size = self.getsizeof(value)
75
+ if size > maxsize:
76
+ raise ValueError("value too large")
77
+ if key not in self.__data or self.__size[key] < size:
78
+ while self.__currsize + size > maxsize:
79
+ self.popitem()
80
+ if key in self.__data:
81
+ diffsize = size - self.__size[key]
82
+ else:
83
+ diffsize = size
84
+ self.__data[key] = value
85
+ self.__size[key] = size
86
+ self.__currsize += diffsize
87
+
88
+ def __delitem__(self, key):
89
+ size = self.__size.pop(key)
90
+ del self.__data[key]
91
+ self.__currsize -= size
92
+
93
+ def __contains__(self, key):
94
+ return key in self.__data
95
+
96
+ def __missing__(self, key):
97
+ raise KeyError(key)
98
+
99
+ def __iter__(self):
100
+ return iter(self.__data)
101
+
102
+ def __len__(self):
103
+ return len(self.__data)
104
+
105
+ def get(self, key, default=None):
106
+ if key in self:
107
+ return self[key]
108
+ else:
109
+ return default
110
+
111
+ def pop(self, key, default=__marker):
112
+ if key in self:
113
+ value = self[key]
114
+ del self[key]
115
+ elif default is self.__marker:
116
+ raise KeyError(key)
117
+ else:
118
+ value = default
119
+ return value
120
+
121
+ def setdefault(self, key, default=None):
122
+ if key in self:
123
+ value = self[key]
124
+ else:
125
+ self[key] = value = default
126
+ return value
127
+
128
+ @property
129
+ def maxsize(self):
130
+ """The maximum size of the cache."""
131
+ return self.__maxsize
132
+
133
+ @property
134
+ def currsize(self):
135
+ """The current size of the cache."""
136
+ return self.__currsize
137
+
138
+ @staticmethod
139
+ def getsizeof(value):
140
+ """Return the size of a cache element's value."""
141
+ return 1
142
+
143
+
144
+ class FIFOCache(Cache):
145
+ """First In First Out (FIFO) cache implementation."""
146
+
147
+ def __init__(self, maxsize, getsizeof=None):
148
+ Cache.__init__(self, maxsize, getsizeof)
149
+ self.__order = collections.OrderedDict()
150
+
151
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
152
+ cache_setitem(self, key, value)
153
+ try:
154
+ self.__order.move_to_end(key)
155
+ except KeyError:
156
+ self.__order[key] = None
157
+
158
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
159
+ cache_delitem(self, key)
160
+ del self.__order[key]
161
+
162
+ def popitem(self):
163
+ """Remove and return the `(key, value)` pair first inserted."""
164
+ try:
165
+ key = next(iter(self.__order))
166
+ except StopIteration:
167
+ raise KeyError("%s is empty" % type(self).__name__) from None
168
+ else:
169
+ return (key, self.pop(key))
170
+
171
+
172
+ class LFUCache(Cache):
173
+ """Least Frequently Used (LFU) cache implementation."""
174
+
175
+ def __init__(self, maxsize, getsizeof=None):
176
+ Cache.__init__(self, maxsize, getsizeof)
177
+ self.__counter = collections.Counter()
178
+
179
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
180
+ value = cache_getitem(self, key)
181
+ if key in self: # __missing__ may not store item
182
+ self.__counter[key] -= 1
183
+ return value
184
+
185
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
186
+ cache_setitem(self, key, value)
187
+ self.__counter[key] -= 1
188
+
189
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
190
+ cache_delitem(self, key)
191
+ del self.__counter[key]
192
+
193
+ def popitem(self):
194
+ """Remove and return the `(key, value)` pair least frequently used."""
195
+ try:
196
+ ((key, _),) = self.__counter.most_common(1)
197
+ except ValueError:
198
+ raise KeyError("%s is empty" % type(self).__name__) from None
199
+ else:
200
+ return (key, self.pop(key))
201
+
202
+
203
+ class LRUCache(Cache):
204
+ """Least Recently Used (LRU) cache implementation."""
205
+
206
+ def __init__(self, maxsize, getsizeof=None):
207
+ Cache.__init__(self, maxsize, getsizeof)
208
+ self.__order = collections.OrderedDict()
209
+
210
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
211
+ value = cache_getitem(self, key)
212
+ if key in self: # __missing__ may not store item
213
+ self.__update(key)
214
+ return value
215
+
216
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
217
+ cache_setitem(self, key, value)
218
+ self.__update(key)
219
+
220
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
221
+ cache_delitem(self, key)
222
+ del self.__order[key]
223
+
224
+ def popitem(self):
225
+ """Remove and return the `(key, value)` pair least recently used."""
226
+ try:
227
+ key = next(iter(self.__order))
228
+ except StopIteration:
229
+ raise KeyError("%s is empty" % type(self).__name__) from None
230
+ else:
231
+ return (key, self.pop(key))
232
+
233
+ def __update(self, key):
234
+ try:
235
+ self.__order.move_to_end(key)
236
+ except KeyError:
237
+ self.__order[key] = None
238
+
239
+
240
+ class MRUCache(Cache):
241
+ """Most Recently Used (MRU) cache implementation."""
242
+
243
+ def __init__(self, maxsize, getsizeof=None):
244
+ from warnings import warn
245
+
246
+ warn("MRUCache is deprecated", DeprecationWarning, stacklevel=2)
247
+
248
+ Cache.__init__(self, maxsize, getsizeof)
249
+ self.__order = collections.OrderedDict()
250
+
251
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
252
+ value = cache_getitem(self, key)
253
+ if key in self: # __missing__ may not store item
254
+ self.__update(key)
255
+ return value
256
+
257
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
258
+ cache_setitem(self, key, value)
259
+ self.__update(key)
260
+
261
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
262
+ cache_delitem(self, key)
263
+ del self.__order[key]
264
+
265
+ def popitem(self):
266
+ """Remove and return the `(key, value)` pair most recently used."""
267
+ try:
268
+ key = next(iter(self.__order))
269
+ except StopIteration:
270
+ raise KeyError("%s is empty" % type(self).__name__) from None
271
+ else:
272
+ return (key, self.pop(key))
273
+
274
+ def __update(self, key):
275
+ try:
276
+ self.__order.move_to_end(key, last=False)
277
+ except KeyError:
278
+ self.__order[key] = None
279
+
280
+
281
+ class RRCache(Cache):
282
+ """Random Replacement (RR) cache implementation."""
283
+
284
+ def __init__(self, maxsize, choice=random.choice, getsizeof=None):
285
+ Cache.__init__(self, maxsize, getsizeof)
286
+ self.__choice = choice
287
+
288
+ @property
289
+ def choice(self):
290
+ """The `choice` function used by the cache."""
291
+ return self.__choice
292
+
293
+ def popitem(self):
294
+ """Remove and return a random `(key, value)` pair."""
295
+ try:
296
+ key = self.__choice(list(self))
297
+ except IndexError:
298
+ raise KeyError("%s is empty" % type(self).__name__) from None
299
+ else:
300
+ return (key, self.pop(key))
301
+
302
+
303
+ class _TimedCache(Cache):
304
+ """Base class for time aware cache implementations."""
305
+
306
+ class _Timer:
307
+ def __init__(self, timer):
308
+ self.__timer = timer
309
+ self.__nesting = 0
310
+
311
+ def __call__(self):
312
+ if self.__nesting == 0:
313
+ return self.__timer()
314
+ else:
315
+ return self.__time
316
+
317
+ def __enter__(self):
318
+ if self.__nesting == 0:
319
+ self.__time = time = self.__timer()
320
+ else:
321
+ time = self.__time
322
+ self.__nesting += 1
323
+ return time
324
+
325
+ def __exit__(self, *exc):
326
+ self.__nesting -= 1
327
+
328
+ def __reduce__(self):
329
+ return _TimedCache._Timer, (self.__timer,)
330
+
331
+ def __getattr__(self, name):
332
+ return getattr(self.__timer, name)
333
+
334
+ def __init__(self, maxsize, timer=time.monotonic, getsizeof=None):
335
+ Cache.__init__(self, maxsize, getsizeof)
336
+ self.__timer = _TimedCache._Timer(timer)
337
+
338
+ def __repr__(self, cache_repr=Cache.__repr__):
339
+ with self.__timer as time:
340
+ self.expire(time)
341
+ return cache_repr(self)
342
+
343
+ def __len__(self, cache_len=Cache.__len__):
344
+ with self.__timer as time:
345
+ self.expire(time)
346
+ return cache_len(self)
347
+
348
+ @property
349
+ def currsize(self):
350
+ with self.__timer as time:
351
+ self.expire(time)
352
+ return super().currsize
353
+
354
+ @property
355
+ def timer(self):
356
+ """The timer function used by the cache."""
357
+ return self.__timer
358
+
359
+ def clear(self):
360
+ with self.__timer as time:
361
+ self.expire(time)
362
+ Cache.clear(self)
363
+
364
+ def get(self, *args, **kwargs):
365
+ with self.__timer:
366
+ return Cache.get(self, *args, **kwargs)
367
+
368
+ def pop(self, *args, **kwargs):
369
+ with self.__timer:
370
+ return Cache.pop(self, *args, **kwargs)
371
+
372
+ def setdefault(self, *args, **kwargs):
373
+ with self.__timer:
374
+ return Cache.setdefault(self, *args, **kwargs)
375
+
376
+
377
+ class TTLCache(_TimedCache):
378
+ """LRU Cache implementation with per-item time-to-live (TTL) value."""
379
+
380
+ class _Link:
381
+ __slots__ = ("key", "expires", "next", "prev")
382
+
383
+ def __init__(self, key=None, expires=None):
384
+ self.key = key
385
+ self.expires = expires
386
+
387
+ def __reduce__(self):
388
+ return TTLCache._Link, (self.key, self.expires)
389
+
390
+ def unlink(self):
391
+ next = self.next
392
+ prev = self.prev
393
+ prev.next = next
394
+ next.prev = prev
395
+
396
+ def __init__(self, maxsize, ttl, timer=time.monotonic, getsizeof=None):
397
+ _TimedCache.__init__(self, maxsize, timer, getsizeof)
398
+ self.__root = root = TTLCache._Link()
399
+ root.prev = root.next = root
400
+ self.__links = collections.OrderedDict()
401
+ self.__ttl = ttl
402
+
403
+ def __contains__(self, key):
404
+ try:
405
+ link = self.__links[key] # no reordering
406
+ except KeyError:
407
+ return False
408
+ else:
409
+ return self.timer() < link.expires
410
+
411
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
412
+ try:
413
+ link = self.__getlink(key)
414
+ except KeyError:
415
+ expired = False
416
+ else:
417
+ expired = not (self.timer() < link.expires)
418
+ if expired:
419
+ return self.__missing__(key)
420
+ else:
421
+ return cache_getitem(self, key)
422
+
423
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
424
+ with self.timer as time:
425
+ self.expire(time)
426
+ cache_setitem(self, key, value)
427
+ try:
428
+ link = self.__getlink(key)
429
+ except KeyError:
430
+ self.__links[key] = link = TTLCache._Link(key)
431
+ else:
432
+ link.unlink()
433
+ link.expires = time + self.__ttl
434
+ link.next = root = self.__root
435
+ link.prev = prev = root.prev
436
+ prev.next = root.prev = link
437
+
438
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
439
+ cache_delitem(self, key)
440
+ link = self.__links.pop(key)
441
+ link.unlink()
442
+ if not (self.timer() < link.expires):
443
+ raise KeyError(key)
444
+
445
+ def __iter__(self):
446
+ root = self.__root
447
+ curr = root.next
448
+ while curr is not root:
449
+ # "freeze" time for iterator access
450
+ with self.timer as time:
451
+ if time < curr.expires:
452
+ yield curr.key
453
+ curr = curr.next
454
+
455
+ def __setstate__(self, state):
456
+ self.__dict__.update(state)
457
+ root = self.__root
458
+ root.prev = root.next = root
459
+ for link in sorted(self.__links.values(), key=lambda obj: obj.expires):
460
+ link.next = root
461
+ link.prev = prev = root.prev
462
+ prev.next = root.prev = link
463
+ self.expire(self.timer())
464
+
465
+ @property
466
+ def ttl(self):
467
+ """The time-to-live value of the cache's items."""
468
+ return self.__ttl
469
+
470
+ def expire(self, time=None):
471
+ """Remove expired items from the cache and return an iterable of the
472
+ expired `(key, value)` pairs.
473
+
474
+ """
475
+ if time is None:
476
+ time = self.timer()
477
+ root = self.__root
478
+ curr = root.next
479
+ links = self.__links
480
+ expired = []
481
+ cache_delitem = Cache.__delitem__
482
+ cache_getitem = Cache.__getitem__
483
+ while curr is not root and not (time < curr.expires):
484
+ expired.append((curr.key, cache_getitem(self, curr.key)))
485
+ cache_delitem(self, curr.key)
486
+ del links[curr.key]
487
+ next = curr.next
488
+ curr.unlink()
489
+ curr = next
490
+ return expired
491
+
492
+ def popitem(self):
493
+ """Remove and return the `(key, value)` pair least recently used that
494
+ has not already expired.
495
+
496
+ """
497
+ with self.timer as time:
498
+ self.expire(time)
499
+ try:
500
+ key = next(iter(self.__links))
501
+ except StopIteration:
502
+ raise KeyError("%s is empty" % type(self).__name__) from None
503
+ else:
504
+ return (key, self.pop(key))
505
+
506
+ def __getlink(self, key):
507
+ value = self.__links[key]
508
+ self.__links.move_to_end(key)
509
+ return value
510
+
511
+
512
+ class TLRUCache(_TimedCache):
513
+ """Time aware Least Recently Used (TLRU) cache implementation."""
514
+
515
+ @functools.total_ordering
516
+ class _Item:
517
+ __slots__ = ("key", "expires", "removed")
518
+
519
+ def __init__(self, key=None, expires=None):
520
+ self.key = key
521
+ self.expires = expires
522
+ self.removed = False
523
+
524
+ def __lt__(self, other):
525
+ return self.expires < other.expires
526
+
527
+ def __init__(self, maxsize, ttu, timer=time.monotonic, getsizeof=None):
528
+ _TimedCache.__init__(self, maxsize, timer, getsizeof)
529
+ self.__items = collections.OrderedDict()
530
+ self.__order = []
531
+ self.__ttu = ttu
532
+
533
+ def __contains__(self, key):
534
+ try:
535
+ item = self.__items[key] # no reordering
536
+ except KeyError:
537
+ return False
538
+ else:
539
+ return self.timer() < item.expires
540
+
541
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
542
+ try:
543
+ item = self.__getitem(key)
544
+ except KeyError:
545
+ expired = False
546
+ else:
547
+ expired = not (self.timer() < item.expires)
548
+ if expired:
549
+ return self.__missing__(key)
550
+ else:
551
+ return cache_getitem(self, key)
552
+
553
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
554
+ with self.timer as time:
555
+ expires = self.__ttu(key, value, time)
556
+ if not (time < expires):
557
+ return # skip expired items
558
+ self.expire(time)
559
+ cache_setitem(self, key, value)
560
+ # removing an existing item would break the heap structure, so
561
+ # only mark it as removed for now
562
+ try:
563
+ self.__getitem(key).removed = True
564
+ except KeyError:
565
+ pass
566
+ self.__items[key] = item = TLRUCache._Item(key, expires)
567
+ heapq.heappush(self.__order, item)
568
+
569
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
570
+ with self.timer as time:
571
+ # no self.expire() for performance reasons, e.g. self.clear() [#67]
572
+ cache_delitem(self, key)
573
+ item = self.__items.pop(key)
574
+ item.removed = True
575
+ if not (time < item.expires):
576
+ raise KeyError(key)
577
+
578
+ def __iter__(self):
579
+ for curr in self.__order:
580
+ # "freeze" time for iterator access
581
+ with self.timer as time:
582
+ if time < curr.expires and not curr.removed:
583
+ yield curr.key
584
+
585
+ @property
586
+ def ttu(self):
587
+ """The local time-to-use function used by the cache."""
588
+ return self.__ttu
589
+
590
+ def expire(self, time=None):
591
+ """Remove expired items from the cache and return an iterable of the
592
+ expired `(key, value)` pairs.
593
+
594
+ """
595
+ if time is None:
596
+ time = self.timer()
597
+ items = self.__items
598
+ order = self.__order
599
+ # clean up the heap if too many items are marked as removed
600
+ if len(order) > len(items) * 2:
601
+ self.__order = order = [item for item in order if not item.removed]
602
+ heapq.heapify(order)
603
+ expired = []
604
+ cache_delitem = Cache.__delitem__
605
+ cache_getitem = Cache.__getitem__
606
+ while order and (order[0].removed or not (time < order[0].expires)):
607
+ item = heapq.heappop(order)
608
+ if not item.removed:
609
+ expired.append((item.key, cache_getitem(self, item.key)))
610
+ cache_delitem(self, item.key)
611
+ del items[item.key]
612
+ return expired
613
+
614
+ def popitem(self):
615
+ """Remove and return the `(key, value)` pair least recently used that
616
+ has not already expired.
617
+
618
+ """
619
+ with self.timer as time:
620
+ self.expire(time)
621
+ try:
622
+ key = next(iter(self.__items))
623
+ except StopIteration:
624
+ raise KeyError("%s is empty" % self.__class__.__name__) from None
625
+ else:
626
+ return (key, self.pop(key))
627
+
628
+ def __getitem(self, key):
629
+ value = self.__items[key]
630
+ self.__items.move_to_end(key)
631
+ return value
632
+
633
+
634
+ _CacheInfo = collections.namedtuple(
635
+ "CacheInfo", ["hits", "misses", "maxsize", "currsize"]
636
+ )
637
+
638
+
639
+ def cached(cache, key=keys.hashkey, lock=None, info=False):
640
+ """Decorator to wrap a function with a memoizing callable that saves
641
+ results in a cache.
642
+
643
+ """
644
+
645
+ def decorator(func):
646
+ if info:
647
+ if isinstance(cache, Cache):
648
+
649
+ def make_info(hits, misses):
650
+ return _CacheInfo(hits, misses, cache.maxsize, cache.currsize)
651
+
652
+ elif isinstance(cache, collections.abc.Mapping):
653
+
654
+ def make_info(hits, misses):
655
+ return _CacheInfo(hits, misses, None, len(cache))
656
+
657
+ else:
658
+
659
+ def make_info(hits, misses):
660
+ return _CacheInfo(hits, misses, 0, 0)
661
+
662
+ wrapper = _cached_wrapper(func, cache, key, lock, make_info)
663
+ else:
664
+ wrapper = _cached_wrapper(func, cache, key, lock, None)
665
+
666
+ wrapper.cache = cache
667
+ wrapper.cache_key = key
668
+ wrapper.cache_lock = lock
669
+
670
+ return functools.update_wrapper(wrapper, func)
671
+
672
+ return decorator
673
+
674
+
675
+ def cachedmethod(cache, key=keys.methodkey, lock=None):
676
+ """Decorator to wrap a class or instance method with a memoizing
677
+ callable that saves results in a cache.
678
+
679
+ """
680
+
681
+ def decorator(method):
682
+ if lock is None:
683
+
684
+ def wrapper(self, *args, **kwargs):
685
+ c = cache(self)
686
+ if c is None:
687
+ return method(self, *args, **kwargs)
688
+ k = key(self, *args, **kwargs)
689
+ try:
690
+ return c[k]
691
+ except KeyError:
692
+ pass # key not found
693
+ v = method(self, *args, **kwargs)
694
+ try:
695
+ c[k] = v
696
+ except ValueError:
697
+ pass # value too large
698
+ return v
699
+
700
+ def clear(self):
701
+ c = cache(self)
702
+ if c is not None:
703
+ c.clear()
704
+
705
+ else:
706
+
707
+ def wrapper(self, *args, **kwargs):
708
+ c = cache(self)
709
+ if c is None:
710
+ return method(self, *args, **kwargs)
711
+ k = key(self, *args, **kwargs)
712
+ try:
713
+ with lock(self):
714
+ return c[k]
715
+ except KeyError:
716
+ pass # key not found
717
+ v = method(self, *args, **kwargs)
718
+ # in case of a race, prefer the item already in the cache
719
+ try:
720
+ with lock(self):
721
+ return c.setdefault(k, v)
722
+ except ValueError:
723
+ return v # value too large
724
+
725
+ def clear(self):
726
+ c = cache(self)
727
+ if c is not None:
728
+ with lock(self):
729
+ c.clear()
730
+
731
+ wrapper.cache = cache
732
+ wrapper.cache_key = key
733
+ wrapper.cache_lock = lock
734
+ wrapper.cache_clear = clear
735
+
736
+ return functools.update_wrapper(wrapper, method)
737
+
738
+ return decorator
python_embeded/Lib/site-packages/cachetools/_decorators.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extensible memoizing decorator helpers."""
2
+
3
+
4
+ def _cached_locked_info(func, cache, key, lock, info):
5
+ hits = misses = 0
6
+
7
+ def wrapper(*args, **kwargs):
8
+ nonlocal hits, misses
9
+ k = key(*args, **kwargs)
10
+ with lock:
11
+ try:
12
+ result = cache[k]
13
+ hits += 1
14
+ return result
15
+ except KeyError:
16
+ misses += 1
17
+ v = func(*args, **kwargs)
18
+ with lock:
19
+ try:
20
+ # in case of a race, prefer the item already in the cache
21
+ return cache.setdefault(k, v)
22
+ except ValueError:
23
+ return v # value too large
24
+
25
+ def cache_clear():
26
+ nonlocal hits, misses
27
+ with lock:
28
+ cache.clear()
29
+ hits = misses = 0
30
+
31
+ def cache_info():
32
+ with lock:
33
+ return info(hits, misses)
34
+
35
+ wrapper.cache_clear = cache_clear
36
+ wrapper.cache_info = cache_info
37
+ return wrapper
38
+
39
+
40
+ def _cached_unlocked_info(func, cache, key, info):
41
+ hits = misses = 0
42
+
43
+ def wrapper(*args, **kwargs):
44
+ nonlocal hits, misses
45
+ k = key(*args, **kwargs)
46
+ try:
47
+ result = cache[k]
48
+ hits += 1
49
+ return result
50
+ except KeyError:
51
+ misses += 1
52
+ v = func(*args, **kwargs)
53
+ try:
54
+ cache[k] = v
55
+ except ValueError:
56
+ pass # value too large
57
+ return v
58
+
59
+ def cache_clear():
60
+ nonlocal hits, misses
61
+ cache.clear()
62
+ hits = misses = 0
63
+
64
+ wrapper.cache_clear = cache_clear
65
+ wrapper.cache_info = lambda: info(hits, misses)
66
+ return wrapper
67
+
68
+
69
+ def _uncached_info(func, info):
70
+ misses = 0
71
+
72
+ def wrapper(*args, **kwargs):
73
+ nonlocal misses
74
+ misses += 1
75
+ return func(*args, **kwargs)
76
+
77
+ def cache_clear():
78
+ nonlocal misses
79
+ misses = 0
80
+
81
+ wrapper.cache_clear = cache_clear
82
+ wrapper.cache_info = lambda: info(0, misses)
83
+ return wrapper
84
+
85
+
86
+ def _cached_locked(func, cache, key, lock):
87
+ def wrapper(*args, **kwargs):
88
+ k = key(*args, **kwargs)
89
+ with lock:
90
+ try:
91
+ return cache[k]
92
+ except KeyError:
93
+ pass # key not found
94
+ v = func(*args, **kwargs)
95
+ with lock:
96
+ try:
97
+ # in case of a race, prefer the item already in the cache
98
+ return cache.setdefault(k, v)
99
+ except ValueError:
100
+ return v # value too large
101
+
102
+ def cache_clear():
103
+ with lock:
104
+ cache.clear()
105
+
106
+ wrapper.cache_clear = cache_clear
107
+ return wrapper
108
+
109
+
110
+ def _cached_unlocked(func, cache, key):
111
+ def wrapper(*args, **kwargs):
112
+ k = key(*args, **kwargs)
113
+ try:
114
+ return cache[k]
115
+ except KeyError:
116
+ pass # key not found
117
+ v = func(*args, **kwargs)
118
+ try:
119
+ cache[k] = v
120
+ except ValueError:
121
+ pass # value too large
122
+ return v
123
+
124
+ wrapper.cache_clear = lambda: cache.clear()
125
+ return wrapper
126
+
127
+
128
+ def _uncached(func):
129
+ def wrapper(*args, **kwargs):
130
+ return func(*args, **kwargs)
131
+
132
+ wrapper.cache_clear = lambda: None
133
+ return wrapper
134
+
135
+
136
+ def _cached_wrapper(func, cache, key, lock, info):
137
+ if info is not None:
138
+ if cache is None:
139
+ wrapper = _uncached_info(func, info)
140
+ elif lock is None:
141
+ wrapper = _cached_unlocked_info(func, cache, key, info)
142
+ else:
143
+ wrapper = _cached_locked_info(func, cache, key, lock, info)
144
+ else:
145
+ if cache is None:
146
+ wrapper = _uncached(func)
147
+ elif lock is None:
148
+ wrapper = _cached_unlocked(func, cache, key)
149
+ else:
150
+ wrapper = _cached_locked(func, cache, key, lock)
151
+ wrapper.cache_info = None
152
+ return wrapper
python_embeded/Lib/site-packages/cachetools/func.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """`functools.lru_cache` compatible memoizing function decorators."""
2
+
3
+ __all__ = ("fifo_cache", "lfu_cache", "lru_cache", "mru_cache", "rr_cache", "ttl_cache")
4
+
5
+ import math
6
+ import random
7
+ import time
8
+
9
+ try:
10
+ from threading import RLock
11
+ except ImportError: # pragma: no cover
12
+ from dummy_threading import RLock
13
+
14
+ from . import FIFOCache, LFUCache, LRUCache, MRUCache, RRCache, TTLCache
15
+ from . import cached
16
+ from . import keys
17
+
18
+
19
+ class _UnboundTTLCache(TTLCache):
20
+ def __init__(self, ttl, timer):
21
+ TTLCache.__init__(self, math.inf, ttl, timer)
22
+
23
+ @property
24
+ def maxsize(self):
25
+ return None
26
+
27
+
28
+ def _cache(cache, maxsize, typed):
29
+ def decorator(func):
30
+ key = keys.typedkey if typed else keys.hashkey
31
+ wrapper = cached(cache=cache, key=key, lock=RLock(), info=True)(func)
32
+ wrapper.cache_parameters = lambda: {"maxsize": maxsize, "typed": typed}
33
+ return wrapper
34
+
35
+ return decorator
36
+
37
+
38
+ def fifo_cache(maxsize=128, typed=False):
39
+ """Decorator to wrap a function with a memoizing callable that saves
40
+ up to `maxsize` results based on a First In First Out (FIFO)
41
+ algorithm.
42
+
43
+ """
44
+ if maxsize is None:
45
+ return _cache({}, None, typed)
46
+ elif callable(maxsize):
47
+ return _cache(FIFOCache(128), 128, typed)(maxsize)
48
+ else:
49
+ return _cache(FIFOCache(maxsize), maxsize, typed)
50
+
51
+
52
+ def lfu_cache(maxsize=128, typed=False):
53
+ """Decorator to wrap a function with a memoizing callable that saves
54
+ up to `maxsize` results based on a Least Frequently Used (LFU)
55
+ algorithm.
56
+
57
+ """
58
+ if maxsize is None:
59
+ return _cache({}, None, typed)
60
+ elif callable(maxsize):
61
+ return _cache(LFUCache(128), 128, typed)(maxsize)
62
+ else:
63
+ return _cache(LFUCache(maxsize), maxsize, typed)
64
+
65
+
66
+ def lru_cache(maxsize=128, typed=False):
67
+ """Decorator to wrap a function with a memoizing callable that saves
68
+ up to `maxsize` results based on a Least Recently Used (LRU)
69
+ algorithm.
70
+
71
+ """
72
+ if maxsize is None:
73
+ return _cache({}, None, typed)
74
+ elif callable(maxsize):
75
+ return _cache(LRUCache(128), 128, typed)(maxsize)
76
+ else:
77
+ return _cache(LRUCache(maxsize), maxsize, typed)
78
+
79
+
80
+ def mru_cache(maxsize=128, typed=False):
81
+ """Decorator to wrap a function with a memoizing callable that saves
82
+ up to `maxsize` results based on a Most Recently Used (MRU)
83
+ algorithm.
84
+ """
85
+ from warnings import warn
86
+
87
+ warn("@mru_cache is deprecated", DeprecationWarning, stacklevel=2)
88
+
89
+ if maxsize is None:
90
+ return _cache({}, None, typed)
91
+ elif callable(maxsize):
92
+ return _cache(MRUCache(128), 128, typed)(maxsize)
93
+ else:
94
+ return _cache(MRUCache(maxsize), maxsize, typed)
95
+
96
+
97
+ def rr_cache(maxsize=128, choice=random.choice, typed=False):
98
+ """Decorator to wrap a function with a memoizing callable that saves
99
+ up to `maxsize` results based on a Random Replacement (RR)
100
+ algorithm.
101
+
102
+ """
103
+ if maxsize is None:
104
+ return _cache({}, None, typed)
105
+ elif callable(maxsize):
106
+ return _cache(RRCache(128, choice), 128, typed)(maxsize)
107
+ else:
108
+ return _cache(RRCache(maxsize, choice), maxsize, typed)
109
+
110
+
111
+ def ttl_cache(maxsize=128, ttl=600, timer=time.monotonic, typed=False):
112
+ """Decorator to wrap a function with a memoizing callable that saves
113
+ up to `maxsize` results based on a Least Recently Used (LRU)
114
+ algorithm with a per-item time-to-live (TTL) value.
115
+ """
116
+ if maxsize is None:
117
+ return _cache(_UnboundTTLCache(ttl, timer), None, typed)
118
+ elif callable(maxsize):
119
+ return _cache(TTLCache(128, ttl, timer), 128, typed)(maxsize)
120
+ else:
121
+ return _cache(TTLCache(maxsize, ttl, timer), maxsize, typed)
python_embeded/Lib/site-packages/cachetools/keys.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Key functions for memoizing decorators."""
2
+
3
+ __all__ = ("hashkey", "methodkey", "typedkey", "typedmethodkey")
4
+
5
+
6
+ class _HashedTuple(tuple):
7
+ """A tuple that ensures that hash() will be called no more than once
8
+ per element, since cache decorators will hash the key multiple
9
+ times on a cache miss. See also _HashedSeq in the standard
10
+ library functools implementation.
11
+
12
+ """
13
+
14
+ __hashvalue = None
15
+
16
+ def __hash__(self, hash=tuple.__hash__):
17
+ hashvalue = self.__hashvalue
18
+ if hashvalue is None:
19
+ self.__hashvalue = hashvalue = hash(self)
20
+ return hashvalue
21
+
22
+ def __add__(self, other, add=tuple.__add__):
23
+ return _HashedTuple(add(self, other))
24
+
25
+ def __radd__(self, other, add=tuple.__add__):
26
+ return _HashedTuple(add(other, self))
27
+
28
+ def __getstate__(self):
29
+ return {}
30
+
31
+
32
+ # used for separating keyword arguments; we do not use an object
33
+ # instance here so identity is preserved when pickling/unpickling
34
+ _kwmark = (_HashedTuple,)
35
+
36
+
37
+ def hashkey(*args, **kwargs):
38
+ """Return a cache key for the specified hashable arguments."""
39
+
40
+ if kwargs:
41
+ return _HashedTuple(args + sum(sorted(kwargs.items()), _kwmark))
42
+ else:
43
+ return _HashedTuple(args)
44
+
45
+
46
+ def methodkey(self, *args, **kwargs):
47
+ """Return a cache key for use with cached methods."""
48
+ return hashkey(*args, **kwargs)
49
+
50
+
51
+ def typedkey(*args, **kwargs):
52
+ """Return a typed cache key for the specified hashable arguments."""
53
+
54
+ key = hashkey(*args, **kwargs)
55
+ key += tuple(type(v) for v in args)
56
+ key += tuple(type(v) for _, v in sorted(kwargs.items()))
57
+ return key
58
+
59
+
60
+ def typedmethodkey(self, *args, **kwargs):
61
+ """Return a typed cache key for use with cached methods."""
62
+ return typedkey(*args, **kwargs)
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/METADATA ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: certifi
3
+ Version: 2025.6.15
4
+ Summary: Python package for providing Mozilla's CA Bundle.
5
+ Home-page: https://github.com/certifi/python-certifi
6
+ Author: Kenneth Reitz
7
+ Author-email: me@kennethreitz.com
8
+ License: MPL-2.0
9
+ Project-URL: Source, https://github.com/certifi/python-certifi
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Requires-Python: >=3.7
25
+ License-File: LICENSE
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: home-page
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: project-url
34
+ Dynamic: requires-python
35
+ Dynamic: summary
36
+
37
+ Certifi: Python SSL Certificates
38
+ ================================
39
+
40
+ Certifi provides Mozilla's carefully curated collection of Root Certificates for
41
+ validating the trustworthiness of SSL certificates while verifying the identity
42
+ of TLS hosts. It has been extracted from the `Requests`_ project.
43
+
44
+ Installation
45
+ ------------
46
+
47
+ ``certifi`` is available on PyPI. Simply install it with ``pip``::
48
+
49
+ $ pip install certifi
50
+
51
+ Usage
52
+ -----
53
+
54
+ To reference the installed certificate authority (CA) bundle, you can use the
55
+ built-in function::
56
+
57
+ >>> import certifi
58
+
59
+ >>> certifi.where()
60
+ '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
61
+
62
+ Or from the command line::
63
+
64
+ $ python -m certifi
65
+ /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
66
+
67
+ Enjoy!
68
+
69
+ .. _`Requests`: https://requests.readthedocs.io/en/master/
70
+
71
+ Addition/Removal of Certificates
72
+ --------------------------------
73
+
74
+ Certifi does not support any addition/removal or other modification of the
75
+ CA trust store content. This project is intended to provide a reliable and
76
+ highly portable root of trust to python deployments. Look to upstream projects
77
+ for methods to use alternate trust.
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/RECORD ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ certifi-2025.6.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ certifi-2025.6.15.dist-info/METADATA,sha256=zgiNbFi9bMv8olVT9OQxB7G5-xQmCjQZ5eO7Z0IGKoI,2423
3
+ certifi-2025.6.15.dist-info/RECORD,,
4
+ certifi-2025.6.15.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ certifi-2025.6.15.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
+ certifi-2025.6.15.dist-info/direct_url.json,sha256=iIVurJUMFHuWBib0FbjcBAngsDVRc6I4v7IcVX-w28A,275
7
+ certifi-2025.6.15.dist-info/licenses/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
8
+ certifi-2025.6.15.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
9
+ certifi/__init__.py,sha256=H8ta5ryBBsJrzYoTklAyzrzsu-dZlfkyL5_aPq5vvFM,94
10
+ certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
11
+ certifi/__pycache__/__init__.cpython-312.pyc,,
12
+ certifi/__pycache__/__main__.cpython-312.pyc,,
13
+ certifi/__pycache__/core.cpython-312.pyc,,
14
+ certifi/cacert.pem,sha256=sc3S1mV1jvSdCPQOoT4agm5fBBLp4JQMkh7RAhRkzcI,281225
15
+ certifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394
16
+ certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/REQUESTED ADDED
File without changes
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/direct_url.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"archive_info": {"hash": "sha256=2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057", "hashes": {"sha256": "2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057"}}, "url": "file:///C:/a/ComfyUI/cu128_python_deps/certifi-2025.6.15-py3-none-any.whl"}
python_embeded/Lib/site-packages/certifi-2025.6.15.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ certifi
python_embeded/Lib/site-packages/certifi/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .core import contents, where
2
+
3
+ __all__ = ["contents", "where"]
4
+ __version__ = "2025.06.15"
python_embeded/Lib/site-packages/certifi/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from certifi import contents, where
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("-c", "--contents", action="store_true")
7
+ args = parser.parse_args()
8
+
9
+ if args.contents:
10
+ print(contents())
11
+ else:
12
+ print(where())
python_embeded/Lib/site-packages/certifi/cacert.pem ADDED
The diff for this file is too large to render. See raw diff
 
python_embeded/Lib/site-packages/certifi/core.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ certifi.py
3
+ ~~~~~~~~~~
4
+
5
+ This module returns the installation location of cacert.pem or its contents.
6
+ """
7
+ import sys
8
+ import atexit
9
+
10
+ def exit_cacert_ctx() -> None:
11
+ _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr]
12
+
13
+
14
+ if sys.version_info >= (3, 11):
15
+
16
+ from importlib.resources import as_file, files
17
+
18
+ _CACERT_CTX = None
19
+ _CACERT_PATH = None
20
+
21
+ def where() -> str:
22
+ # This is slightly terrible, but we want to delay extracting the file
23
+ # in cases where we're inside of a zipimport situation until someone
24
+ # actually calls where(), but we don't want to re-extract the file
25
+ # on every call of where(), so we'll do it once then store it in a
26
+ # global variable.
27
+ global _CACERT_CTX
28
+ global _CACERT_PATH
29
+ if _CACERT_PATH is None:
30
+ # This is slightly janky, the importlib.resources API wants you to
31
+ # manage the cleanup of this file, so it doesn't actually return a
32
+ # path, it returns a context manager that will give you the path
33
+ # when you enter it and will do any cleanup when you leave it. In
34
+ # the common case of not needing a temporary file, it will just
35
+ # return the file system location and the __exit__() is a no-op.
36
+ #
37
+ # We also have to hold onto the actual context manager, because
38
+ # it will do the cleanup whenever it gets garbage collected, so
39
+ # we will also store that at the global level as well.
40
+ _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem"))
41
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
42
+ atexit.register(exit_cacert_ctx)
43
+
44
+ return _CACERT_PATH
45
+
46
+ def contents() -> str:
47
+ return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii")
48
+
49
+ else:
50
+
51
+ from importlib.resources import path as get_path, read_text
52
+
53
+ _CACERT_CTX = None
54
+ _CACERT_PATH = None
55
+
56
+ def where() -> str:
57
+ # This is slightly terrible, but we want to delay extracting the
58
+ # file in cases where we're inside of a zipimport situation until
59
+ # someone actually calls where(), but we don't want to re-extract
60
+ # the file on every call of where(), so we'll do it once then store
61
+ # it in a global variable.
62
+ global _CACERT_CTX
63
+ global _CACERT_PATH
64
+ if _CACERT_PATH is None:
65
+ # This is slightly janky, the importlib.resources API wants you
66
+ # to manage the cleanup of this file, so it doesn't actually
67
+ # return a path, it returns a context manager that will give
68
+ # you the path when you enter it and will do any cleanup when
69
+ # you leave it. In the common case of not needing a temporary
70
+ # file, it will just return the file system location and the
71
+ # __exit__() is a no-op.
72
+ #
73
+ # We also have to hold onto the actual context manager, because
74
+ # it will do the cleanup whenever it gets garbage collected, so
75
+ # we will also store that at the global level as well.
76
+ _CACERT_CTX = get_path("certifi", "cacert.pem")
77
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
78
+ atexit.register(exit_cacert_ctx)
79
+
80
+ return _CACERT_PATH
81
+
82
+ def contents() -> str:
83
+ return read_text("certifi", "cacert.pem", encoding="ascii")
python_embeded/Lib/site-packages/certifi/py.typed ADDED
File without changes
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/LICENSE ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Except when otherwise stated (look for LICENSE files in directories or
3
+ information at the beginning of each file) all software and
4
+ documentation is licensed as follows:
5
+
6
+ The MIT License
7
+
8
+ Permission is hereby granted, free of charge, to any person
9
+ obtaining a copy of this software and associated documentation
10
+ files (the "Software"), to deal in the Software without
11
+ restriction, including without limitation the rights to use,
12
+ copy, modify, merge, publish, distribute, sublicense, and/or
13
+ sell copies of the Software, and to permit persons to whom the
14
+ Software is furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included
17
+ in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
26
+
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/METADATA ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: cffi
3
+ Version: 1.17.1
4
+ Summary: Foreign Function Interface for Python calling C code.
5
+ Home-page: http://cffi.readthedocs.org
6
+ Author: Armin Rigo, Maciej Fijalkowski
7
+ Author-email: python-cffi@googlegroups.com
8
+ License: MIT
9
+ Project-URL: Documentation, http://cffi.readthedocs.org/
10
+ Project-URL: Source Code, https://github.com/python-cffi/cffi
11
+ Project-URL: Issue Tracker, https://github.com/python-cffi/cffi/issues
12
+ Project-URL: Changelog, https://cffi.readthedocs.io/en/latest/whatsnew.html
13
+ Project-URL: Downloads, https://github.com/python-cffi/cffi/releases
14
+ Project-URL: Contact, https://groups.google.com/forum/#!forum/python-cffi
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
25
+ Classifier: License :: OSI Approved :: MIT License
26
+ Requires-Python: >=3.8
27
+ License-File: LICENSE
28
+ Requires-Dist: pycparser
29
+
30
+
31
+ CFFI
32
+ ====
33
+
34
+ Foreign Function Interface for Python calling C code.
35
+ Please see the `Documentation <http://cffi.readthedocs.org/>`_.
36
+
37
+ Contact
38
+ -------
39
+
40
+ `Mailing list <https://groups.google.com/forum/#!forum/python-cffi>`_
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/RECORD ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _cffi_backend.cp312-win_amd64.pyd,sha256=hvE2VTujAccOe62oQWt360oH92zLAvfXPCmZo4-l-ls,179712
2
+ cffi-1.17.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
3
+ cffi-1.17.1.dist-info/LICENSE,sha256=BLgPWwd7vtaICM_rreteNSPyqMmpZJXFh72W3x6sKjM,1294
4
+ cffi-1.17.1.dist-info/METADATA,sha256=avJrvo-kUNx6iXJEaZVjGXNy42QS-YfjNHdJdeiBlFc,1571
5
+ cffi-1.17.1.dist-info/RECORD,,
6
+ cffi-1.17.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ cffi-1.17.1.dist-info/WHEEL,sha256=3zjzPpJAAQZ7kyAYr1O63QL4y0ohnWT_s-XnjTM8vt0,101
8
+ cffi-1.17.1.dist-info/direct_url.json,sha256=UWeE6VVFiZrPDqCsKambabHZq75qc-p9xGsQ4HMD1YI,278
9
+ cffi-1.17.1.dist-info/entry_points.txt,sha256=y6jTxnyeuLnL-XJcDv8uML3n6wyYiGRg8MTp_QGJ9Ho,75
10
+ cffi-1.17.1.dist-info/top_level.txt,sha256=rE7WR3rZfNKxWI9-jn6hsHCAl7MDkB-FmuQbxWjFehQ,19
11
+ cffi/__init__.py,sha256=H6t_ebva6EeHpUuItFLW1gbRp94eZRNJODLaWKdbx1I,513
12
+ cffi/__pycache__/__init__.cpython-312.pyc,,
13
+ cffi/__pycache__/_imp_emulation.cpython-312.pyc,,
14
+ cffi/__pycache__/_shimmed_dist_utils.cpython-312.pyc,,
15
+ cffi/__pycache__/api.cpython-312.pyc,,
16
+ cffi/__pycache__/backend_ctypes.cpython-312.pyc,,
17
+ cffi/__pycache__/cffi_opcode.cpython-312.pyc,,
18
+ cffi/__pycache__/commontypes.cpython-312.pyc,,
19
+ cffi/__pycache__/cparser.cpython-312.pyc,,
20
+ cffi/__pycache__/error.cpython-312.pyc,,
21
+ cffi/__pycache__/ffiplatform.cpython-312.pyc,,
22
+ cffi/__pycache__/lock.cpython-312.pyc,,
23
+ cffi/__pycache__/model.cpython-312.pyc,,
24
+ cffi/__pycache__/pkgconfig.cpython-312.pyc,,
25
+ cffi/__pycache__/recompiler.cpython-312.pyc,,
26
+ cffi/__pycache__/setuptools_ext.cpython-312.pyc,,
27
+ cffi/__pycache__/vengine_cpy.cpython-312.pyc,,
28
+ cffi/__pycache__/vengine_gen.cpython-312.pyc,,
29
+ cffi/__pycache__/verifier.cpython-312.pyc,,
30
+ cffi/_cffi_errors.h,sha256=zQXt7uR_m8gUW-fI2hJg0KoSkJFwXv8RGUkEDZ177dQ,3908
31
+ cffi/_cffi_include.h,sha256=Exhmgm9qzHWzWivjfTe0D7Xp4rPUkVxdNuwGhMTMzbw,15055
32
+ cffi/_embedding.h,sha256=EDKw5QrLvQoe3uosXB3H1xPVTYxsn33eV3A43zsA_Fw,18787
33
+ cffi/_imp_emulation.py,sha256=RxREG8zAbI2RPGBww90u_5fi8sWdahpdipOoPzkp7C0,2960
34
+ cffi/_shimmed_dist_utils.py,sha256=Bjj2wm8yZbvFvWEx5AEfmqaqZyZFhYfoyLLQHkXZuao,2230
35
+ cffi/api.py,sha256=alBv6hZQkjpmZplBphdaRn2lPO9-CORs_M7ixabvZWI,42169
36
+ cffi/backend_ctypes.py,sha256=h5ZIzLc6BFVXnGyc9xPqZWUS7qGy7yFSDqXe68Sa8z4,42454
37
+ cffi/cffi_opcode.py,sha256=JDV5l0R0_OadBX_uE7xPPTYtMdmpp8I9UYd6av7aiDU,5731
38
+ cffi/commontypes.py,sha256=7N6zPtCFlvxXMWhHV08psUjdYIK2XgsN3yo5dgua_v4,2805
39
+ cffi/cparser.py,sha256=0qI3mEzZSNVcCangoyXOoAcL-RhpQL08eG8798T024s,44789
40
+ cffi/error.py,sha256=v6xTiS4U0kvDcy4h_BDRo5v39ZQuj-IMRYLv5ETddZs,877
41
+ cffi/ffiplatform.py,sha256=avxFjdikYGJoEtmJO7ewVmwG_VEVl6EZ_WaNhZYCqv4,3584
42
+ cffi/lock.py,sha256=l9TTdwMIMpi6jDkJGnQgE9cvTIR7CAntIJr8EGHt3pY,747
43
+ cffi/model.py,sha256=W30UFQZE73jL5Mx5N81YT77us2W2iJjTm0XYfnwz1cg,21797
44
+ cffi/parse_c_type.h,sha256=OdwQfwM9ktq6vlCB43exFQmxDBtj2MBNdK8LYl15tjw,5976
45
+ cffi/pkgconfig.py,sha256=LP1w7vmWvmKwyqLaU1Z243FOWGNQMrgMUZrvgFuOlco,4374
46
+ cffi/recompiler.py,sha256=sim4Tm7lamt2Jn8uzKN0wMYp6ODByk3g7of47-h9LD4,65367
47
+ cffi/setuptools_ext.py,sha256=-ebj79lO2_AUH-kRcaja2pKY1Z_5tloGwsJgzK8P3Cc,8871
48
+ cffi/vengine_cpy.py,sha256=8UagT6ZEOZf6Dju7_CfNulue8CnsHLEzJYhnqUhoF04,43752
49
+ cffi/vengine_gen.py,sha256=DUlEIrDiVin1Pnhn1sfoamnS5NLqfJcOdhRoeSNeJRg,26939
50
+ cffi/verifier.py,sha256=oX8jpaohg2Qm3aHcznidAdvrVm5N4sQYG0a3Eo5mIl4,11182
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/REQUESTED ADDED
File without changes
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (74.1.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-win_amd64
5
+
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/direct_url.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"archive_info": {"hash": "sha256=51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903", "hashes": {"sha256": "51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903"}}, "url": "file:///C:/a/ComfyUI/cu128_python_deps/cffi-1.17.1-cp312-cp312-win_amd64.whl"}
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [distutils.setup_keywords]
2
+ cffi_modules = cffi.setuptools_ext:cffi_modules
python_embeded/Lib/site-packages/cffi-1.17.1.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ _cffi_backend
2
+ cffi
python_embeded/Lib/site-packages/cffi/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError',
2
+ 'FFIError']
3
+
4
+ from .api import FFI
5
+ from .error import CDefError, FFIError, VerificationError, VerificationMissing
6
+ from .error import PkgConfigError
7
+
8
+ __version__ = "1.17.1"
9
+ __version_info__ = (1, 17, 1)
10
+
11
+ # The verifier module file names are based on the CRC32 of a string that
12
+ # contains the following version number. It may be older than __version__
13
+ # if nothing is clearly incompatible.
14
+ __version_verifier_modules__ = "0.8.6"
python_embeded/Lib/site-packages/cffi/_cffi_errors.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef CFFI_MESSAGEBOX
2
+ # ifdef _MSC_VER
3
+ # define CFFI_MESSAGEBOX 1
4
+ # else
5
+ # define CFFI_MESSAGEBOX 0
6
+ # endif
7
+ #endif
8
+
9
+
10
+ #if CFFI_MESSAGEBOX
11
+ /* Windows only: logic to take the Python-CFFI embedding logic
12
+ initialization errors and display them in a background thread
13
+ with MessageBox. The idea is that if the whole program closes
14
+ as a result of this problem, then likely it is already a console
15
+ program and you can read the stderr output in the console too.
16
+ If it is not a console program, then it will likely show its own
17
+ dialog to complain, or generally not abruptly close, and for this
18
+ case the background thread should stay alive.
19
+ */
20
+ static void *volatile _cffi_bootstrap_text;
21
+
22
+ static PyObject *_cffi_start_error_capture(void)
23
+ {
24
+ PyObject *result = NULL;
25
+ PyObject *x, *m, *bi;
26
+
27
+ if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text,
28
+ (void *)1, NULL) != NULL)
29
+ return (PyObject *)1;
30
+
31
+ m = PyImport_AddModule("_cffi_error_capture");
32
+ if (m == NULL)
33
+ goto error;
34
+
35
+ result = PyModule_GetDict(m);
36
+ if (result == NULL)
37
+ goto error;
38
+
39
+ #if PY_MAJOR_VERSION >= 3
40
+ bi = PyImport_ImportModule("builtins");
41
+ #else
42
+ bi = PyImport_ImportModule("__builtin__");
43
+ #endif
44
+ if (bi == NULL)
45
+ goto error;
46
+ PyDict_SetItemString(result, "__builtins__", bi);
47
+ Py_DECREF(bi);
48
+
49
+ x = PyRun_String(
50
+ "import sys\n"
51
+ "class FileLike:\n"
52
+ " def write(self, x):\n"
53
+ " try:\n"
54
+ " of.write(x)\n"
55
+ " except: pass\n"
56
+ " self.buf += x\n"
57
+ " def flush(self):\n"
58
+ " pass\n"
59
+ "fl = FileLike()\n"
60
+ "fl.buf = ''\n"
61
+ "of = sys.stderr\n"
62
+ "sys.stderr = fl\n"
63
+ "def done():\n"
64
+ " sys.stderr = of\n"
65
+ " return fl.buf\n", /* make sure the returned value stays alive */
66
+ Py_file_input,
67
+ result, result);
68
+ Py_XDECREF(x);
69
+
70
+ error:
71
+ if (PyErr_Occurred())
72
+ {
73
+ PyErr_WriteUnraisable(Py_None);
74
+ PyErr_Clear();
75
+ }
76
+ return result;
77
+ }
78
+
79
+ #pragma comment(lib, "user32.lib")
80
+
81
+ static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
82
+ {
83
+ Sleep(666); /* may be interrupted if the whole process is closing */
84
+ #if PY_MAJOR_VERSION >= 3
85
+ MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,
86
+ L"Python-CFFI error",
87
+ MB_OK | MB_ICONERROR);
88
+ #else
89
+ MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
90
+ "Python-CFFI error",
91
+ MB_OK | MB_ICONERROR);
92
+ #endif
93
+ _cffi_bootstrap_text = NULL;
94
+ return 0;
95
+ }
96
+
97
+ static void _cffi_stop_error_capture(PyObject *ecap)
98
+ {
99
+ PyObject *s;
100
+ void *text;
101
+
102
+ if (ecap == (PyObject *)1)
103
+ return;
104
+
105
+ if (ecap == NULL)
106
+ goto error;
107
+
108
+ s = PyRun_String("done()", Py_eval_input, ecap, ecap);
109
+ if (s == NULL)
110
+ goto error;
111
+
112
+ /* Show a dialog box, but in a background thread, and
113
+ never show multiple dialog boxes at once. */
114
+ #if PY_MAJOR_VERSION >= 3
115
+ text = PyUnicode_AsWideCharString(s, NULL);
116
+ #else
117
+ text = PyString_AsString(s);
118
+ #endif
119
+
120
+ _cffi_bootstrap_text = text;
121
+
122
+ if (text != NULL)
123
+ {
124
+ HANDLE h;
125
+ h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
126
+ NULL, 0, NULL);
127
+ if (h != NULL)
128
+ CloseHandle(h);
129
+ }
130
+ /* decref the string, but it should stay alive as 'fl.buf'
131
+ in the small module above. It will really be freed only if
132
+ we later get another similar error. So it's a leak of at
133
+ most one copy of the small module. That's fine for this
134
+ situation which is usually a "fatal error" anyway. */
135
+ Py_DECREF(s);
136
+ PyErr_Clear();
137
+ return;
138
+
139
+ error:
140
+ _cffi_bootstrap_text = NULL;
141
+ PyErr_Clear();
142
+ }
143
+
144
+ #else
145
+
146
+ static PyObject *_cffi_start_error_capture(void) { return NULL; }
147
+ static void _cffi_stop_error_capture(PyObject *ecap) { }
148
+
149
+ #endif
python_embeded/Lib/site-packages/cffi/_cffi_include.h ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define _CFFI_
2
+
3
+ /* We try to define Py_LIMITED_API before including Python.h.
4
+
5
+ Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and
6
+ Py_REF_DEBUG are not defined. This is a best-effort approximation:
7
+ we can learn about Py_DEBUG from pyconfig.h, but it is unclear if
8
+ the same works for the other two macros. Py_DEBUG implies them,
9
+ but not the other way around.
10
+
11
+ The implementation is messy (issue #350): on Windows, with _MSC_VER,
12
+ we have to define Py_LIMITED_API even before including pyconfig.h.
13
+ In that case, we guess what pyconfig.h will do to the macros above,
14
+ and check our guess after the #include.
15
+
16
+ Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv
17
+ version >= 16.0.0. With older versions of either, you don't get a
18
+ copy of PYTHON3.DLL in the virtualenv. We can't check the version of
19
+ CPython *before* we even include pyconfig.h. ffi.set_source() puts
20
+ a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is
21
+ running on Windows < 3.5, as an attempt at fixing it, but that's
22
+ arguably wrong because it may not be the target version of Python.
23
+ Still better than nothing I guess. As another workaround, you can
24
+ remove the definition of Py_LIMITED_API here.
25
+
26
+ See also 'py_limited_api' in cffi/setuptools_ext.py.
27
+ */
28
+ #if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API)
29
+ # ifdef _MSC_VER
30
+ # if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API)
31
+ # define Py_LIMITED_API
32
+ # endif
33
+ # include <pyconfig.h>
34
+ /* sanity-check: Py_LIMITED_API will cause crashes if any of these
35
+ are also defined. Normally, the Python file PC/pyconfig.h does not
36
+ cause any of these to be defined, with the exception that _DEBUG
37
+ causes Py_DEBUG. Double-check that. */
38
+ # ifdef Py_LIMITED_API
39
+ # if defined(Py_DEBUG)
40
+ # error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set"
41
+ # endif
42
+ # if defined(Py_TRACE_REFS)
43
+ # error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set"
44
+ # endif
45
+ # if defined(Py_REF_DEBUG)
46
+ # error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set"
47
+ # endif
48
+ # endif
49
+ # else
50
+ # include <pyconfig.h>
51
+ # if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API)
52
+ # define Py_LIMITED_API
53
+ # endif
54
+ # endif
55
+ #endif
56
+
57
+ #include <Python.h>
58
+ #ifdef __cplusplus
59
+ extern "C" {
60
+ #endif
61
+ #include <stddef.h>
62
+ #include "parse_c_type.h"
63
+
64
+ /* this block of #ifs should be kept exactly identical between
65
+ c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
66
+ and cffi/_cffi_include.h */
67
+ #if defined(_MSC_VER)
68
+ # include <malloc.h> /* for alloca() */
69
+ # if _MSC_VER < 1600 /* MSVC < 2010 */
70
+ typedef __int8 int8_t;
71
+ typedef __int16 int16_t;
72
+ typedef __int32 int32_t;
73
+ typedef __int64 int64_t;
74
+ typedef unsigned __int8 uint8_t;
75
+ typedef unsigned __int16 uint16_t;
76
+ typedef unsigned __int32 uint32_t;
77
+ typedef unsigned __int64 uint64_t;
78
+ typedef __int8 int_least8_t;
79
+ typedef __int16 int_least16_t;
80
+ typedef __int32 int_least32_t;
81
+ typedef __int64 int_least64_t;
82
+ typedef unsigned __int8 uint_least8_t;
83
+ typedef unsigned __int16 uint_least16_t;
84
+ typedef unsigned __int32 uint_least32_t;
85
+ typedef unsigned __int64 uint_least64_t;
86
+ typedef __int8 int_fast8_t;
87
+ typedef __int16 int_fast16_t;
88
+ typedef __int32 int_fast32_t;
89
+ typedef __int64 int_fast64_t;
90
+ typedef unsigned __int8 uint_fast8_t;
91
+ typedef unsigned __int16 uint_fast16_t;
92
+ typedef unsigned __int32 uint_fast32_t;
93
+ typedef unsigned __int64 uint_fast64_t;
94
+ typedef __int64 intmax_t;
95
+ typedef unsigned __int64 uintmax_t;
96
+ # else
97
+ # include <stdint.h>
98
+ # endif
99
+ # if _MSC_VER < 1800 /* MSVC < 2013 */
100
+ # ifndef __cplusplus
101
+ typedef unsigned char _Bool;
102
+ # endif
103
+ # endif
104
+ # define _cffi_float_complex_t _Fcomplex /* include <complex.h> for it */
105
+ # define _cffi_double_complex_t _Dcomplex /* include <complex.h> for it */
106
+ #else
107
+ # include <stdint.h>
108
+ # if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
109
+ # include <alloca.h>
110
+ # endif
111
+ # define _cffi_float_complex_t float _Complex
112
+ # define _cffi_double_complex_t double _Complex
113
+ #endif
114
+
115
+ #ifdef __GNUC__
116
+ # define _CFFI_UNUSED_FN __attribute__((unused))
117
+ #else
118
+ # define _CFFI_UNUSED_FN /* nothing */
119
+ #endif
120
+
121
+ #ifdef __cplusplus
122
+ # ifndef _Bool
123
+ typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */
124
+ # endif
125
+ #endif
126
+
127
+ /********** CPython-specific section **********/
128
+ #ifndef PYPY_VERSION
129
+
130
+
131
+ #if PY_MAJOR_VERSION >= 3
132
+ # define PyInt_FromLong PyLong_FromLong
133
+ #endif
134
+
135
+ #define _cffi_from_c_double PyFloat_FromDouble
136
+ #define _cffi_from_c_float PyFloat_FromDouble
137
+ #define _cffi_from_c_long PyInt_FromLong
138
+ #define _cffi_from_c_ulong PyLong_FromUnsignedLong
139
+ #define _cffi_from_c_longlong PyLong_FromLongLong
140
+ #define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
141
+ #define _cffi_from_c__Bool PyBool_FromLong
142
+
143
+ #define _cffi_to_c_double PyFloat_AsDouble
144
+ #define _cffi_to_c_float PyFloat_AsDouble
145
+
146
+ #define _cffi_from_c_int(x, type) \
147
+ (((type)-1) > 0 ? /* unsigned */ \
148
+ (sizeof(type) < sizeof(long) ? \
149
+ PyInt_FromLong((long)x) : \
150
+ sizeof(type) == sizeof(long) ? \
151
+ PyLong_FromUnsignedLong((unsigned long)x) : \
152
+ PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
153
+ (sizeof(type) <= sizeof(long) ? \
154
+ PyInt_FromLong((long)x) : \
155
+ PyLong_FromLongLong((long long)x)))
156
+
157
+ #define _cffi_to_c_int(o, type) \
158
+ ((type)( \
159
+ sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
160
+ : (type)_cffi_to_c_i8(o)) : \
161
+ sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
162
+ : (type)_cffi_to_c_i16(o)) : \
163
+ sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
164
+ : (type)_cffi_to_c_i32(o)) : \
165
+ sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
166
+ : (type)_cffi_to_c_i64(o)) : \
167
+ (Py_FatalError("unsupported size for type " #type), (type)0)))
168
+
169
+ #define _cffi_to_c_i8 \
170
+ ((int(*)(PyObject *))_cffi_exports[1])
171
+ #define _cffi_to_c_u8 \
172
+ ((int(*)(PyObject *))_cffi_exports[2])
173
+ #define _cffi_to_c_i16 \
174
+ ((int(*)(PyObject *))_cffi_exports[3])
175
+ #define _cffi_to_c_u16 \
176
+ ((int(*)(PyObject *))_cffi_exports[4])
177
+ #define _cffi_to_c_i32 \
178
+ ((int(*)(PyObject *))_cffi_exports[5])
179
+ #define _cffi_to_c_u32 \
180
+ ((unsigned int(*)(PyObject *))_cffi_exports[6])
181
+ #define _cffi_to_c_i64 \
182
+ ((long long(*)(PyObject *))_cffi_exports[7])
183
+ #define _cffi_to_c_u64 \
184
+ ((unsigned long long(*)(PyObject *))_cffi_exports[8])
185
+ #define _cffi_to_c_char \
186
+ ((int(*)(PyObject *))_cffi_exports[9])
187
+ #define _cffi_from_c_pointer \
188
+ ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10])
189
+ #define _cffi_to_c_pointer \
190
+ ((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11])
191
+ #define _cffi_get_struct_layout \
192
+ not used any more
193
+ #define _cffi_restore_errno \
194
+ ((void(*)(void))_cffi_exports[13])
195
+ #define _cffi_save_errno \
196
+ ((void(*)(void))_cffi_exports[14])
197
+ #define _cffi_from_c_char \
198
+ ((PyObject *(*)(char))_cffi_exports[15])
199
+ #define _cffi_from_c_deref \
200
+ ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16])
201
+ #define _cffi_to_c \
202
+ ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17])
203
+ #define _cffi_from_c_struct \
204
+ ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18])
205
+ #define _cffi_to_c_wchar_t \
206
+ ((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19])
207
+ #define _cffi_from_c_wchar_t \
208
+ ((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20])
209
+ #define _cffi_to_c_long_double \
210
+ ((long double(*)(PyObject *))_cffi_exports[21])
211
+ #define _cffi_to_c__Bool \
212
+ ((_Bool(*)(PyObject *))_cffi_exports[22])
213
+ #define _cffi_prepare_pointer_call_argument \
214
+ ((Py_ssize_t(*)(struct _cffi_ctypedescr *, \
215
+ PyObject *, char **))_cffi_exports[23])
216
+ #define _cffi_convert_array_from_object \
217
+ ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24])
218
+ #define _CFFI_CPIDX 25
219
+ #define _cffi_call_python \
220
+ ((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX])
221
+ #define _cffi_to_c_wchar3216_t \
222
+ ((int(*)(PyObject *))_cffi_exports[26])
223
+ #define _cffi_from_c_wchar3216_t \
224
+ ((PyObject *(*)(int))_cffi_exports[27])
225
+ #define _CFFI_NUM_EXPORTS 28
226
+
227
+ struct _cffi_ctypedescr;
228
+
229
+ static void *_cffi_exports[_CFFI_NUM_EXPORTS];
230
+
231
+ #define _cffi_type(index) ( \
232
+ assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \
233
+ (struct _cffi_ctypedescr *)_cffi_types[index])
234
+
235
+ static PyObject *_cffi_init(const char *module_name, Py_ssize_t version,
236
+ const struct _cffi_type_context_s *ctx)
237
+ {
238
+ PyObject *module, *o_arg, *new_module;
239
+ void *raw[] = {
240
+ (void *)module_name,
241
+ (void *)version,
242
+ (void *)_cffi_exports,
243
+ (void *)ctx,
244
+ };
245
+
246
+ module = PyImport_ImportModule("_cffi_backend");
247
+ if (module == NULL)
248
+ goto failure;
249
+
250
+ o_arg = PyLong_FromVoidPtr((void *)raw);
251
+ if (o_arg == NULL)
252
+ goto failure;
253
+
254
+ new_module = PyObject_CallMethod(
255
+ module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg);
256
+
257
+ Py_DECREF(o_arg);
258
+ Py_DECREF(module);
259
+ return new_module;
260
+
261
+ failure:
262
+ Py_XDECREF(module);
263
+ return NULL;
264
+ }
265
+
266
+
267
+ #ifdef HAVE_WCHAR_H
268
+ typedef wchar_t _cffi_wchar_t;
269
+ #else
270
+ typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */
271
+ #endif
272
+
273
+ _CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o)
274
+ {
275
+ if (sizeof(_cffi_wchar_t) == 2)
276
+ return (uint16_t)_cffi_to_c_wchar_t(o);
277
+ else
278
+ return (uint16_t)_cffi_to_c_wchar3216_t(o);
279
+ }
280
+
281
+ _CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x)
282
+ {
283
+ if (sizeof(_cffi_wchar_t) == 2)
284
+ return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
285
+ else
286
+ return _cffi_from_c_wchar3216_t((int)x);
287
+ }
288
+
289
+ _CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o)
290
+ {
291
+ if (sizeof(_cffi_wchar_t) == 4)
292
+ return (int)_cffi_to_c_wchar_t(o);
293
+ else
294
+ return (int)_cffi_to_c_wchar3216_t(o);
295
+ }
296
+
297
+ _CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x)
298
+ {
299
+ if (sizeof(_cffi_wchar_t) == 4)
300
+ return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
301
+ else
302
+ return _cffi_from_c_wchar3216_t((int)x);
303
+ }
304
+
305
+ union _cffi_union_alignment_u {
306
+ unsigned char m_char;
307
+ unsigned short m_short;
308
+ unsigned int m_int;
309
+ unsigned long m_long;
310
+ unsigned long long m_longlong;
311
+ float m_float;
312
+ double m_double;
313
+ long double m_longdouble;
314
+ };
315
+
316
+ struct _cffi_freeme_s {
317
+ struct _cffi_freeme_s *next;
318
+ union _cffi_union_alignment_u alignment;
319
+ };
320
+
321
+ _CFFI_UNUSED_FN static int
322
+ _cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg,
323
+ char **output_data, Py_ssize_t datasize,
324
+ struct _cffi_freeme_s **freeme)
325
+ {
326
+ char *p;
327
+ if (datasize < 0)
328
+ return -1;
329
+
330
+ p = *output_data;
331
+ if (p == NULL) {
332
+ struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc(
333
+ offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize);
334
+ if (fp == NULL)
335
+ return -1;
336
+ fp->next = *freeme;
337
+ *freeme = fp;
338
+ p = *output_data = (char *)&fp->alignment;
339
+ }
340
+ memset((void *)p, 0, (size_t)datasize);
341
+ return _cffi_convert_array_from_object(p, ctptr, arg);
342
+ }
343
+
344
+ _CFFI_UNUSED_FN static void
345
+ _cffi_free_array_arguments(struct _cffi_freeme_s *freeme)
346
+ {
347
+ do {
348
+ void *p = (void *)freeme;
349
+ freeme = freeme->next;
350
+ PyObject_Free(p);
351
+ } while (freeme != NULL);
352
+ }
353
+
354
+ /********** end CPython-specific section **********/
355
+ #else
356
+ _CFFI_UNUSED_FN
357
+ static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *);
358
+ # define _cffi_call_python _cffi_call_python_org
359
+ #endif
360
+
361
+
362
+ #define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0]))
363
+
364
+ #define _cffi_prim_int(size, sign) \
365
+ ((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \
366
+ (size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \
367
+ (size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \
368
+ (size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \
369
+ _CFFI__UNKNOWN_PRIM)
370
+
371
+ #define _cffi_prim_float(size) \
372
+ ((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \
373
+ (size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \
374
+ (size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \
375
+ _CFFI__UNKNOWN_FLOAT_PRIM)
376
+
377
+ #define _cffi_check_int(got, got_nonpos, expected) \
378
+ ((got_nonpos) == (expected <= 0) && \
379
+ (got) == (unsigned long long)expected)
380
+
381
+ #ifdef MS_WIN32
382
+ # define _cffi_stdcall __stdcall
383
+ #else
384
+ # define _cffi_stdcall /* nothing */
385
+ #endif
386
+
387
+ #ifdef __cplusplus
388
+ }
389
+ #endif
python_embeded/Lib/site-packages/cffi/_embedding.h ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ /***** Support code for embedding *****/
3
+
4
+ #ifdef __cplusplus
5
+ extern "C" {
6
+ #endif
7
+
8
+
9
+ #if defined(_WIN32)
10
+ # define CFFI_DLLEXPORT __declspec(dllexport)
11
+ #elif defined(__GNUC__)
12
+ # define CFFI_DLLEXPORT __attribute__((visibility("default")))
13
+ #else
14
+ # define CFFI_DLLEXPORT /* nothing */
15
+ #endif
16
+
17
+
18
+ /* There are two global variables of type _cffi_call_python_fnptr:
19
+
20
+ * _cffi_call_python, which we declare just below, is the one called
21
+ by ``extern "Python"`` implementations.
22
+
23
+ * _cffi_call_python_org, which on CPython is actually part of the
24
+ _cffi_exports[] array, is the function pointer copied from
25
+ _cffi_backend. If _cffi_start_python() fails, then this is set
26
+ to NULL; otherwise, it should never be NULL.
27
+
28
+ After initialization is complete, both are equal. However, the
29
+ first one remains equal to &_cffi_start_and_call_python until the
30
+ very end of initialization, when we are (or should be) sure that
31
+ concurrent threads also see a completely initialized world, and
32
+ only then is it changed.
33
+ */
34
+ #undef _cffi_call_python
35
+ typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *);
36
+ static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *);
37
+ static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python;
38
+
39
+
40
+ #ifndef _MSC_VER
41
+ /* --- Assuming a GCC not infinitely old --- */
42
+ # define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n)
43
+ # define cffi_write_barrier() __sync_synchronize()
44
+ # if !defined(__amd64__) && !defined(__x86_64__) && \
45
+ !defined(__i386__) && !defined(__i386)
46
+ # define cffi_read_barrier() __sync_synchronize()
47
+ # else
48
+ # define cffi_read_barrier() (void)0
49
+ # endif
50
+ #else
51
+ /* --- Windows threads version --- */
52
+ # include <Windows.h>
53
+ # define cffi_compare_and_swap(l,o,n) \
54
+ (InterlockedCompareExchangePointer(l,n,o) == (o))
55
+ # define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0)
56
+ # define cffi_read_barrier() (void)0
57
+ static volatile LONG _cffi_dummy;
58
+ #endif
59
+
60
+ #ifdef WITH_THREAD
61
+ # ifndef _MSC_VER
62
+ # include <pthread.h>
63
+ static pthread_mutex_t _cffi_embed_startup_lock;
64
+ # else
65
+ static CRITICAL_SECTION _cffi_embed_startup_lock;
66
+ # endif
67
+ static char _cffi_embed_startup_lock_ready = 0;
68
+ #endif
69
+
70
+ static void _cffi_acquire_reentrant_mutex(void)
71
+ {
72
+ static void *volatile lock = NULL;
73
+
74
+ while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) {
75
+ /* should ideally do a spin loop instruction here, but
76
+ hard to do it portably and doesn't really matter I
77
+ think: pthread_mutex_init() should be very fast, and
78
+ this is only run at start-up anyway. */
79
+ }
80
+
81
+ #ifdef WITH_THREAD
82
+ if (!_cffi_embed_startup_lock_ready) {
83
+ # ifndef _MSC_VER
84
+ pthread_mutexattr_t attr;
85
+ pthread_mutexattr_init(&attr);
86
+ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
87
+ pthread_mutex_init(&_cffi_embed_startup_lock, &attr);
88
+ # else
89
+ InitializeCriticalSection(&_cffi_embed_startup_lock);
90
+ # endif
91
+ _cffi_embed_startup_lock_ready = 1;
92
+ }
93
+ #endif
94
+
95
+ while (!cffi_compare_and_swap(&lock, (void *)1, NULL))
96
+ ;
97
+
98
+ #ifndef _MSC_VER
99
+ pthread_mutex_lock(&_cffi_embed_startup_lock);
100
+ #else
101
+ EnterCriticalSection(&_cffi_embed_startup_lock);
102
+ #endif
103
+ }
104
+
105
+ static void _cffi_release_reentrant_mutex(void)
106
+ {
107
+ #ifndef _MSC_VER
108
+ pthread_mutex_unlock(&_cffi_embed_startup_lock);
109
+ #else
110
+ LeaveCriticalSection(&_cffi_embed_startup_lock);
111
+ #endif
112
+ }
113
+
114
+
115
+ /********** CPython-specific section **********/
116
+ #ifndef PYPY_VERSION
117
+
118
+ #include "_cffi_errors.h"
119
+
120
+
121
+ #define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX]
122
+
123
+ PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */
124
+
125
+ static void _cffi_py_initialize(void)
126
+ {
127
+ /* XXX use initsigs=0, which "skips initialization registration of
128
+ signal handlers, which might be useful when Python is
129
+ embedded" according to the Python docs. But review and think
130
+ if it should be a user-controllable setting.
131
+
132
+ XXX we should also give a way to write errors to a buffer
133
+ instead of to stderr.
134
+
135
+ XXX if importing 'site' fails, CPython (any version) calls
136
+ exit(). Should we try to work around this behavior here?
137
+ */
138
+ Py_InitializeEx(0);
139
+ }
140
+
141
+ static int _cffi_initialize_python(void)
142
+ {
143
+ /* This initializes Python, imports _cffi_backend, and then the
144
+ present .dll/.so is set up as a CPython C extension module.
145
+ */
146
+ int result;
147
+ PyGILState_STATE state;
148
+ PyObject *pycode=NULL, *global_dict=NULL, *x;
149
+ PyObject *builtins;
150
+
151
+ state = PyGILState_Ensure();
152
+
153
+ /* Call the initxxx() function from the present module. It will
154
+ create and initialize us as a CPython extension module, instead
155
+ of letting the startup Python code do it---it might reimport
156
+ the same .dll/.so and get maybe confused on some platforms.
157
+ It might also have troubles locating the .dll/.so again for all
158
+ I know.
159
+ */
160
+ (void)_CFFI_PYTHON_STARTUP_FUNC();
161
+ if (PyErr_Occurred())
162
+ goto error;
163
+
164
+ /* Now run the Python code provided to ffi.embedding_init_code().
165
+ */
166
+ pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE,
167
+ "<init code for '" _CFFI_MODULE_NAME "'>",
168
+ Py_file_input);
169
+ if (pycode == NULL)
170
+ goto error;
171
+ global_dict = PyDict_New();
172
+ if (global_dict == NULL)
173
+ goto error;
174
+ builtins = PyEval_GetBuiltins();
175
+ if (builtins == NULL)
176
+ goto error;
177
+ if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0)
178
+ goto error;
179
+ x = PyEval_EvalCode(
180
+ #if PY_MAJOR_VERSION < 3
181
+ (PyCodeObject *)
182
+ #endif
183
+ pycode, global_dict, global_dict);
184
+ if (x == NULL)
185
+ goto error;
186
+ Py_DECREF(x);
187
+
188
+ /* Done! Now if we've been called from
189
+ _cffi_start_and_call_python() in an ``extern "Python"``, we can
190
+ only hope that the Python code did correctly set up the
191
+ corresponding @ffi.def_extern() function. Otherwise, the
192
+ general logic of ``extern "Python"`` functions (inside the
193
+ _cffi_backend module) will find that the reference is still
194
+ missing and print an error.
195
+ */
196
+ result = 0;
197
+ done:
198
+ Py_XDECREF(pycode);
199
+ Py_XDECREF(global_dict);
200
+ PyGILState_Release(state);
201
+ return result;
202
+
203
+ error:;
204
+ {
205
+ /* Print as much information as potentially useful.
206
+ Debugging load-time failures with embedding is not fun
207
+ */
208
+ PyObject *ecap;
209
+ PyObject *exception, *v, *tb, *f, *modules, *mod;
210
+ PyErr_Fetch(&exception, &v, &tb);
211
+ ecap = _cffi_start_error_capture();
212
+ f = PySys_GetObject((char *)"stderr");
213
+ if (f != NULL && f != Py_None) {
214
+ PyFile_WriteString(
215
+ "Failed to initialize the Python-CFFI embedding logic:\n\n", f);
216
+ }
217
+
218
+ if (exception != NULL) {
219
+ PyErr_NormalizeException(&exception, &v, &tb);
220
+ PyErr_Display(exception, v, tb);
221
+ }
222
+ Py_XDECREF(exception);
223
+ Py_XDECREF(v);
224
+ Py_XDECREF(tb);
225
+
226
+ if (f != NULL && f != Py_None) {
227
+ PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME
228
+ "\ncompiled with cffi version: 1.17.1"
229
+ "\n_cffi_backend module: ", f);
230
+ modules = PyImport_GetModuleDict();
231
+ mod = PyDict_GetItemString(modules, "_cffi_backend");
232
+ if (mod == NULL) {
233
+ PyFile_WriteString("not loaded", f);
234
+ }
235
+ else {
236
+ v = PyObject_GetAttrString(mod, "__file__");
237
+ PyFile_WriteObject(v, f, 0);
238
+ Py_XDECREF(v);
239
+ }
240
+ PyFile_WriteString("\nsys.path: ", f);
241
+ PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
242
+ PyFile_WriteString("\n\n", f);
243
+ }
244
+ _cffi_stop_error_capture(ecap);
245
+ }
246
+ result = -1;
247
+ goto done;
248
+ }
249
+
250
+ #if PY_VERSION_HEX < 0x03080000
251
+ PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */
252
+ #endif
253
+
254
+ static int _cffi_carefully_make_gil(void)
255
+ {
256
+ /* This does the basic initialization of Python. It can be called
257
+ completely concurrently from unrelated threads. It assumes
258
+ that we don't hold the GIL before (if it exists), and we don't
259
+ hold it afterwards.
260
+
261
+ (What it really does used to be completely different in Python 2
262
+ and Python 3, with the Python 2 solution avoiding the spin-lock
263
+ around the Py_InitializeEx() call. However, after recent changes
264
+ to CPython 2.7 (issue #358) it no longer works. So we use the
265
+ Python 3 solution everywhere.)
266
+
267
+ This initializes Python by calling Py_InitializeEx().
268
+ Important: this must not be called concurrently at all.
269
+ So we use a global variable as a simple spin lock. This global
270
+ variable must be from 'libpythonX.Y.so', not from this
271
+ cffi-based extension module, because it must be shared from
272
+ different cffi-based extension modules.
273
+
274
+ In Python < 3.8, we choose
275
+ _PyParser_TokenNames[0] as a completely arbitrary pointer value
276
+ that is never written to. The default is to point to the
277
+ string "ENDMARKER". We change it temporarily to point to the
278
+ next character in that string. (Yes, I know it's REALLY
279
+ obscure.)
280
+
281
+ In Python >= 3.8, this string array is no longer writable, so
282
+ instead we pick PyCapsuleType.tp_version_tag. We can't change
283
+ Python < 3.8 because someone might use a mixture of cffi
284
+ embedded modules, some of which were compiled before this file
285
+ changed.
286
+
287
+ In Python >= 3.12, this stopped working because that particular
288
+ tp_version_tag gets modified during interpreter startup. It's
289
+ arguably a bad idea before 3.12 too, but again we can't change
290
+ that because someone might use a mixture of cffi embedded
291
+ modules, and no-one reported a bug so far. In Python >= 3.12
292
+ we go instead for PyCapsuleType.tp_as_buffer, which is supposed
293
+ to always be NULL. We write to it temporarily a pointer to
294
+ a struct full of NULLs, which is semantically the same.
295
+ */
296
+
297
+ #ifdef WITH_THREAD
298
+ # if PY_VERSION_HEX < 0x03080000
299
+ char *volatile *lock = (char *volatile *)_PyParser_TokenNames;
300
+ char *old_value, *locked_value;
301
+
302
+ while (1) { /* spin loop */
303
+ old_value = *lock;
304
+ locked_value = old_value + 1;
305
+ if (old_value[0] == 'E') {
306
+ assert(old_value[1] == 'N');
307
+ if (cffi_compare_and_swap(lock, old_value, locked_value))
308
+ break;
309
+ }
310
+ else {
311
+ assert(old_value[0] == 'N');
312
+ /* should ideally do a spin loop instruction here, but
313
+ hard to do it portably and doesn't really matter I
314
+ think: PyEval_InitThreads() should be very fast, and
315
+ this is only run at start-up anyway. */
316
+ }
317
+ }
318
+ # else
319
+ # if PY_VERSION_HEX < 0x030C0000
320
+ int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag;
321
+ int old_value, locked_value = -42;
322
+ assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG));
323
+ # else
324
+ static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs;
325
+ empty_buffer_procs.mark = -42;
326
+ PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *)
327
+ &PyCapsule_Type.tp_as_buffer;
328
+ PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf;
329
+ # endif
330
+
331
+ while (1) { /* spin loop */
332
+ old_value = *lock;
333
+ if (old_value == 0) {
334
+ if (cffi_compare_and_swap(lock, old_value, locked_value))
335
+ break;
336
+ }
337
+ else {
338
+ # if PY_VERSION_HEX < 0x030C0000
339
+ assert(old_value == locked_value);
340
+ # else
341
+ /* The pointer should point to a possibly different
342
+ empty_buffer_procs from another C extension module */
343
+ assert(((struct ebp_s *)old_value)->mark == -42);
344
+ # endif
345
+ /* should ideally do a spin loop instruction here, but
346
+ hard to do it portably and doesn't really matter I
347
+ think: PyEval_InitThreads() should be very fast, and
348
+ this is only run at start-up anyway. */
349
+ }
350
+ }
351
+ # endif
352
+ #endif
353
+
354
+ /* call Py_InitializeEx() */
355
+ if (!Py_IsInitialized()) {
356
+ _cffi_py_initialize();
357
+ #if PY_VERSION_HEX < 0x03070000
358
+ PyEval_InitThreads();
359
+ #endif
360
+ PyEval_SaveThread(); /* release the GIL */
361
+ /* the returned tstate must be the one that has been stored into the
362
+ autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */
363
+ }
364
+ else {
365
+ #if PY_VERSION_HEX < 0x03070000
366
+ /* PyEval_InitThreads() is always a no-op from CPython 3.7 */
367
+ PyGILState_STATE state = PyGILState_Ensure();
368
+ PyEval_InitThreads();
369
+ PyGILState_Release(state);
370
+ #endif
371
+ }
372
+
373
+ #ifdef WITH_THREAD
374
+ /* release the lock */
375
+ while (!cffi_compare_and_swap(lock, locked_value, old_value))
376
+ ;
377
+ #endif
378
+
379
+ return 0;
380
+ }
381
+
382
+ /********** end CPython-specific section **********/
383
+
384
+
385
+ #else
386
+
387
+
388
+ /********** PyPy-specific section **********/
389
+
390
+ PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */
391
+
392
+ static struct _cffi_pypy_init_s {
393
+ const char *name;
394
+ void *func; /* function pointer */
395
+ const char *code;
396
+ } _cffi_pypy_init = {
397
+ _CFFI_MODULE_NAME,
398
+ _CFFI_PYTHON_STARTUP_FUNC,
399
+ _CFFI_PYTHON_STARTUP_CODE,
400
+ };
401
+
402
+ extern int pypy_carefully_make_gil(const char *);
403
+ extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *);
404
+
405
+ static int _cffi_carefully_make_gil(void)
406
+ {
407
+ return pypy_carefully_make_gil(_CFFI_MODULE_NAME);
408
+ }
409
+
410
+ static int _cffi_initialize_python(void)
411
+ {
412
+ return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init);
413
+ }
414
+
415
+ /********** end PyPy-specific section **********/
416
+
417
+
418
+ #endif
419
+
420
+
421
+ #ifdef __GNUC__
422
+ __attribute__((noinline))
423
+ #endif
424
+ static _cffi_call_python_fnptr _cffi_start_python(void)
425
+ {
426
+ /* Delicate logic to initialize Python. This function can be
427
+ called multiple times concurrently, e.g. when the process calls
428
+ its first ``extern "Python"`` functions in multiple threads at
429
+ once. It can also be called recursively, in which case we must
430
+ ignore it. We also have to consider what occurs if several
431
+ different cffi-based extensions reach this code in parallel
432
+ threads---it is a different copy of the code, then, and we
433
+ can't have any shared global variable unless it comes from
434
+ 'libpythonX.Y.so'.
435
+
436
+ Idea:
437
+
438
+ * _cffi_carefully_make_gil(): "carefully" call
439
+ PyEval_InitThreads() (possibly with Py_InitializeEx() first).
440
+
441
+ * then we use a (local) custom lock to make sure that a call to this
442
+ cffi-based extension will wait if another call to the *same*
443
+ extension is running the initialization in another thread.
444
+ It is reentrant, so that a recursive call will not block, but
445
+ only one from a different thread.
446
+
447
+ * then we grab the GIL and (Python 2) we call Py_InitializeEx().
448
+ At this point, concurrent calls to Py_InitializeEx() are not
449
+ possible: we have the GIL.
450
+
451
+ * do the rest of the specific initialization, which may
452
+ temporarily release the GIL but not the custom lock.
453
+ Only release the custom lock when we are done.
454
+ */
455
+ static char called = 0;
456
+
457
+ if (_cffi_carefully_make_gil() != 0)
458
+ return NULL;
459
+
460
+ _cffi_acquire_reentrant_mutex();
461
+
462
+ /* Here the GIL exists, but we don't have it. We're only protected
463
+ from concurrency by the reentrant mutex. */
464
+
465
+ /* This file only initializes the embedded module once, the first
466
+ time this is called, even if there are subinterpreters. */
467
+ if (!called) {
468
+ called = 1; /* invoke _cffi_initialize_python() only once,
469
+ but don't set '_cffi_call_python' right now,
470
+ otherwise concurrent threads won't call
471
+ this function at all (we need them to wait) */
472
+ if (_cffi_initialize_python() == 0) {
473
+ /* now initialization is finished. Switch to the fast-path. */
474
+
475
+ /* We would like nobody to see the new value of
476
+ '_cffi_call_python' without also seeing the rest of the
477
+ data initialized. However, this is not possible. But
478
+ the new value of '_cffi_call_python' is the function
479
+ 'cffi_call_python()' from _cffi_backend. So: */
480
+ cffi_write_barrier();
481
+ /* ^^^ we put a write barrier here, and a corresponding
482
+ read barrier at the start of cffi_call_python(). This
483
+ ensures that after that read barrier, we see everything
484
+ done here before the write barrier.
485
+ */
486
+
487
+ assert(_cffi_call_python_org != NULL);
488
+ _cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org;
489
+ }
490
+ else {
491
+ /* initialization failed. Reset this to NULL, even if it was
492
+ already set to some other value. Future calls to
493
+ _cffi_start_python() are still forced to occur, and will
494
+ always return NULL from now on. */
495
+ _cffi_call_python_org = NULL;
496
+ }
497
+ }
498
+
499
+ _cffi_release_reentrant_mutex();
500
+
501
+ return (_cffi_call_python_fnptr)_cffi_call_python_org;
502
+ }
503
+
504
+ static
505
+ void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args)
506
+ {
507
+ _cffi_call_python_fnptr fnptr;
508
+ int current_err = errno;
509
+ #ifdef _MSC_VER
510
+ int current_lasterr = GetLastError();
511
+ #endif
512
+ fnptr = _cffi_start_python();
513
+ if (fnptr == NULL) {
514
+ fprintf(stderr, "function %s() called, but initialization code "
515
+ "failed. Returning 0.\n", externpy->name);
516
+ memset(args, 0, externpy->size_of_result);
517
+ }
518
+ #ifdef _MSC_VER
519
+ SetLastError(current_lasterr);
520
+ #endif
521
+ errno = current_err;
522
+
523
+ if (fnptr != NULL)
524
+ fnptr(externpy, args);
525
+ }
526
+
527
+
528
+ /* The cffi_start_python() function makes sure Python is initialized
529
+ and our cffi module is set up. It can be called manually from the
530
+ user C code. The same effect is obtained automatically from any
531
+ dll-exported ``extern "Python"`` function. This function returns
532
+ -1 if initialization failed, 0 if all is OK. */
533
+ _CFFI_UNUSED_FN
534
+ static int cffi_start_python(void)
535
+ {
536
+ if (_cffi_call_python == &_cffi_start_and_call_python) {
537
+ if (_cffi_start_python() == NULL)
538
+ return -1;
539
+ }
540
+ cffi_read_barrier();
541
+ return 0;
542
+ }
543
+
544
+ #undef cffi_compare_and_swap
545
+ #undef cffi_write_barrier
546
+ #undef cffi_read_barrier
547
+
548
+ #ifdef __cplusplus
549
+ }
550
+ #endif
python_embeded/Lib/site-packages/cffi/_imp_emulation.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ try:
3
+ # this works on Python < 3.12
4
+ from imp import *
5
+
6
+ except ImportError:
7
+ # this is a limited emulation for Python >= 3.12.
8
+ # Note that this is used only for tests or for the old ffi.verify().
9
+ # This is copied from the source code of Python 3.11.
10
+
11
+ from _imp import (acquire_lock, release_lock,
12
+ is_builtin, is_frozen)
13
+
14
+ from importlib._bootstrap import _load
15
+
16
+ from importlib import machinery
17
+ import os
18
+ import sys
19
+ import tokenize
20
+
21
+ SEARCH_ERROR = 0
22
+ PY_SOURCE = 1
23
+ PY_COMPILED = 2
24
+ C_EXTENSION = 3
25
+ PY_RESOURCE = 4
26
+ PKG_DIRECTORY = 5
27
+ C_BUILTIN = 6
28
+ PY_FROZEN = 7
29
+ PY_CODERESOURCE = 8
30
+ IMP_HOOK = 9
31
+
32
+ def get_suffixes():
33
+ extensions = [(s, 'rb', C_EXTENSION)
34
+ for s in machinery.EXTENSION_SUFFIXES]
35
+ source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
36
+ bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
37
+ return extensions + source + bytecode
38
+
39
+ def find_module(name, path=None):
40
+ if not isinstance(name, str):
41
+ raise TypeError("'name' must be a str, not {}".format(type(name)))
42
+ elif not isinstance(path, (type(None), list)):
43
+ # Backwards-compatibility
44
+ raise RuntimeError("'path' must be None or a list, "
45
+ "not {}".format(type(path)))
46
+
47
+ if path is None:
48
+ if is_builtin(name):
49
+ return None, None, ('', '', C_BUILTIN)
50
+ elif is_frozen(name):
51
+ return None, None, ('', '', PY_FROZEN)
52
+ else:
53
+ path = sys.path
54
+
55
+ for entry in path:
56
+ package_directory = os.path.join(entry, name)
57
+ for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
58
+ package_file_name = '__init__' + suffix
59
+ file_path = os.path.join(package_directory, package_file_name)
60
+ if os.path.isfile(file_path):
61
+ return None, package_directory, ('', '', PKG_DIRECTORY)
62
+ for suffix, mode, type_ in get_suffixes():
63
+ file_name = name + suffix
64
+ file_path = os.path.join(entry, file_name)
65
+ if os.path.isfile(file_path):
66
+ break
67
+ else:
68
+ continue
69
+ break # Break out of outer loop when breaking out of inner loop.
70
+ else:
71
+ raise ImportError(name, name=name)
72
+
73
+ encoding = None
74
+ if 'b' not in mode:
75
+ with open(file_path, 'rb') as file:
76
+ encoding = tokenize.detect_encoding(file.readline)[0]
77
+ file = open(file_path, mode, encoding=encoding)
78
+ return file, file_path, (suffix, mode, type_)
79
+
80
+ def load_dynamic(name, path, file=None):
81
+ loader = machinery.ExtensionFileLoader(name, path)
82
+ spec = machinery.ModuleSpec(name=name, loader=loader, origin=path)
83
+ return _load(spec)
python_embeded/Lib/site-packages/cffi/_shimmed_dist_utils.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful
3
+ error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken.
4
+
5
+ This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI.
6
+ """
7
+ import sys
8
+
9
+ try:
10
+ # import setuptools first; this is the most robust way to ensure its embedded distutils is available
11
+ # (the .pth shim should usually work, but this is even more robust)
12
+ import setuptools
13
+ except Exception as ex:
14
+ if sys.version_info >= (3, 12):
15
+ # Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal
16
+ raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex
17
+
18
+ # silently ignore on older Pythons (support fallback to stdlib distutils where available)
19
+ else:
20
+ del setuptools
21
+
22
+ try:
23
+ # bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils
24
+ from distutils import log, sysconfig
25
+ from distutils.ccompiler import CCompiler
26
+ from distutils.command.build_ext import build_ext
27
+ from distutils.core import Distribution, Extension
28
+ from distutils.dir_util import mkpath
29
+ from distutils.errors import DistutilsSetupError, CompileError, LinkError
30
+ from distutils.log import set_threshold, set_verbosity
31
+
32
+ if sys.platform == 'win32':
33
+ try:
34
+ # FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler`
35
+ from distutils.msvc9compiler import MSVCCompiler
36
+ except ImportError:
37
+ MSVCCompiler = None
38
+ except Exception as ex:
39
+ if sys.version_info >= (3, 12):
40
+ raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex
41
+
42
+ # anything older, just let the underlying distutils import error fly
43
+ raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex
44
+
45
+ del sys
python_embeded/Lib/site-packages/cffi/api.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, types
2
+ from .lock import allocate_lock
3
+ from .error import CDefError
4
+ from . import model
5
+
6
+ try:
7
+ callable
8
+ except NameError:
9
+ # Python 3.1
10
+ from collections import Callable
11
+ callable = lambda x: isinstance(x, Callable)
12
+
13
+ try:
14
+ basestring
15
+ except NameError:
16
+ # Python 3.x
17
+ basestring = str
18
+
19
+ _unspecified = object()
20
+
21
+
22
+
23
+ class FFI(object):
24
+ r'''
25
+ The main top-level class that you instantiate once, or once per module.
26
+
27
+ Example usage:
28
+
29
+ ffi = FFI()
30
+ ffi.cdef("""
31
+ int printf(const char *, ...);
32
+ """)
33
+
34
+ C = ffi.dlopen(None) # standard library
35
+ -or-
36
+ C = ffi.verify() # use a C compiler: verify the decl above is right
37
+
38
+ C.printf("hello, %s!\n", ffi.new("char[]", "world"))
39
+ '''
40
+
41
+ def __init__(self, backend=None):
42
+ """Create an FFI instance. The 'backend' argument is used to
43
+ select a non-default backend, mostly for tests.
44
+ """
45
+ if backend is None:
46
+ # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
47
+ # _cffi_backend.so compiled.
48
+ import _cffi_backend as backend
49
+ from . import __version__
50
+ if backend.__version__ != __version__:
51
+ # bad version! Try to be as explicit as possible.
52
+ if hasattr(backend, '__file__'):
53
+ # CPython
54
+ raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % (
55
+ __version__, __file__,
56
+ backend.__version__, backend.__file__))
57
+ else:
58
+ # PyPy
59
+ raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % (
60
+ __version__, __file__, backend.__version__))
61
+ # (If you insist you can also try to pass the option
62
+ # 'backend=backend_ctypes.CTypesBackend()', but don't
63
+ # rely on it! It's probably not going to work well.)
64
+
65
+ from . import cparser
66
+ self._backend = backend
67
+ self._lock = allocate_lock()
68
+ self._parser = cparser.Parser()
69
+ self._cached_btypes = {}
70
+ self._parsed_types = types.ModuleType('parsed_types').__dict__
71
+ self._new_types = types.ModuleType('new_types').__dict__
72
+ self._function_caches = []
73
+ self._libraries = []
74
+ self._cdefsources = []
75
+ self._included_ffis = []
76
+ self._windows_unicode = None
77
+ self._init_once_cache = {}
78
+ self._cdef_version = None
79
+ self._embedding = None
80
+ self._typecache = model.get_typecache(backend)
81
+ if hasattr(backend, 'set_ffi'):
82
+ backend.set_ffi(self)
83
+ for name in list(backend.__dict__):
84
+ if name.startswith('RTLD_'):
85
+ setattr(self, name, getattr(backend, name))
86
+ #
87
+ with self._lock:
88
+ self.BVoidP = self._get_cached_btype(model.voidp_type)
89
+ self.BCharA = self._get_cached_btype(model.char_array_type)
90
+ if isinstance(backend, types.ModuleType):
91
+ # _cffi_backend: attach these constants to the class
92
+ if not hasattr(FFI, 'NULL'):
93
+ FFI.NULL = self.cast(self.BVoidP, 0)
94
+ FFI.CData, FFI.CType = backend._get_types()
95
+ else:
96
+ # ctypes backend: attach these constants to the instance
97
+ self.NULL = self.cast(self.BVoidP, 0)
98
+ self.CData, self.CType = backend._get_types()
99
+ self.buffer = backend.buffer
100
+
101
+ def cdef(self, csource, override=False, packed=False, pack=None):
102
+ """Parse the given C source. This registers all declared functions,
103
+ types, and global variables. The functions and global variables can
104
+ then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'.
105
+ The types can be used in 'ffi.new()' and other functions.
106
+ If 'packed' is specified as True, all structs declared inside this
107
+ cdef are packed, i.e. laid out without any field alignment at all.
108
+ Alternatively, 'pack' can be a small integer, and requests for
109
+ alignment greater than that are ignored (pack=1 is equivalent to
110
+ packed=True).
111
+ """
112
+ self._cdef(csource, override=override, packed=packed, pack=pack)
113
+
114
+ def embedding_api(self, csource, packed=False, pack=None):
115
+ self._cdef(csource, packed=packed, pack=pack, dllexport=True)
116
+ if self._embedding is None:
117
+ self._embedding = ''
118
+
119
+ def _cdef(self, csource, override=False, **options):
120
+ if not isinstance(csource, str): # unicode, on Python 2
121
+ if not isinstance(csource, basestring):
122
+ raise TypeError("cdef() argument must be a string")
123
+ csource = csource.encode('ascii')
124
+ with self._lock:
125
+ self._cdef_version = object()
126
+ self._parser.parse(csource, override=override, **options)
127
+ self._cdefsources.append(csource)
128
+ if override:
129
+ for cache in self._function_caches:
130
+ cache.clear()
131
+ finishlist = self._parser._recomplete
132
+ if finishlist:
133
+ self._parser._recomplete = []
134
+ for tp in finishlist:
135
+ tp.finish_backend_type(self, finishlist)
136
+
137
+ def dlopen(self, name, flags=0):
138
+ """Load and return a dynamic library identified by 'name'.
139
+ The standard C library can be loaded by passing None.
140
+ Note that functions and types declared by 'ffi.cdef()' are not
141
+ linked to a particular library, just like C headers; in the
142
+ library we only look for the actual (untyped) symbols.
143
+ """
144
+ if not (isinstance(name, basestring) or
145
+ name is None or
146
+ isinstance(name, self.CData)):
147
+ raise TypeError("dlopen(name): name must be a file name, None, "
148
+ "or an already-opened 'void *' handle")
149
+ with self._lock:
150
+ lib, function_cache = _make_ffi_library(self, name, flags)
151
+ self._function_caches.append(function_cache)
152
+ self._libraries.append(lib)
153
+ return lib
154
+
155
+ def dlclose(self, lib):
156
+ """Close a library obtained with ffi.dlopen(). After this call,
157
+ access to functions or variables from the library will fail
158
+ (possibly with a segmentation fault).
159
+ """
160
+ type(lib).__cffi_close__(lib)
161
+
162
+ def _typeof_locked(self, cdecl):
163
+ # call me with the lock!
164
+ key = cdecl
165
+ if key in self._parsed_types:
166
+ return self._parsed_types[key]
167
+ #
168
+ if not isinstance(cdecl, str): # unicode, on Python 2
169
+ cdecl = cdecl.encode('ascii')
170
+ #
171
+ type = self._parser.parse_type(cdecl)
172
+ really_a_function_type = type.is_raw_function
173
+ if really_a_function_type:
174
+ type = type.as_function_pointer()
175
+ btype = self._get_cached_btype(type)
176
+ result = btype, really_a_function_type
177
+ self._parsed_types[key] = result
178
+ return result
179
+
180
+ def _typeof(self, cdecl, consider_function_as_funcptr=False):
181
+ # string -> ctype object
182
+ try:
183
+ result = self._parsed_types[cdecl]
184
+ except KeyError:
185
+ with self._lock:
186
+ result = self._typeof_locked(cdecl)
187
+ #
188
+ btype, really_a_function_type = result
189
+ if really_a_function_type and not consider_function_as_funcptr:
190
+ raise CDefError("the type %r is a function type, not a "
191
+ "pointer-to-function type" % (cdecl,))
192
+ return btype
193
+
194
+ def typeof(self, cdecl):
195
+ """Parse the C type given as a string and return the
196
+ corresponding <ctype> object.
197
+ It can also be used on 'cdata' instance to get its C type.
198
+ """
199
+ if isinstance(cdecl, basestring):
200
+ return self._typeof(cdecl)
201
+ if isinstance(cdecl, self.CData):
202
+ return self._backend.typeof(cdecl)
203
+ if isinstance(cdecl, types.BuiltinFunctionType):
204
+ res = _builtin_function_type(cdecl)
205
+ if res is not None:
206
+ return res
207
+ if (isinstance(cdecl, types.FunctionType)
208
+ and hasattr(cdecl, '_cffi_base_type')):
209
+ with self._lock:
210
+ return self._get_cached_btype(cdecl._cffi_base_type)
211
+ raise TypeError(type(cdecl))
212
+
213
+ def sizeof(self, cdecl):
214
+ """Return the size in bytes of the argument. It can be a
215
+ string naming a C type, or a 'cdata' instance.
216
+ """
217
+ if isinstance(cdecl, basestring):
218
+ BType = self._typeof(cdecl)
219
+ return self._backend.sizeof(BType)
220
+ else:
221
+ return self._backend.sizeof(cdecl)
222
+
223
+ def alignof(self, cdecl):
224
+ """Return the natural alignment size in bytes of the C type
225
+ given as a string.
226
+ """
227
+ if isinstance(cdecl, basestring):
228
+ cdecl = self._typeof(cdecl)
229
+ return self._backend.alignof(cdecl)
230
+
231
+ def offsetof(self, cdecl, *fields_or_indexes):
232
+ """Return the offset of the named field inside the given
233
+ structure or array, which must be given as a C type name.
234
+ You can give several field names in case of nested structures.
235
+ You can also give numeric values which correspond to array
236
+ items, in case of an array type.
237
+ """
238
+ if isinstance(cdecl, basestring):
239
+ cdecl = self._typeof(cdecl)
240
+ return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
241
+
242
+ def new(self, cdecl, init=None):
243
+ """Allocate an instance according to the specified C type and
244
+ return a pointer to it. The specified C type must be either a
245
+ pointer or an array: ``new('X *')`` allocates an X and returns
246
+ a pointer to it, whereas ``new('X[n]')`` allocates an array of
247
+ n X'es and returns an array referencing it (which works
248
+ mostly like a pointer, like in C). You can also use
249
+ ``new('X[]', n)`` to allocate an array of a non-constant
250
+ length n.
251
+
252
+ The memory is initialized following the rules of declaring a
253
+ global variable in C: by default it is zero-initialized, but
254
+ an explicit initializer can be given which can be used to
255
+ fill all or part of the memory.
256
+
257
+ When the returned <cdata> object goes out of scope, the memory
258
+ is freed. In other words the returned <cdata> object has
259
+ ownership of the value of type 'cdecl' that it points to. This
260
+ means that the raw data can be used as long as this object is
261
+ kept alive, but must not be used for a longer time. Be careful
262
+ about that when copying the pointer to the memory somewhere
263
+ else, e.g. into another structure.
264
+ """
265
+ if isinstance(cdecl, basestring):
266
+ cdecl = self._typeof(cdecl)
267
+ return self._backend.newp(cdecl, init)
268
+
269
+ def new_allocator(self, alloc=None, free=None,
270
+ should_clear_after_alloc=True):
271
+ """Return a new allocator, i.e. a function that behaves like ffi.new()
272
+ but uses the provided low-level 'alloc' and 'free' functions.
273
+
274
+ 'alloc' is called with the size as argument. If it returns NULL, a
275
+ MemoryError is raised. 'free' is called with the result of 'alloc'
276
+ as argument. Both can be either Python function or directly C
277
+ functions. If 'free' is None, then no free function is called.
278
+ If both 'alloc' and 'free' are None, the default is used.
279
+
280
+ If 'should_clear_after_alloc' is set to False, then the memory
281
+ returned by 'alloc' is assumed to be already cleared (or you are
282
+ fine with garbage); otherwise CFFI will clear it.
283
+ """
284
+ compiled_ffi = self._backend.FFI()
285
+ allocator = compiled_ffi.new_allocator(alloc, free,
286
+ should_clear_after_alloc)
287
+ def allocate(cdecl, init=None):
288
+ if isinstance(cdecl, basestring):
289
+ cdecl = self._typeof(cdecl)
290
+ return allocator(cdecl, init)
291
+ return allocate
292
+
293
+ def cast(self, cdecl, source):
294
+ """Similar to a C cast: returns an instance of the named C
295
+ type initialized with the given 'source'. The source is
296
+ casted between integers or pointers of any type.
297
+ """
298
+ if isinstance(cdecl, basestring):
299
+ cdecl = self._typeof(cdecl)
300
+ return self._backend.cast(cdecl, source)
301
+
302
+ def string(self, cdata, maxlen=-1):
303
+ """Return a Python string (or unicode string) from the 'cdata'.
304
+ If 'cdata' is a pointer or array of characters or bytes, returns
305
+ the null-terminated string. The returned string extends until
306
+ the first null character, or at most 'maxlen' characters. If
307
+ 'cdata' is an array then 'maxlen' defaults to its length.
308
+
309
+ If 'cdata' is a pointer or array of wchar_t, returns a unicode
310
+ string following the same rules.
311
+
312
+ If 'cdata' is a single character or byte or a wchar_t, returns
313
+ it as a string or unicode string.
314
+
315
+ If 'cdata' is an enum, returns the value of the enumerator as a
316
+ string, or 'NUMBER' if the value is out of range.
317
+ """
318
+ return self._backend.string(cdata, maxlen)
319
+
320
+ def unpack(self, cdata, length):
321
+ """Unpack an array of C data of the given length,
322
+ returning a Python string/unicode/list.
323
+
324
+ If 'cdata' is a pointer to 'char', returns a byte string.
325
+ It does not stop at the first null. This is equivalent to:
326
+ ffi.buffer(cdata, length)[:]
327
+
328
+ If 'cdata' is a pointer to 'wchar_t', returns a unicode string.
329
+ 'length' is measured in wchar_t's; it is not the size in bytes.
330
+
331
+ If 'cdata' is a pointer to anything else, returns a list of
332
+ 'length' items. This is a faster equivalent to:
333
+ [cdata[i] for i in range(length)]
334
+ """
335
+ return self._backend.unpack(cdata, length)
336
+
337
+ #def buffer(self, cdata, size=-1):
338
+ # """Return a read-write buffer object that references the raw C data
339
+ # pointed to by the given 'cdata'. The 'cdata' must be a pointer or
340
+ # an array. Can be passed to functions expecting a buffer, or directly
341
+ # manipulated with:
342
+ #
343
+ # buf[:] get a copy of it in a regular string, or
344
+ # buf[idx] as a single character
345
+ # buf[:] = ...
346
+ # buf[idx] = ... change the content
347
+ # """
348
+ # note that 'buffer' is a type, set on this instance by __init__
349
+
350
+ def from_buffer(self, cdecl, python_buffer=_unspecified,
351
+ require_writable=False):
352
+ """Return a cdata of the given type pointing to the data of the
353
+ given Python object, which must support the buffer interface.
354
+ Note that this is not meant to be used on the built-in types
355
+ str or unicode (you can build 'char[]' arrays explicitly)
356
+ but only on objects containing large quantities of raw data
357
+ in some other format, like 'array.array' or numpy arrays.
358
+
359
+ The first argument is optional and default to 'char[]'.
360
+ """
361
+ if python_buffer is _unspecified:
362
+ cdecl, python_buffer = self.BCharA, cdecl
363
+ elif isinstance(cdecl, basestring):
364
+ cdecl = self._typeof(cdecl)
365
+ return self._backend.from_buffer(cdecl, python_buffer,
366
+ require_writable)
367
+
368
+ def memmove(self, dest, src, n):
369
+ """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest.
370
+
371
+ Like the C function memmove(), the memory areas may overlap;
372
+ apart from that it behaves like the C function memcpy().
373
+
374
+ 'src' can be any cdata ptr or array, or any Python buffer object.
375
+ 'dest' can be any cdata ptr or array, or a writable Python buffer
376
+ object. The size to copy, 'n', is always measured in bytes.
377
+
378
+ Unlike other methods, this one supports all Python buffer including
379
+ byte strings and bytearrays---but it still does not support
380
+ non-contiguous buffers.
381
+ """
382
+ return self._backend.memmove(dest, src, n)
383
+
384
+ def callback(self, cdecl, python_callable=None, error=None, onerror=None):
385
+ """Return a callback object or a decorator making such a
386
+ callback object. 'cdecl' must name a C function pointer type.
387
+ The callback invokes the specified 'python_callable' (which may
388
+ be provided either directly or via a decorator). Important: the
389
+ callback object must be manually kept alive for as long as the
390
+ callback may be invoked from the C level.
391
+ """
392
+ def callback_decorator_wrap(python_callable):
393
+ if not callable(python_callable):
394
+ raise TypeError("the 'python_callable' argument "
395
+ "is not callable")
396
+ return self._backend.callback(cdecl, python_callable,
397
+ error, onerror)
398
+ if isinstance(cdecl, basestring):
399
+ cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
400
+ if python_callable is None:
401
+ return callback_decorator_wrap # decorator mode
402
+ else:
403
+ return callback_decorator_wrap(python_callable) # direct mode
404
+
405
+ def getctype(self, cdecl, replace_with=''):
406
+ """Return a string giving the C type 'cdecl', which may be itself
407
+ a string or a <ctype> object. If 'replace_with' is given, it gives
408
+ extra text to append (or insert for more complicated C types), like
409
+ a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
410
+ """
411
+ if isinstance(cdecl, basestring):
412
+ cdecl = self._typeof(cdecl)
413
+ replace_with = replace_with.strip()
414
+ if (replace_with.startswith('*')
415
+ and '&[' in self._backend.getcname(cdecl, '&')):
416
+ replace_with = '(%s)' % replace_with
417
+ elif replace_with and not replace_with[0] in '[(':
418
+ replace_with = ' ' + replace_with
419
+ return self._backend.getcname(cdecl, replace_with)
420
+
421
+ def gc(self, cdata, destructor, size=0):
422
+ """Return a new cdata object that points to the same
423
+ data. Later, when this new cdata object is garbage-collected,
424
+ 'destructor(old_cdata_object)' will be called.
425
+
426
+ The optional 'size' gives an estimate of the size, used to
427
+ trigger the garbage collection more eagerly. So far only used
428
+ on PyPy. It tells the GC that the returned object keeps alive
429
+ roughly 'size' bytes of external memory.
430
+ """
431
+ return self._backend.gcp(cdata, destructor, size)
432
+
433
+ def _get_cached_btype(self, type):
434
+ assert self._lock.acquire(False) is False
435
+ # call me with the lock!
436
+ try:
437
+ BType = self._cached_btypes[type]
438
+ except KeyError:
439
+ finishlist = []
440
+ BType = type.get_cached_btype(self, finishlist)
441
+ for type in finishlist:
442
+ type.finish_backend_type(self, finishlist)
443
+ return BType
444
+
445
+ def verify(self, source='', tmpdir=None, **kwargs):
446
+ """Verify that the current ffi signatures compile on this
447
+ machine, and return a dynamic library object. The dynamic
448
+ library can be used to call functions and access global
449
+ variables declared in this 'ffi'. The library is compiled
450
+ by the C compiler: it gives you C-level API compatibility
451
+ (including calling macros). This is unlike 'ffi.dlopen()',
452
+ which requires binary compatibility in the signatures.
453
+ """
454
+ from .verifier import Verifier, _caller_dir_pycache
455
+ #
456
+ # If set_unicode(True) was called, insert the UNICODE and
457
+ # _UNICODE macro declarations
458
+ if self._windows_unicode:
459
+ self._apply_windows_unicode(kwargs)
460
+ #
461
+ # Set the tmpdir here, and not in Verifier.__init__: it picks
462
+ # up the caller's directory, which we want to be the caller of
463
+ # ffi.verify(), as opposed to the caller of Veritier().
464
+ tmpdir = tmpdir or _caller_dir_pycache()
465
+ #
466
+ # Make a Verifier() and use it to load the library.
467
+ self.verifier = Verifier(self, source, tmpdir, **kwargs)
468
+ lib = self.verifier.load_library()
469
+ #
470
+ # Save the loaded library for keep-alive purposes, even
471
+ # if the caller doesn't keep it alive itself (it should).
472
+ self._libraries.append(lib)
473
+ return lib
474
+
475
+ def _get_errno(self):
476
+ return self._backend.get_errno()
477
+ def _set_errno(self, errno):
478
+ self._backend.set_errno(errno)
479
+ errno = property(_get_errno, _set_errno, None,
480
+ "the value of 'errno' from/to the C calls")
481
+
482
+ def getwinerror(self, code=-1):
483
+ return self._backend.getwinerror(code)
484
+
485
+ def _pointer_to(self, ctype):
486
+ with self._lock:
487
+ return model.pointer_cache(self, ctype)
488
+
489
+ def addressof(self, cdata, *fields_or_indexes):
490
+ """Return the address of a <cdata 'struct-or-union'>.
491
+ If 'fields_or_indexes' are given, returns the address of that
492
+ field or array item in the structure or array, recursively in
493
+ case of nested structures.
494
+ """
495
+ try:
496
+ ctype = self._backend.typeof(cdata)
497
+ except TypeError:
498
+ if '__addressof__' in type(cdata).__dict__:
499
+ return type(cdata).__addressof__(cdata, *fields_or_indexes)
500
+ raise
501
+ if fields_or_indexes:
502
+ ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes)
503
+ else:
504
+ if ctype.kind == "pointer":
505
+ raise TypeError("addressof(pointer)")
506
+ offset = 0
507
+ ctypeptr = self._pointer_to(ctype)
508
+ return self._backend.rawaddressof(ctypeptr, cdata, offset)
509
+
510
+ def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes):
511
+ ctype, offset = self._backend.typeoffsetof(ctype, field_or_index)
512
+ for field1 in fields_or_indexes:
513
+ ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1)
514
+ offset += offset1
515
+ return ctype, offset
516
+
517
+ def include(self, ffi_to_include):
518
+ """Includes the typedefs, structs, unions and enums defined
519
+ in another FFI instance. Usage is similar to a #include in C,
520
+ where a part of the program might include types defined in
521
+ another part for its own usage. Note that the include()
522
+ method has no effect on functions, constants and global
523
+ variables, which must anyway be accessed directly from the
524
+ lib object returned by the original FFI instance.
525
+ """
526
+ if not isinstance(ffi_to_include, FFI):
527
+ raise TypeError("ffi.include() expects an argument that is also of"
528
+ " type cffi.FFI, not %r" % (
529
+ type(ffi_to_include).__name__,))
530
+ if ffi_to_include is self:
531
+ raise ValueError("self.include(self)")
532
+ with ffi_to_include._lock:
533
+ with self._lock:
534
+ self._parser.include(ffi_to_include._parser)
535
+ self._cdefsources.append('[')
536
+ self._cdefsources.extend(ffi_to_include._cdefsources)
537
+ self._cdefsources.append(']')
538
+ self._included_ffis.append(ffi_to_include)
539
+
540
+ def new_handle(self, x):
541
+ return self._backend.newp_handle(self.BVoidP, x)
542
+
543
+ def from_handle(self, x):
544
+ return self._backend.from_handle(x)
545
+
546
+ def release(self, x):
547
+ self._backend.release(x)
548
+
549
+ def set_unicode(self, enabled_flag):
550
+ """Windows: if 'enabled_flag' is True, enable the UNICODE and
551
+ _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR
552
+ to be (pointers to) wchar_t. If 'enabled_flag' is False,
553
+ declare these types to be (pointers to) plain 8-bit characters.
554
+ This is mostly for backward compatibility; you usually want True.
555
+ """
556
+ if self._windows_unicode is not None:
557
+ raise ValueError("set_unicode() can only be called once")
558
+ enabled_flag = bool(enabled_flag)
559
+ if enabled_flag:
560
+ self.cdef("typedef wchar_t TBYTE;"
561
+ "typedef wchar_t TCHAR;"
562
+ "typedef const wchar_t *LPCTSTR;"
563
+ "typedef const wchar_t *PCTSTR;"
564
+ "typedef wchar_t *LPTSTR;"
565
+ "typedef wchar_t *PTSTR;"
566
+ "typedef TBYTE *PTBYTE;"
567
+ "typedef TCHAR *PTCHAR;")
568
+ else:
569
+ self.cdef("typedef char TBYTE;"
570
+ "typedef char TCHAR;"
571
+ "typedef const char *LPCTSTR;"
572
+ "typedef const char *PCTSTR;"
573
+ "typedef char *LPTSTR;"
574
+ "typedef char *PTSTR;"
575
+ "typedef TBYTE *PTBYTE;"
576
+ "typedef TCHAR *PTCHAR;")
577
+ self._windows_unicode = enabled_flag
578
+
579
+ def _apply_windows_unicode(self, kwds):
580
+ defmacros = kwds.get('define_macros', ())
581
+ if not isinstance(defmacros, (list, tuple)):
582
+ raise TypeError("'define_macros' must be a list or tuple")
583
+ defmacros = list(defmacros) + [('UNICODE', '1'),
584
+ ('_UNICODE', '1')]
585
+ kwds['define_macros'] = defmacros
586
+
587
+ def _apply_embedding_fix(self, kwds):
588
+ # must include an argument like "-lpython2.7" for the compiler
589
+ def ensure(key, value):
590
+ lst = kwds.setdefault(key, [])
591
+ if value not in lst:
592
+ lst.append(value)
593
+ #
594
+ if '__pypy__' in sys.builtin_module_names:
595
+ import os
596
+ if sys.platform == "win32":
597
+ # we need 'libpypy-c.lib'. Current distributions of
598
+ # pypy (>= 4.1) contain it as 'libs/python27.lib'.
599
+ pythonlib = "python{0[0]}{0[1]}".format(sys.version_info)
600
+ if hasattr(sys, 'prefix'):
601
+ ensure('library_dirs', os.path.join(sys.prefix, 'libs'))
602
+ else:
603
+ # we need 'libpypy-c.{so,dylib}', which should be by
604
+ # default located in 'sys.prefix/bin' for installed
605
+ # systems.
606
+ if sys.version_info < (3,):
607
+ pythonlib = "pypy-c"
608
+ else:
609
+ pythonlib = "pypy3-c"
610
+ if hasattr(sys, 'prefix'):
611
+ ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
612
+ # On uninstalled pypy's, the libpypy-c is typically found in
613
+ # .../pypy/goal/.
614
+ if hasattr(sys, 'prefix'):
615
+ ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal'))
616
+ else:
617
+ if sys.platform == "win32":
618
+ template = "python%d%d"
619
+ if hasattr(sys, 'gettotalrefcount'):
620
+ template += '_d'
621
+ else:
622
+ try:
623
+ import sysconfig
624
+ except ImportError: # 2.6
625
+ from cffi._shimmed_dist_utils import sysconfig
626
+ template = "python%d.%d"
627
+ if sysconfig.get_config_var('DEBUG_EXT'):
628
+ template += sysconfig.get_config_var('DEBUG_EXT')
629
+ pythonlib = (template %
630
+ (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
631
+ if hasattr(sys, 'abiflags'):
632
+ pythonlib += sys.abiflags
633
+ ensure('libraries', pythonlib)
634
+ if sys.platform == "win32":
635
+ ensure('extra_link_args', '/MANIFEST')
636
+
637
+ def set_source(self, module_name, source, source_extension='.c', **kwds):
638
+ import os
639
+ if hasattr(self, '_assigned_source'):
640
+ raise ValueError("set_source() cannot be called several times "
641
+ "per ffi object")
642
+ if not isinstance(module_name, basestring):
643
+ raise TypeError("'module_name' must be a string")
644
+ if os.sep in module_name or (os.altsep and os.altsep in module_name):
645
+ raise ValueError("'module_name' must not contain '/': use a dotted "
646
+ "name to make a 'package.module' location")
647
+ self._assigned_source = (str(module_name), source,
648
+ source_extension, kwds)
649
+
650
+ def set_source_pkgconfig(self, module_name, pkgconfig_libs, source,
651
+ source_extension='.c', **kwds):
652
+ from . import pkgconfig
653
+ if not isinstance(pkgconfig_libs, list):
654
+ raise TypeError("the pkgconfig_libs argument must be a list "
655
+ "of package names")
656
+ kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs)
657
+ pkgconfig.merge_flags(kwds, kwds2)
658
+ self.set_source(module_name, source, source_extension, **kwds)
659
+
660
+ def distutils_extension(self, tmpdir='build', verbose=True):
661
+ from cffi._shimmed_dist_utils import mkpath
662
+ from .recompiler import recompile
663
+ #
664
+ if not hasattr(self, '_assigned_source'):
665
+ if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored
666
+ return self.verifier.get_extension()
667
+ raise ValueError("set_source() must be called before"
668
+ " distutils_extension()")
669
+ module_name, source, source_extension, kwds = self._assigned_source
670
+ if source is None:
671
+ raise TypeError("distutils_extension() is only for C extension "
672
+ "modules, not for dlopen()-style pure Python "
673
+ "modules")
674
+ mkpath(tmpdir)
675
+ ext, updated = recompile(self, module_name,
676
+ source, tmpdir=tmpdir, extradir=tmpdir,
677
+ source_extension=source_extension,
678
+ call_c_compiler=False, **kwds)
679
+ if verbose:
680
+ if updated:
681
+ sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
682
+ else:
683
+ sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
684
+ return ext
685
+
686
+ def emit_c_code(self, filename):
687
+ from .recompiler import recompile
688
+ #
689
+ if not hasattr(self, '_assigned_source'):
690
+ raise ValueError("set_source() must be called before emit_c_code()")
691
+ module_name, source, source_extension, kwds = self._assigned_source
692
+ if source is None:
693
+ raise TypeError("emit_c_code() is only for C extension modules, "
694
+ "not for dlopen()-style pure Python modules")
695
+ recompile(self, module_name, source,
696
+ c_file=filename, call_c_compiler=False,
697
+ uses_ffiplatform=False, **kwds)
698
+
699
+ def emit_python_code(self, filename):
700
+ from .recompiler import recompile
701
+ #
702
+ if not hasattr(self, '_assigned_source'):
703
+ raise ValueError("set_source() must be called before emit_c_code()")
704
+ module_name, source, source_extension, kwds = self._assigned_source
705
+ if source is not None:
706
+ raise TypeError("emit_python_code() is only for dlopen()-style "
707
+ "pure Python modules, not for C extension modules")
708
+ recompile(self, module_name, source,
709
+ c_file=filename, call_c_compiler=False,
710
+ uses_ffiplatform=False, **kwds)
711
+
712
+ def compile(self, tmpdir='.', verbose=0, target=None, debug=None):
713
+ """The 'target' argument gives the final file name of the
714
+ compiled DLL. Use '*' to force distutils' choice, suitable for
715
+ regular CPython C API modules. Use a file name ending in '.*'
716
+ to ask for the system's default extension for dynamic libraries
717
+ (.so/.dll/.dylib).
718
+
719
+ The default is '*' when building a non-embedded C API extension,
720
+ and (module_name + '.*') when building an embedded library.
721
+ """
722
+ from .recompiler import recompile
723
+ #
724
+ if not hasattr(self, '_assigned_source'):
725
+ raise ValueError("set_source() must be called before compile()")
726
+ module_name, source, source_extension, kwds = self._assigned_source
727
+ return recompile(self, module_name, source, tmpdir=tmpdir,
728
+ target=target, source_extension=source_extension,
729
+ compiler_verbose=verbose, debug=debug, **kwds)
730
+
731
+ def init_once(self, func, tag):
732
+ # Read _init_once_cache[tag], which is either (False, lock) if
733
+ # we're calling the function now in some thread, or (True, result).
734
+ # Don't call setdefault() in most cases, to avoid allocating and
735
+ # immediately freeing a lock; but still use setdefaut() to avoid
736
+ # races.
737
+ try:
738
+ x = self._init_once_cache[tag]
739
+ except KeyError:
740
+ x = self._init_once_cache.setdefault(tag, (False, allocate_lock()))
741
+ # Common case: we got (True, result), so we return the result.
742
+ if x[0]:
743
+ return x[1]
744
+ # Else, it's a lock. Acquire it to serialize the following tests.
745
+ with x[1]:
746
+ # Read again from _init_once_cache the current status.
747
+ x = self._init_once_cache[tag]
748
+ if x[0]:
749
+ return x[1]
750
+ # Call the function and store the result back.
751
+ result = func()
752
+ self._init_once_cache[tag] = (True, result)
753
+ return result
754
+
755
+ def embedding_init_code(self, pysource):
756
+ if self._embedding:
757
+ raise ValueError("embedding_init_code() can only be called once")
758
+ # fix 'pysource' before it gets dumped into the C file:
759
+ # - remove empty lines at the beginning, so it starts at "line 1"
760
+ # - dedent, if all non-empty lines are indented
761
+ # - check for SyntaxErrors
762
+ import re
763
+ match = re.match(r'\s*\n', pysource)
764
+ if match:
765
+ pysource = pysource[match.end():]
766
+ lines = pysource.splitlines() or ['']
767
+ prefix = re.match(r'\s*', lines[0]).group()
768
+ for i in range(1, len(lines)):
769
+ line = lines[i]
770
+ if line.rstrip():
771
+ while not line.startswith(prefix):
772
+ prefix = prefix[:-1]
773
+ i = len(prefix)
774
+ lines = [line[i:]+'\n' for line in lines]
775
+ pysource = ''.join(lines)
776
+ #
777
+ compile(pysource, "cffi_init", "exec")
778
+ #
779
+ self._embedding = pysource
780
+
781
+ def def_extern(self, *args, **kwds):
782
+ raise ValueError("ffi.def_extern() is only available on API-mode FFI "
783
+ "objects")
784
+
785
+ def list_types(self):
786
+ """Returns the user type names known to this FFI instance.
787
+ This returns a tuple containing three lists of names:
788
+ (typedef_names, names_of_structs, names_of_unions)
789
+ """
790
+ typedefs = []
791
+ structs = []
792
+ unions = []
793
+ for key in self._parser._declarations:
794
+ if key.startswith('typedef '):
795
+ typedefs.append(key[8:])
796
+ elif key.startswith('struct '):
797
+ structs.append(key[7:])
798
+ elif key.startswith('union '):
799
+ unions.append(key[6:])
800
+ typedefs.sort()
801
+ structs.sort()
802
+ unions.sort()
803
+ return (typedefs, structs, unions)
804
+
805
+
806
+ def _load_backend_lib(backend, name, flags):
807
+ import os
808
+ if not isinstance(name, basestring):
809
+ if sys.platform != "win32" or name is not None:
810
+ return backend.load_library(name, flags)
811
+ name = "c" # Windows: load_library(None) fails, but this works
812
+ # on Python 2 (backward compatibility hack only)
813
+ first_error = None
814
+ if '.' in name or '/' in name or os.sep in name:
815
+ try:
816
+ return backend.load_library(name, flags)
817
+ except OSError as e:
818
+ first_error = e
819
+ import ctypes.util
820
+ path = ctypes.util.find_library(name)
821
+ if path is None:
822
+ if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
823
+ raise OSError("dlopen(None) cannot work on Windows for Python 3 "
824
+ "(see http://bugs.python.org/issue23606)")
825
+ msg = ("ctypes.util.find_library() did not manage "
826
+ "to locate a library called %r" % (name,))
827
+ if first_error is not None:
828
+ msg = "%s. Additionally, %s" % (first_error, msg)
829
+ raise OSError(msg)
830
+ return backend.load_library(path, flags)
831
+
832
+ def _make_ffi_library(ffi, libname, flags):
833
+ backend = ffi._backend
834
+ backendlib = _load_backend_lib(backend, libname, flags)
835
+ #
836
+ def accessor_function(name):
837
+ key = 'function ' + name
838
+ tp, _ = ffi._parser._declarations[key]
839
+ BType = ffi._get_cached_btype(tp)
840
+ value = backendlib.load_function(BType, name)
841
+ library.__dict__[name] = value
842
+ #
843
+ def accessor_variable(name):
844
+ key = 'variable ' + name
845
+ tp, _ = ffi._parser._declarations[key]
846
+ BType = ffi._get_cached_btype(tp)
847
+ read_variable = backendlib.read_variable
848
+ write_variable = backendlib.write_variable
849
+ setattr(FFILibrary, name, property(
850
+ lambda self: read_variable(BType, name),
851
+ lambda self, value: write_variable(BType, name, value)))
852
+ #
853
+ def addressof_var(name):
854
+ try:
855
+ return addr_variables[name]
856
+ except KeyError:
857
+ with ffi._lock:
858
+ if name not in addr_variables:
859
+ key = 'variable ' + name
860
+ tp, _ = ffi._parser._declarations[key]
861
+ BType = ffi._get_cached_btype(tp)
862
+ if BType.kind != 'array':
863
+ BType = model.pointer_cache(ffi, BType)
864
+ p = backendlib.load_function(BType, name)
865
+ addr_variables[name] = p
866
+ return addr_variables[name]
867
+ #
868
+ def accessor_constant(name):
869
+ raise NotImplementedError("non-integer constant '%s' cannot be "
870
+ "accessed from a dlopen() library" % (name,))
871
+ #
872
+ def accessor_int_constant(name):
873
+ library.__dict__[name] = ffi._parser._int_constants[name]
874
+ #
875
+ accessors = {}
876
+ accessors_version = [False]
877
+ addr_variables = {}
878
+ #
879
+ def update_accessors():
880
+ if accessors_version[0] is ffi._cdef_version:
881
+ return
882
+ #
883
+ for key, (tp, _) in ffi._parser._declarations.items():
884
+ if not isinstance(tp, model.EnumType):
885
+ tag, name = key.split(' ', 1)
886
+ if tag == 'function':
887
+ accessors[name] = accessor_function
888
+ elif tag == 'variable':
889
+ accessors[name] = accessor_variable
890
+ elif tag == 'constant':
891
+ accessors[name] = accessor_constant
892
+ else:
893
+ for i, enumname in enumerate(tp.enumerators):
894
+ def accessor_enum(name, tp=tp, i=i):
895
+ tp.check_not_partial()
896
+ library.__dict__[name] = tp.enumvalues[i]
897
+ accessors[enumname] = accessor_enum
898
+ for name in ffi._parser._int_constants:
899
+ accessors.setdefault(name, accessor_int_constant)
900
+ accessors_version[0] = ffi._cdef_version
901
+ #
902
+ def make_accessor(name):
903
+ with ffi._lock:
904
+ if name in library.__dict__ or name in FFILibrary.__dict__:
905
+ return # added by another thread while waiting for the lock
906
+ if name not in accessors:
907
+ update_accessors()
908
+ if name not in accessors:
909
+ raise AttributeError(name)
910
+ accessors[name](name)
911
+ #
912
+ class FFILibrary(object):
913
+ def __getattr__(self, name):
914
+ make_accessor(name)
915
+ return getattr(self, name)
916
+ def __setattr__(self, name, value):
917
+ try:
918
+ property = getattr(self.__class__, name)
919
+ except AttributeError:
920
+ make_accessor(name)
921
+ setattr(self, name, value)
922
+ else:
923
+ property.__set__(self, value)
924
+ def __dir__(self):
925
+ with ffi._lock:
926
+ update_accessors()
927
+ return accessors.keys()
928
+ def __addressof__(self, name):
929
+ if name in library.__dict__:
930
+ return library.__dict__[name]
931
+ if name in FFILibrary.__dict__:
932
+ return addressof_var(name)
933
+ make_accessor(name)
934
+ if name in library.__dict__:
935
+ return library.__dict__[name]
936
+ if name in FFILibrary.__dict__:
937
+ return addressof_var(name)
938
+ raise AttributeError("cffi library has no function or "
939
+ "global variable named '%s'" % (name,))
940
+ def __cffi_close__(self):
941
+ backendlib.close_lib()
942
+ self.__dict__.clear()
943
+ #
944
+ if isinstance(libname, basestring):
945
+ try:
946
+ if not isinstance(libname, str): # unicode, on Python 2
947
+ libname = libname.encode('utf-8')
948
+ FFILibrary.__name__ = 'FFILibrary_%s' % libname
949
+ except UnicodeError:
950
+ pass
951
+ library = FFILibrary()
952
+ return library, library.__dict__
953
+
954
+ def _builtin_function_type(func):
955
+ # a hack to make at least ffi.typeof(builtin_function) work,
956
+ # if the builtin function was obtained by 'vengine_cpy'.
957
+ import sys
958
+ try:
959
+ module = sys.modules[func.__module__]
960
+ ffi = module._cffi_original_ffi
961
+ types_of_builtin_funcs = module._cffi_types_of_builtin_funcs
962
+ tp = types_of_builtin_funcs[func]
963
+ except (KeyError, AttributeError, TypeError):
964
+ return None
965
+ else:
966
+ with ffi._lock:
967
+ return ffi._get_cached_btype(tp)
python_embeded/Lib/site-packages/cffi/backend_ctypes.py ADDED
@@ -0,0 +1,1121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes, ctypes.util, operator, sys
2
+ from . import model
3
+
4
+ if sys.version_info < (3,):
5
+ bytechr = chr
6
+ else:
7
+ unicode = str
8
+ long = int
9
+ xrange = range
10
+ bytechr = lambda num: bytes([num])
11
+
12
+ class CTypesType(type):
13
+ pass
14
+
15
+ class CTypesData(object):
16
+ __metaclass__ = CTypesType
17
+ __slots__ = ['__weakref__']
18
+ __name__ = '<cdata>'
19
+
20
+ def __init__(self, *args):
21
+ raise TypeError("cannot instantiate %r" % (self.__class__,))
22
+
23
+ @classmethod
24
+ def _newp(cls, init):
25
+ raise TypeError("expected a pointer or array ctype, got '%s'"
26
+ % (cls._get_c_name(),))
27
+
28
+ @staticmethod
29
+ def _to_ctypes(value):
30
+ raise TypeError
31
+
32
+ @classmethod
33
+ def _arg_to_ctypes(cls, *value):
34
+ try:
35
+ ctype = cls._ctype
36
+ except AttributeError:
37
+ raise TypeError("cannot create an instance of %r" % (cls,))
38
+ if value:
39
+ res = cls._to_ctypes(*value)
40
+ if not isinstance(res, ctype):
41
+ res = cls._ctype(res)
42
+ else:
43
+ res = cls._ctype()
44
+ return res
45
+
46
+ @classmethod
47
+ def _create_ctype_obj(cls, init):
48
+ if init is None:
49
+ return cls._arg_to_ctypes()
50
+ else:
51
+ return cls._arg_to_ctypes(init)
52
+
53
+ @staticmethod
54
+ def _from_ctypes(ctypes_value):
55
+ raise TypeError
56
+
57
+ @classmethod
58
+ def _get_c_name(cls, replace_with=''):
59
+ return cls._reftypename.replace(' &', replace_with)
60
+
61
+ @classmethod
62
+ def _fix_class(cls):
63
+ cls.__name__ = 'CData<%s>' % (cls._get_c_name(),)
64
+ cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),)
65
+ cls.__module__ = 'ffi'
66
+
67
+ def _get_own_repr(self):
68
+ raise NotImplementedError
69
+
70
+ def _addr_repr(self, address):
71
+ if address == 0:
72
+ return 'NULL'
73
+ else:
74
+ if address < 0:
75
+ address += 1 << (8*ctypes.sizeof(ctypes.c_void_p))
76
+ return '0x%x' % address
77
+
78
+ def __repr__(self, c_name=None):
79
+ own = self._get_own_repr()
80
+ return '<cdata %r %s>' % (c_name or self._get_c_name(), own)
81
+
82
+ def _convert_to_address(self, BClass):
83
+ if BClass is None:
84
+ raise TypeError("cannot convert %r to an address" % (
85
+ self._get_c_name(),))
86
+ else:
87
+ raise TypeError("cannot convert %r to %r" % (
88
+ self._get_c_name(), BClass._get_c_name()))
89
+
90
+ @classmethod
91
+ def _get_size(cls):
92
+ return ctypes.sizeof(cls._ctype)
93
+
94
+ def _get_size_of_instance(self):
95
+ return ctypes.sizeof(self._ctype)
96
+
97
+ @classmethod
98
+ def _cast_from(cls, source):
99
+ raise TypeError("cannot cast to %r" % (cls._get_c_name(),))
100
+
101
+ def _cast_to_integer(self):
102
+ return self._convert_to_address(None)
103
+
104
+ @classmethod
105
+ def _alignment(cls):
106
+ return ctypes.alignment(cls._ctype)
107
+
108
+ def __iter__(self):
109
+ raise TypeError("cdata %r does not support iteration" % (
110
+ self._get_c_name()),)
111
+
112
+ def _make_cmp(name):
113
+ cmpfunc = getattr(operator, name)
114
+ def cmp(self, other):
115
+ v_is_ptr = not isinstance(self, CTypesGenericPrimitive)
116
+ w_is_ptr = (isinstance(other, CTypesData) and
117
+ not isinstance(other, CTypesGenericPrimitive))
118
+ if v_is_ptr and w_is_ptr:
119
+ return cmpfunc(self._convert_to_address(None),
120
+ other._convert_to_address(None))
121
+ elif v_is_ptr or w_is_ptr:
122
+ return NotImplemented
123
+ else:
124
+ if isinstance(self, CTypesGenericPrimitive):
125
+ self = self._value
126
+ if isinstance(other, CTypesGenericPrimitive):
127
+ other = other._value
128
+ return cmpfunc(self, other)
129
+ cmp.func_name = name
130
+ return cmp
131
+
132
+ __eq__ = _make_cmp('__eq__')
133
+ __ne__ = _make_cmp('__ne__')
134
+ __lt__ = _make_cmp('__lt__')
135
+ __le__ = _make_cmp('__le__')
136
+ __gt__ = _make_cmp('__gt__')
137
+ __ge__ = _make_cmp('__ge__')
138
+
139
+ def __hash__(self):
140
+ return hash(self._convert_to_address(None))
141
+
142
+ def _to_string(self, maxlen):
143
+ raise TypeError("string(): %r" % (self,))
144
+
145
+
146
+ class CTypesGenericPrimitive(CTypesData):
147
+ __slots__ = []
148
+
149
+ def __hash__(self):
150
+ return hash(self._value)
151
+
152
+ def _get_own_repr(self):
153
+ return repr(self._from_ctypes(self._value))
154
+
155
+
156
+ class CTypesGenericArray(CTypesData):
157
+ __slots__ = []
158
+
159
+ @classmethod
160
+ def _newp(cls, init):
161
+ return cls(init)
162
+
163
+ def __iter__(self):
164
+ for i in xrange(len(self)):
165
+ yield self[i]
166
+
167
+ def _get_own_repr(self):
168
+ return self._addr_repr(ctypes.addressof(self._blob))
169
+
170
+
171
+ class CTypesGenericPtr(CTypesData):
172
+ __slots__ = ['_address', '_as_ctype_ptr']
173
+ _automatic_casts = False
174
+ kind = "pointer"
175
+
176
+ @classmethod
177
+ def _newp(cls, init):
178
+ return cls(init)
179
+
180
+ @classmethod
181
+ def _cast_from(cls, source):
182
+ if source is None:
183
+ address = 0
184
+ elif isinstance(source, CTypesData):
185
+ address = source._cast_to_integer()
186
+ elif isinstance(source, (int, long)):
187
+ address = source
188
+ else:
189
+ raise TypeError("bad type for cast to %r: %r" %
190
+ (cls, type(source).__name__))
191
+ return cls._new_pointer_at(address)
192
+
193
+ @classmethod
194
+ def _new_pointer_at(cls, address):
195
+ self = cls.__new__(cls)
196
+ self._address = address
197
+ self._as_ctype_ptr = ctypes.cast(address, cls._ctype)
198
+ return self
199
+
200
+ def _get_own_repr(self):
201
+ try:
202
+ return self._addr_repr(self._address)
203
+ except AttributeError:
204
+ return '???'
205
+
206
+ def _cast_to_integer(self):
207
+ return self._address
208
+
209
+ def __nonzero__(self):
210
+ return bool(self._address)
211
+ __bool__ = __nonzero__
212
+
213
+ @classmethod
214
+ def _to_ctypes(cls, value):
215
+ if not isinstance(value, CTypesData):
216
+ raise TypeError("unexpected %s object" % type(value).__name__)
217
+ address = value._convert_to_address(cls)
218
+ return ctypes.cast(address, cls._ctype)
219
+
220
+ @classmethod
221
+ def _from_ctypes(cls, ctypes_ptr):
222
+ address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0
223
+ return cls._new_pointer_at(address)
224
+
225
+ @classmethod
226
+ def _initialize(cls, ctypes_ptr, value):
227
+ if value:
228
+ ctypes_ptr.contents = cls._to_ctypes(value).contents
229
+
230
+ def _convert_to_address(self, BClass):
231
+ if (BClass in (self.__class__, None) or BClass._automatic_casts
232
+ or self._automatic_casts):
233
+ return self._address
234
+ else:
235
+ return CTypesData._convert_to_address(self, BClass)
236
+
237
+
238
+ class CTypesBaseStructOrUnion(CTypesData):
239
+ __slots__ = ['_blob']
240
+
241
+ @classmethod
242
+ def _create_ctype_obj(cls, init):
243
+ # may be overridden
244
+ raise TypeError("cannot instantiate opaque type %s" % (cls,))
245
+
246
+ def _get_own_repr(self):
247
+ return self._addr_repr(ctypes.addressof(self._blob))
248
+
249
+ @classmethod
250
+ def _offsetof(cls, fieldname):
251
+ return getattr(cls._ctype, fieldname).offset
252
+
253
+ def _convert_to_address(self, BClass):
254
+ if getattr(BClass, '_BItem', None) is self.__class__:
255
+ return ctypes.addressof(self._blob)
256
+ else:
257
+ return CTypesData._convert_to_address(self, BClass)
258
+
259
+ @classmethod
260
+ def _from_ctypes(cls, ctypes_struct_or_union):
261
+ self = cls.__new__(cls)
262
+ self._blob = ctypes_struct_or_union
263
+ return self
264
+
265
+ @classmethod
266
+ def _to_ctypes(cls, value):
267
+ return value._blob
268
+
269
+ def __repr__(self, c_name=None):
270
+ return CTypesData.__repr__(self, c_name or self._get_c_name(' &'))
271
+
272
+
273
+ class CTypesBackend(object):
274
+
275
+ PRIMITIVE_TYPES = {
276
+ 'char': ctypes.c_char,
277
+ 'short': ctypes.c_short,
278
+ 'int': ctypes.c_int,
279
+ 'long': ctypes.c_long,
280
+ 'long long': ctypes.c_longlong,
281
+ 'signed char': ctypes.c_byte,
282
+ 'unsigned char': ctypes.c_ubyte,
283
+ 'unsigned short': ctypes.c_ushort,
284
+ 'unsigned int': ctypes.c_uint,
285
+ 'unsigned long': ctypes.c_ulong,
286
+ 'unsigned long long': ctypes.c_ulonglong,
287
+ 'float': ctypes.c_float,
288
+ 'double': ctypes.c_double,
289
+ '_Bool': ctypes.c_bool,
290
+ }
291
+
292
+ for _name in ['unsigned long long', 'unsigned long',
293
+ 'unsigned int', 'unsigned short', 'unsigned char']:
294
+ _size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
295
+ PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
296
+ if _size == ctypes.sizeof(ctypes.c_void_p):
297
+ PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name]
298
+ if _size == ctypes.sizeof(ctypes.c_size_t):
299
+ PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name]
300
+
301
+ for _name in ['long long', 'long', 'int', 'short', 'signed char']:
302
+ _size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
303
+ PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
304
+ if _size == ctypes.sizeof(ctypes.c_void_p):
305
+ PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name]
306
+ PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name]
307
+ if _size == ctypes.sizeof(ctypes.c_size_t):
308
+ PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name]
309
+
310
+
311
+ def __init__(self):
312
+ self.RTLD_LAZY = 0 # not supported anyway by ctypes
313
+ self.RTLD_NOW = 0
314
+ self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL
315
+ self.RTLD_LOCAL = ctypes.RTLD_LOCAL
316
+
317
+ def set_ffi(self, ffi):
318
+ self.ffi = ffi
319
+
320
+ def _get_types(self):
321
+ return CTypesData, CTypesType
322
+
323
+ def load_library(self, path, flags=0):
324
+ cdll = ctypes.CDLL(path, flags)
325
+ return CTypesLibrary(self, cdll)
326
+
327
+ def new_void_type(self):
328
+ class CTypesVoid(CTypesData):
329
+ __slots__ = []
330
+ _reftypename = 'void &'
331
+ @staticmethod
332
+ def _from_ctypes(novalue):
333
+ return None
334
+ @staticmethod
335
+ def _to_ctypes(novalue):
336
+ if novalue is not None:
337
+ raise TypeError("None expected, got %s object" %
338
+ (type(novalue).__name__,))
339
+ return None
340
+ CTypesVoid._fix_class()
341
+ return CTypesVoid
342
+
343
+ def new_primitive_type(self, name):
344
+ if name == 'wchar_t':
345
+ raise NotImplementedError(name)
346
+ ctype = self.PRIMITIVE_TYPES[name]
347
+ if name == 'char':
348
+ kind = 'char'
349
+ elif name in ('float', 'double'):
350
+ kind = 'float'
351
+ else:
352
+ if name in ('signed char', 'unsigned char'):
353
+ kind = 'byte'
354
+ elif name == '_Bool':
355
+ kind = 'bool'
356
+ else:
357
+ kind = 'int'
358
+ is_signed = (ctype(-1).value == -1)
359
+ #
360
+ def _cast_source_to_int(source):
361
+ if isinstance(source, (int, long, float)):
362
+ source = int(source)
363
+ elif isinstance(source, CTypesData):
364
+ source = source._cast_to_integer()
365
+ elif isinstance(source, bytes):
366
+ source = ord(source)
367
+ elif source is None:
368
+ source = 0
369
+ else:
370
+ raise TypeError("bad type for cast to %r: %r" %
371
+ (CTypesPrimitive, type(source).__name__))
372
+ return source
373
+ #
374
+ kind1 = kind
375
+ class CTypesPrimitive(CTypesGenericPrimitive):
376
+ __slots__ = ['_value']
377
+ _ctype = ctype
378
+ _reftypename = '%s &' % name
379
+ kind = kind1
380
+
381
+ def __init__(self, value):
382
+ self._value = value
383
+
384
+ @staticmethod
385
+ def _create_ctype_obj(init):
386
+ if init is None:
387
+ return ctype()
388
+ return ctype(CTypesPrimitive._to_ctypes(init))
389
+
390
+ if kind == 'int' or kind == 'byte':
391
+ @classmethod
392
+ def _cast_from(cls, source):
393
+ source = _cast_source_to_int(source)
394
+ source = ctype(source).value # cast within range
395
+ return cls(source)
396
+ def __int__(self):
397
+ return self._value
398
+
399
+ if kind == 'bool':
400
+ @classmethod
401
+ def _cast_from(cls, source):
402
+ if not isinstance(source, (int, long, float)):
403
+ source = _cast_source_to_int(source)
404
+ return cls(bool(source))
405
+ def __int__(self):
406
+ return int(self._value)
407
+
408
+ if kind == 'char':
409
+ @classmethod
410
+ def _cast_from(cls, source):
411
+ source = _cast_source_to_int(source)
412
+ source = bytechr(source & 0xFF)
413
+ return cls(source)
414
+ def __int__(self):
415
+ return ord(self._value)
416
+
417
+ if kind == 'float':
418
+ @classmethod
419
+ def _cast_from(cls, source):
420
+ if isinstance(source, float):
421
+ pass
422
+ elif isinstance(source, CTypesGenericPrimitive):
423
+ if hasattr(source, '__float__'):
424
+ source = float(source)
425
+ else:
426
+ source = int(source)
427
+ else:
428
+ source = _cast_source_to_int(source)
429
+ source = ctype(source).value # fix precision
430
+ return cls(source)
431
+ def __int__(self):
432
+ return int(self._value)
433
+ def __float__(self):
434
+ return self._value
435
+
436
+ _cast_to_integer = __int__
437
+
438
+ if kind == 'int' or kind == 'byte' or kind == 'bool':
439
+ @staticmethod
440
+ def _to_ctypes(x):
441
+ if not isinstance(x, (int, long)):
442
+ if isinstance(x, CTypesData):
443
+ x = int(x)
444
+ else:
445
+ raise TypeError("integer expected, got %s" %
446
+ type(x).__name__)
447
+ if ctype(x).value != x:
448
+ if not is_signed and x < 0:
449
+ raise OverflowError("%s: negative integer" % name)
450
+ else:
451
+ raise OverflowError("%s: integer out of bounds"
452
+ % name)
453
+ return x
454
+
455
+ if kind == 'char':
456
+ @staticmethod
457
+ def _to_ctypes(x):
458
+ if isinstance(x, bytes) and len(x) == 1:
459
+ return x
460
+ if isinstance(x, CTypesPrimitive): # <CData <char>>
461
+ return x._value
462
+ raise TypeError("character expected, got %s" %
463
+ type(x).__name__)
464
+ def __nonzero__(self):
465
+ return ord(self._value) != 0
466
+ else:
467
+ def __nonzero__(self):
468
+ return self._value != 0
469
+ __bool__ = __nonzero__
470
+
471
+ if kind == 'float':
472
+ @staticmethod
473
+ def _to_ctypes(x):
474
+ if not isinstance(x, (int, long, float, CTypesData)):
475
+ raise TypeError("float expected, got %s" %
476
+ type(x).__name__)
477
+ return ctype(x).value
478
+
479
+ @staticmethod
480
+ def _from_ctypes(value):
481
+ return getattr(value, 'value', value)
482
+
483
+ @staticmethod
484
+ def _initialize(blob, init):
485
+ blob.value = CTypesPrimitive._to_ctypes(init)
486
+
487
+ if kind == 'char':
488
+ def _to_string(self, maxlen):
489
+ return self._value
490
+ if kind == 'byte':
491
+ def _to_string(self, maxlen):
492
+ return chr(self._value & 0xff)
493
+ #
494
+ CTypesPrimitive._fix_class()
495
+ return CTypesPrimitive
496
+
497
+ def new_pointer_type(self, BItem):
498
+ getbtype = self.ffi._get_cached_btype
499
+ if BItem is getbtype(model.PrimitiveType('char')):
500
+ kind = 'charp'
501
+ elif BItem in (getbtype(model.PrimitiveType('signed char')),
502
+ getbtype(model.PrimitiveType('unsigned char'))):
503
+ kind = 'bytep'
504
+ elif BItem is getbtype(model.void_type):
505
+ kind = 'voidp'
506
+ else:
507
+ kind = 'generic'
508
+ #
509
+ class CTypesPtr(CTypesGenericPtr):
510
+ __slots__ = ['_own']
511
+ if kind == 'charp':
512
+ __slots__ += ['__as_strbuf']
513
+ _BItem = BItem
514
+ if hasattr(BItem, '_ctype'):
515
+ _ctype = ctypes.POINTER(BItem._ctype)
516
+ _bitem_size = ctypes.sizeof(BItem._ctype)
517
+ else:
518
+ _ctype = ctypes.c_void_p
519
+ if issubclass(BItem, CTypesGenericArray):
520
+ _reftypename = BItem._get_c_name('(* &)')
521
+ else:
522
+ _reftypename = BItem._get_c_name(' * &')
523
+
524
+ def __init__(self, init):
525
+ ctypeobj = BItem._create_ctype_obj(init)
526
+ if kind == 'charp':
527
+ self.__as_strbuf = ctypes.create_string_buffer(
528
+ ctypeobj.value + b'\x00')
529
+ self._as_ctype_ptr = ctypes.cast(
530
+ self.__as_strbuf, self._ctype)
531
+ else:
532
+ self._as_ctype_ptr = ctypes.pointer(ctypeobj)
533
+ self._address = ctypes.cast(self._as_ctype_ptr,
534
+ ctypes.c_void_p).value
535
+ self._own = True
536
+
537
+ def __add__(self, other):
538
+ if isinstance(other, (int, long)):
539
+ return self._new_pointer_at(self._address +
540
+ other * self._bitem_size)
541
+ else:
542
+ return NotImplemented
543
+
544
+ def __sub__(self, other):
545
+ if isinstance(other, (int, long)):
546
+ return self._new_pointer_at(self._address -
547
+ other * self._bitem_size)
548
+ elif type(self) is type(other):
549
+ return (self._address - other._address) // self._bitem_size
550
+ else:
551
+ return NotImplemented
552
+
553
+ def __getitem__(self, index):
554
+ if getattr(self, '_own', False) and index != 0:
555
+ raise IndexError
556
+ return BItem._from_ctypes(self._as_ctype_ptr[index])
557
+
558
+ def __setitem__(self, index, value):
559
+ self._as_ctype_ptr[index] = BItem._to_ctypes(value)
560
+
561
+ if kind == 'charp' or kind == 'voidp':
562
+ @classmethod
563
+ def _arg_to_ctypes(cls, *value):
564
+ if value and isinstance(value[0], bytes):
565
+ return ctypes.c_char_p(value[0])
566
+ else:
567
+ return super(CTypesPtr, cls)._arg_to_ctypes(*value)
568
+
569
+ if kind == 'charp' or kind == 'bytep':
570
+ def _to_string(self, maxlen):
571
+ if maxlen < 0:
572
+ maxlen = sys.maxsize
573
+ p = ctypes.cast(self._as_ctype_ptr,
574
+ ctypes.POINTER(ctypes.c_char))
575
+ n = 0
576
+ while n < maxlen and p[n] != b'\x00':
577
+ n += 1
578
+ return b''.join([p[i] for i in range(n)])
579
+
580
+ def _get_own_repr(self):
581
+ if getattr(self, '_own', False):
582
+ return 'owning %d bytes' % (
583
+ ctypes.sizeof(self._as_ctype_ptr.contents),)
584
+ return super(CTypesPtr, self)._get_own_repr()
585
+ #
586
+ if (BItem is self.ffi._get_cached_btype(model.void_type) or
587
+ BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))):
588
+ CTypesPtr._automatic_casts = True
589
+ #
590
+ CTypesPtr._fix_class()
591
+ return CTypesPtr
592
+
593
+ def new_array_type(self, CTypesPtr, length):
594
+ if length is None:
595
+ brackets = ' &[]'
596
+ else:
597
+ brackets = ' &[%d]' % length
598
+ BItem = CTypesPtr._BItem
599
+ getbtype = self.ffi._get_cached_btype
600
+ if BItem is getbtype(model.PrimitiveType('char')):
601
+ kind = 'char'
602
+ elif BItem in (getbtype(model.PrimitiveType('signed char')),
603
+ getbtype(model.PrimitiveType('unsigned char'))):
604
+ kind = 'byte'
605
+ else:
606
+ kind = 'generic'
607
+ #
608
+ class CTypesArray(CTypesGenericArray):
609
+ __slots__ = ['_blob', '_own']
610
+ if length is not None:
611
+ _ctype = BItem._ctype * length
612
+ else:
613
+ __slots__.append('_ctype')
614
+ _reftypename = BItem._get_c_name(brackets)
615
+ _declared_length = length
616
+ _CTPtr = CTypesPtr
617
+
618
+ def __init__(self, init):
619
+ if length is None:
620
+ if isinstance(init, (int, long)):
621
+ len1 = init
622
+ init = None
623
+ elif kind == 'char' and isinstance(init, bytes):
624
+ len1 = len(init) + 1 # extra null
625
+ else:
626
+ init = tuple(init)
627
+ len1 = len(init)
628
+ self._ctype = BItem._ctype * len1
629
+ self._blob = self._ctype()
630
+ self._own = True
631
+ if init is not None:
632
+ self._initialize(self._blob, init)
633
+
634
+ @staticmethod
635
+ def _initialize(blob, init):
636
+ if isinstance(init, bytes):
637
+ init = [init[i:i+1] for i in range(len(init))]
638
+ else:
639
+ if isinstance(init, CTypesGenericArray):
640
+ if (len(init) != len(blob) or
641
+ not isinstance(init, CTypesArray)):
642
+ raise TypeError("length/type mismatch: %s" % (init,))
643
+ init = tuple(init)
644
+ if len(init) > len(blob):
645
+ raise IndexError("too many initializers")
646
+ addr = ctypes.cast(blob, ctypes.c_void_p).value
647
+ PTR = ctypes.POINTER(BItem._ctype)
648
+ itemsize = ctypes.sizeof(BItem._ctype)
649
+ for i, value in enumerate(init):
650
+ p = ctypes.cast(addr + i * itemsize, PTR)
651
+ BItem._initialize(p.contents, value)
652
+
653
+ def __len__(self):
654
+ return len(self._blob)
655
+
656
+ def __getitem__(self, index):
657
+ if not (0 <= index < len(self._blob)):
658
+ raise IndexError
659
+ return BItem._from_ctypes(self._blob[index])
660
+
661
+ def __setitem__(self, index, value):
662
+ if not (0 <= index < len(self._blob)):
663
+ raise IndexError
664
+ self._blob[index] = BItem._to_ctypes(value)
665
+
666
+ if kind == 'char' or kind == 'byte':
667
+ def _to_string(self, maxlen):
668
+ if maxlen < 0:
669
+ maxlen = len(self._blob)
670
+ p = ctypes.cast(self._blob,
671
+ ctypes.POINTER(ctypes.c_char))
672
+ n = 0
673
+ while n < maxlen and p[n] != b'\x00':
674
+ n += 1
675
+ return b''.join([p[i] for i in range(n)])
676
+
677
+ def _get_own_repr(self):
678
+ if getattr(self, '_own', False):
679
+ return 'owning %d bytes' % (ctypes.sizeof(self._blob),)
680
+ return super(CTypesArray, self)._get_own_repr()
681
+
682
+ def _convert_to_address(self, BClass):
683
+ if BClass in (CTypesPtr, None) or BClass._automatic_casts:
684
+ return ctypes.addressof(self._blob)
685
+ else:
686
+ return CTypesData._convert_to_address(self, BClass)
687
+
688
+ @staticmethod
689
+ def _from_ctypes(ctypes_array):
690
+ self = CTypesArray.__new__(CTypesArray)
691
+ self._blob = ctypes_array
692
+ return self
693
+
694
+ @staticmethod
695
+ def _arg_to_ctypes(value):
696
+ return CTypesPtr._arg_to_ctypes(value)
697
+
698
+ def __add__(self, other):
699
+ if isinstance(other, (int, long)):
700
+ return CTypesPtr._new_pointer_at(
701
+ ctypes.addressof(self._blob) +
702
+ other * ctypes.sizeof(BItem._ctype))
703
+ else:
704
+ return NotImplemented
705
+
706
+ @classmethod
707
+ def _cast_from(cls, source):
708
+ raise NotImplementedError("casting to %r" % (
709
+ cls._get_c_name(),))
710
+ #
711
+ CTypesArray._fix_class()
712
+ return CTypesArray
713
+
714
+ def _new_struct_or_union(self, kind, name, base_ctypes_class):
715
+ #
716
+ class struct_or_union(base_ctypes_class):
717
+ pass
718
+ struct_or_union.__name__ = '%s_%s' % (kind, name)
719
+ kind1 = kind
720
+ #
721
+ class CTypesStructOrUnion(CTypesBaseStructOrUnion):
722
+ __slots__ = ['_blob']
723
+ _ctype = struct_or_union
724
+ _reftypename = '%s &' % (name,)
725
+ _kind = kind = kind1
726
+ #
727
+ CTypesStructOrUnion._fix_class()
728
+ return CTypesStructOrUnion
729
+
730
+ def new_struct_type(self, name):
731
+ return self._new_struct_or_union('struct', name, ctypes.Structure)
732
+
733
+ def new_union_type(self, name):
734
+ return self._new_struct_or_union('union', name, ctypes.Union)
735
+
736
+ def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp,
737
+ totalsize=-1, totalalignment=-1, sflags=0,
738
+ pack=0):
739
+ if totalsize >= 0 or totalalignment >= 0:
740
+ raise NotImplementedError("the ctypes backend of CFFI does not support "
741
+ "structures completed by verify(); please "
742
+ "compile and install the _cffi_backend module.")
743
+ struct_or_union = CTypesStructOrUnion._ctype
744
+ fnames = [fname for (fname, BField, bitsize) in fields]
745
+ btypes = [BField for (fname, BField, bitsize) in fields]
746
+ bitfields = [bitsize for (fname, BField, bitsize) in fields]
747
+ #
748
+ bfield_types = {}
749
+ cfields = []
750
+ for (fname, BField, bitsize) in fields:
751
+ if bitsize < 0:
752
+ cfields.append((fname, BField._ctype))
753
+ bfield_types[fname] = BField
754
+ else:
755
+ cfields.append((fname, BField._ctype, bitsize))
756
+ bfield_types[fname] = Ellipsis
757
+ if sflags & 8:
758
+ struct_or_union._pack_ = 1
759
+ elif pack:
760
+ struct_or_union._pack_ = pack
761
+ struct_or_union._fields_ = cfields
762
+ CTypesStructOrUnion._bfield_types = bfield_types
763
+ #
764
+ @staticmethod
765
+ def _create_ctype_obj(init):
766
+ result = struct_or_union()
767
+ if init is not None:
768
+ initialize(result, init)
769
+ return result
770
+ CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj
771
+ #
772
+ def initialize(blob, init):
773
+ if is_union:
774
+ if len(init) > 1:
775
+ raise ValueError("union initializer: %d items given, but "
776
+ "only one supported (use a dict if needed)"
777
+ % (len(init),))
778
+ if not isinstance(init, dict):
779
+ if isinstance(init, (bytes, unicode)):
780
+ raise TypeError("union initializer: got a str")
781
+ init = tuple(init)
782
+ if len(init) > len(fnames):
783
+ raise ValueError("too many values for %s initializer" %
784
+ CTypesStructOrUnion._get_c_name())
785
+ init = dict(zip(fnames, init))
786
+ addr = ctypes.addressof(blob)
787
+ for fname, value in init.items():
788
+ BField, bitsize = name2fieldtype[fname]
789
+ assert bitsize < 0, \
790
+ "not implemented: initializer with bit fields"
791
+ offset = CTypesStructOrUnion._offsetof(fname)
792
+ PTR = ctypes.POINTER(BField._ctype)
793
+ p = ctypes.cast(addr + offset, PTR)
794
+ BField._initialize(p.contents, value)
795
+ is_union = CTypesStructOrUnion._kind == 'union'
796
+ name2fieldtype = dict(zip(fnames, zip(btypes, bitfields)))
797
+ #
798
+ for fname, BField, bitsize in fields:
799
+ if fname == '':
800
+ raise NotImplementedError("nested anonymous structs/unions")
801
+ if hasattr(CTypesStructOrUnion, fname):
802
+ raise ValueError("the field name %r conflicts in "
803
+ "the ctypes backend" % fname)
804
+ if bitsize < 0:
805
+ def getter(self, fname=fname, BField=BField,
806
+ offset=CTypesStructOrUnion._offsetof(fname),
807
+ PTR=ctypes.POINTER(BField._ctype)):
808
+ addr = ctypes.addressof(self._blob)
809
+ p = ctypes.cast(addr + offset, PTR)
810
+ return BField._from_ctypes(p.contents)
811
+ def setter(self, value, fname=fname, BField=BField):
812
+ setattr(self._blob, fname, BField._to_ctypes(value))
813
+ #
814
+ if issubclass(BField, CTypesGenericArray):
815
+ setter = None
816
+ if BField._declared_length == 0:
817
+ def getter(self, fname=fname, BFieldPtr=BField._CTPtr,
818
+ offset=CTypesStructOrUnion._offsetof(fname),
819
+ PTR=ctypes.POINTER(BField._ctype)):
820
+ addr = ctypes.addressof(self._blob)
821
+ p = ctypes.cast(addr + offset, PTR)
822
+ return BFieldPtr._from_ctypes(p)
823
+ #
824
+ else:
825
+ def getter(self, fname=fname, BField=BField):
826
+ return BField._from_ctypes(getattr(self._blob, fname))
827
+ def setter(self, value, fname=fname, BField=BField):
828
+ # xxx obscure workaround
829
+ value = BField._to_ctypes(value)
830
+ oldvalue = getattr(self._blob, fname)
831
+ setattr(self._blob, fname, value)
832
+ if value != getattr(self._blob, fname):
833
+ setattr(self._blob, fname, oldvalue)
834
+ raise OverflowError("value too large for bitfield")
835
+ setattr(CTypesStructOrUnion, fname, property(getter, setter))
836
+ #
837
+ CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp))
838
+ for fname in fnames:
839
+ if hasattr(CTypesPtr, fname):
840
+ raise ValueError("the field name %r conflicts in "
841
+ "the ctypes backend" % fname)
842
+ def getter(self, fname=fname):
843
+ return getattr(self[0], fname)
844
+ def setter(self, value, fname=fname):
845
+ setattr(self[0], fname, value)
846
+ setattr(CTypesPtr, fname, property(getter, setter))
847
+
848
+ def new_function_type(self, BArgs, BResult, has_varargs):
849
+ nameargs = [BArg._get_c_name() for BArg in BArgs]
850
+ if has_varargs:
851
+ nameargs.append('...')
852
+ nameargs = ', '.join(nameargs)
853
+ #
854
+ class CTypesFunctionPtr(CTypesGenericPtr):
855
+ __slots__ = ['_own_callback', '_name']
856
+ _ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None),
857
+ *[BArg._ctype for BArg in BArgs],
858
+ use_errno=True)
859
+ _reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,))
860
+
861
+ def __init__(self, init, error=None):
862
+ # create a callback to the Python callable init()
863
+ import traceback
864
+ assert not has_varargs, "varargs not supported for callbacks"
865
+ if getattr(BResult, '_ctype', None) is not None:
866
+ error = BResult._from_ctypes(
867
+ BResult._create_ctype_obj(error))
868
+ else:
869
+ error = None
870
+ def callback(*args):
871
+ args2 = []
872
+ for arg, BArg in zip(args, BArgs):
873
+ args2.append(BArg._from_ctypes(arg))
874
+ try:
875
+ res2 = init(*args2)
876
+ res2 = BResult._to_ctypes(res2)
877
+ except:
878
+ traceback.print_exc()
879
+ res2 = error
880
+ if issubclass(BResult, CTypesGenericPtr):
881
+ if res2:
882
+ res2 = ctypes.cast(res2, ctypes.c_void_p).value
883
+ # .value: http://bugs.python.org/issue1574593
884
+ else:
885
+ res2 = None
886
+ #print repr(res2)
887
+ return res2
888
+ if issubclass(BResult, CTypesGenericPtr):
889
+ # The only pointers callbacks can return are void*s:
890
+ # http://bugs.python.org/issue5710
891
+ callback_ctype = ctypes.CFUNCTYPE(
892
+ ctypes.c_void_p,
893
+ *[BArg._ctype for BArg in BArgs],
894
+ use_errno=True)
895
+ else:
896
+ callback_ctype = CTypesFunctionPtr._ctype
897
+ self._as_ctype_ptr = callback_ctype(callback)
898
+ self._address = ctypes.cast(self._as_ctype_ptr,
899
+ ctypes.c_void_p).value
900
+ self._own_callback = init
901
+
902
+ @staticmethod
903
+ def _initialize(ctypes_ptr, value):
904
+ if value:
905
+ raise NotImplementedError("ctypes backend: not supported: "
906
+ "initializers for function pointers")
907
+
908
+ def __repr__(self):
909
+ c_name = getattr(self, '_name', None)
910
+ if c_name:
911
+ i = self._reftypename.index('(* &)')
912
+ if self._reftypename[i-1] not in ' )*':
913
+ c_name = ' ' + c_name
914
+ c_name = self._reftypename.replace('(* &)', c_name)
915
+ return CTypesData.__repr__(self, c_name)
916
+
917
+ def _get_own_repr(self):
918
+ if getattr(self, '_own_callback', None) is not None:
919
+ return 'calling %r' % (self._own_callback,)
920
+ return super(CTypesFunctionPtr, self)._get_own_repr()
921
+
922
+ def __call__(self, *args):
923
+ if has_varargs:
924
+ assert len(args) >= len(BArgs)
925
+ extraargs = args[len(BArgs):]
926
+ args = args[:len(BArgs)]
927
+ else:
928
+ assert len(args) == len(BArgs)
929
+ ctypes_args = []
930
+ for arg, BArg in zip(args, BArgs):
931
+ ctypes_args.append(BArg._arg_to_ctypes(arg))
932
+ if has_varargs:
933
+ for i, arg in enumerate(extraargs):
934
+ if arg is None:
935
+ ctypes_args.append(ctypes.c_void_p(0)) # NULL
936
+ continue
937
+ if not isinstance(arg, CTypesData):
938
+ raise TypeError(
939
+ "argument %d passed in the variadic part "
940
+ "needs to be a cdata object (got %s)" %
941
+ (1 + len(BArgs) + i, type(arg).__name__))
942
+ ctypes_args.append(arg._arg_to_ctypes(arg))
943
+ result = self._as_ctype_ptr(*ctypes_args)
944
+ return BResult._from_ctypes(result)
945
+ #
946
+ CTypesFunctionPtr._fix_class()
947
+ return CTypesFunctionPtr
948
+
949
+ def new_enum_type(self, name, enumerators, enumvalues, CTypesInt):
950
+ assert isinstance(name, str)
951
+ reverse_mapping = dict(zip(reversed(enumvalues),
952
+ reversed(enumerators)))
953
+ #
954
+ class CTypesEnum(CTypesInt):
955
+ __slots__ = []
956
+ _reftypename = '%s &' % name
957
+
958
+ def _get_own_repr(self):
959
+ value = self._value
960
+ try:
961
+ return '%d: %s' % (value, reverse_mapping[value])
962
+ except KeyError:
963
+ return str(value)
964
+
965
+ def _to_string(self, maxlen):
966
+ value = self._value
967
+ try:
968
+ return reverse_mapping[value]
969
+ except KeyError:
970
+ return str(value)
971
+ #
972
+ CTypesEnum._fix_class()
973
+ return CTypesEnum
974
+
975
+ def get_errno(self):
976
+ return ctypes.get_errno()
977
+
978
+ def set_errno(self, value):
979
+ ctypes.set_errno(value)
980
+
981
+ def string(self, b, maxlen=-1):
982
+ return b._to_string(maxlen)
983
+
984
+ def buffer(self, bptr, size=-1):
985
+ raise NotImplementedError("buffer() with ctypes backend")
986
+
987
+ def sizeof(self, cdata_or_BType):
988
+ if isinstance(cdata_or_BType, CTypesData):
989
+ return cdata_or_BType._get_size_of_instance()
990
+ else:
991
+ assert issubclass(cdata_or_BType, CTypesData)
992
+ return cdata_or_BType._get_size()
993
+
994
+ def alignof(self, BType):
995
+ assert issubclass(BType, CTypesData)
996
+ return BType._alignment()
997
+
998
+ def newp(self, BType, source):
999
+ if not issubclass(BType, CTypesData):
1000
+ raise TypeError
1001
+ return BType._newp(source)
1002
+
1003
+ def cast(self, BType, source):
1004
+ return BType._cast_from(source)
1005
+
1006
+ def callback(self, BType, source, error, onerror):
1007
+ assert onerror is None # XXX not implemented
1008
+ return BType(source, error)
1009
+
1010
+ _weakref_cache_ref = None
1011
+
1012
+ def gcp(self, cdata, destructor, size=0):
1013
+ if self._weakref_cache_ref is None:
1014
+ import weakref
1015
+ class MyRef(weakref.ref):
1016
+ def __eq__(self, other):
1017
+ myref = self()
1018
+ return self is other or (
1019
+ myref is not None and myref is other())
1020
+ def __ne__(self, other):
1021
+ return not (self == other)
1022
+ def __hash__(self):
1023
+ try:
1024
+ return self._hash
1025
+ except AttributeError:
1026
+ self._hash = hash(self())
1027
+ return self._hash
1028
+ self._weakref_cache_ref = {}, MyRef
1029
+ weak_cache, MyRef = self._weakref_cache_ref
1030
+
1031
+ if destructor is None:
1032
+ try:
1033
+ del weak_cache[MyRef(cdata)]
1034
+ except KeyError:
1035
+ raise TypeError("Can remove destructor only on a object "
1036
+ "previously returned by ffi.gc()")
1037
+ return None
1038
+
1039
+ def remove(k):
1040
+ cdata, destructor = weak_cache.pop(k, (None, None))
1041
+ if destructor is not None:
1042
+ destructor(cdata)
1043
+
1044
+ new_cdata = self.cast(self.typeof(cdata), cdata)
1045
+ assert new_cdata is not cdata
1046
+ weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor)
1047
+ return new_cdata
1048
+
1049
+ typeof = type
1050
+
1051
+ def getcname(self, BType, replace_with):
1052
+ return BType._get_c_name(replace_with)
1053
+
1054
+ def typeoffsetof(self, BType, fieldname, num=0):
1055
+ if isinstance(fieldname, str):
1056
+ if num == 0 and issubclass(BType, CTypesGenericPtr):
1057
+ BType = BType._BItem
1058
+ if not issubclass(BType, CTypesBaseStructOrUnion):
1059
+ raise TypeError("expected a struct or union ctype")
1060
+ BField = BType._bfield_types[fieldname]
1061
+ if BField is Ellipsis:
1062
+ raise TypeError("not supported for bitfields")
1063
+ return (BField, BType._offsetof(fieldname))
1064
+ elif isinstance(fieldname, (int, long)):
1065
+ if issubclass(BType, CTypesGenericArray):
1066
+ BType = BType._CTPtr
1067
+ if not issubclass(BType, CTypesGenericPtr):
1068
+ raise TypeError("expected an array or ptr ctype")
1069
+ BItem = BType._BItem
1070
+ offset = BItem._get_size() * fieldname
1071
+ if offset > sys.maxsize:
1072
+ raise OverflowError
1073
+ return (BItem, offset)
1074
+ else:
1075
+ raise TypeError(type(fieldname))
1076
+
1077
+ def rawaddressof(self, BTypePtr, cdata, offset=None):
1078
+ if isinstance(cdata, CTypesBaseStructOrUnion):
1079
+ ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata))
1080
+ elif isinstance(cdata, CTypesGenericPtr):
1081
+ if offset is None or not issubclass(type(cdata)._BItem,
1082
+ CTypesBaseStructOrUnion):
1083
+ raise TypeError("unexpected cdata type")
1084
+ ptr = type(cdata)._to_ctypes(cdata)
1085
+ elif isinstance(cdata, CTypesGenericArray):
1086
+ ptr = type(cdata)._to_ctypes(cdata)
1087
+ else:
1088
+ raise TypeError("expected a <cdata 'struct-or-union'>")
1089
+ if offset:
1090
+ ptr = ctypes.cast(
1091
+ ctypes.c_void_p(
1092
+ ctypes.cast(ptr, ctypes.c_void_p).value + offset),
1093
+ type(ptr))
1094
+ return BTypePtr._from_ctypes(ptr)
1095
+
1096
+
1097
+ class CTypesLibrary(object):
1098
+
1099
+ def __init__(self, backend, cdll):
1100
+ self.backend = backend
1101
+ self.cdll = cdll
1102
+
1103
+ def load_function(self, BType, name):
1104
+ c_func = getattr(self.cdll, name)
1105
+ funcobj = BType._from_ctypes(c_func)
1106
+ funcobj._name = name
1107
+ return funcobj
1108
+
1109
+ def read_variable(self, BType, name):
1110
+ try:
1111
+ ctypes_obj = BType._ctype.in_dll(self.cdll, name)
1112
+ except AttributeError as e:
1113
+ raise NotImplementedError(e)
1114
+ return BType._from_ctypes(ctypes_obj)
1115
+
1116
+ def write_variable(self, BType, name, value):
1117
+ new_ctypes_obj = BType._to_ctypes(value)
1118
+ ctypes_obj = BType._ctype.in_dll(self.cdll, name)
1119
+ ctypes.memmove(ctypes.addressof(ctypes_obj),
1120
+ ctypes.addressof(new_ctypes_obj),
1121
+ ctypes.sizeof(BType._ctype))