ZTWHHH commited on
Commit
d76127b
·
verified ·
1 Parent(s): dce3b7d

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. parrot/lib/python3.10/distutils/__pycache__/_msvccompiler.cpython-310.pyc +0 -0
  2. parrot/lib/python3.10/distutils/__pycache__/cmd.cpython-310.pyc +0 -0
  3. parrot/lib/python3.10/distutils/__pycache__/dir_util.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/distutils/__pycache__/errors.cpython-310.pyc +0 -0
  5. parrot/lib/python3.10/distutils/__pycache__/extension.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/distutils/__pycache__/file_util.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/distutils/__pycache__/log.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/distutils/__pycache__/msvc9compiler.cpython-310.pyc +0 -0
  9. parrot/lib/python3.10/distutils/__pycache__/util.cpython-310.pyc +0 -0
  10. parrot/lib/python3.10/distutils/command/__pycache__/__init__.cpython-310.pyc +0 -0
  11. parrot/lib/python3.10/distutils/command/__pycache__/bdist_msi.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/distutils/command/__pycache__/build.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/distutils/command/__pycache__/build_clib.cpython-310.pyc +0 -0
  14. parrot/lib/python3.10/distutils/command/__pycache__/build_scripts.cpython-310.pyc +0 -0
  15. parrot/lib/python3.10/distutils/command/__pycache__/check.cpython-310.pyc +0 -0
  16. parrot/lib/python3.10/distutils/command/__pycache__/install.cpython-310.pyc +0 -0
  17. parrot/lib/python3.10/distutils/command/__pycache__/install_data.cpython-310.pyc +0 -0
  18. parrot/lib/python3.10/distutils/command/__pycache__/install_egg_info.cpython-310.pyc +0 -0
  19. parrot/lib/python3.10/distutils/command/__pycache__/install_headers.cpython-310.pyc +0 -0
  20. parrot/lib/python3.10/distutils/command/__pycache__/install_scripts.cpython-310.pyc +0 -0
  21. parrot/lib/python3.10/distutils/command/__pycache__/upload.cpython-310.pyc +0 -0
  22. parrot/lib/python3.10/distutils/command/build_clib.py +209 -0
  23. parrot/lib/python3.10/distutils/command/build_ext.py +754 -0
  24. parrot/lib/python3.10/distutils/command/command_template +33 -0
  25. parrot/lib/python3.10/distutils/command/config.py +344 -0
  26. parrot/lib/python3.10/distutils/command/install_egg_info.py +77 -0
  27. parrot/lib/python3.10/distutils/command/install_lib.py +217 -0
  28. parrot/lib/python3.10/distutils/command/register.py +304 -0
  29. parrot/lib/python3.10/distutils/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  30. parrot/lib/python3.10/distutils/tests/__pycache__/test_install.cpython-310.pyc +0 -0
  31. parrot/lib/python3.10/ensurepip/__pycache__/_uninstall.cpython-310.pyc +0 -0
  32. parrot/lib/python3.10/json/__pycache__/encoder.cpython-310.pyc +0 -0
  33. parrot/lib/python3.10/json/__pycache__/scanner.cpython-310.pyc +0 -0
  34. parrot/lib/python3.10/json/encoder.py +442 -0
  35. parrot/lib/python3.10/json/tool.py +85 -0
  36. parrot/lib/python3.10/lib2to3/fixes/__pycache__/fix_except.cpython-310.pyc +0 -0
  37. parrot/lib/python3.10/lib2to3/fixes/__pycache__/fix_sys_exc.cpython-310.pyc +0 -0
  38. parrot/lib/python3.10/lib2to3/fixes/__pycache__/fix_throw.cpython-310.pyc +0 -0
  39. parrot/lib/python3.10/lib2to3/fixes/fix_apply.py +68 -0
  40. parrot/lib/python3.10/lib2to3/fixes/fix_exitfunc.py +72 -0
  41. parrot/lib/python3.10/lib2to3/fixes/fix_idioms.py +152 -0
  42. parrot/lib/python3.10/lib2to3/fixes/fix_imports.py +145 -0
  43. parrot/lib/python3.10/lib2to3/fixes/fix_isinstance.py +52 -0
  44. parrot/lib/python3.10/lib2to3/fixes/fix_map.py +110 -0
  45. parrot/lib/python3.10/lib2to3/fixes/fix_operator.py +97 -0
  46. parrot/lib/python3.10/lib2to3/fixes/fix_print.py +87 -0
  47. parrot/lib/python3.10/lib2to3/fixes/fix_raw_input.py +17 -0
  48. parrot/lib/python3.10/lib2to3/fixes/fix_reduce.py +35 -0
  49. parrot/lib/python3.10/lib2to3/fixes/fix_sys_exc.py +30 -0
  50. parrot/lib/python3.10/lib2to3/fixes/fix_xreadlines.py +25 -0
parrot/lib/python3.10/distutils/__pycache__/_msvccompiler.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/cmd.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/dir_util.cpython-310.pyc ADDED
Binary file (6.08 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/errors.cpython-310.pyc ADDED
Binary file (4.93 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/extension.cpython-310.pyc ADDED
Binary file (7.23 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/file_util.cpython-310.pyc ADDED
Binary file (5.92 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/log.cpython-310.pyc ADDED
Binary file (2.25 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/msvc9compiler.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
parrot/lib/python3.10/distutils/__pycache__/util.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (715 Bytes). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/bdist_msi.cpython-310.pyc ADDED
Binary file (19.7 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/build.cpython-310.pyc ADDED
Binary file (4.1 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/build_clib.cpython-310.pyc ADDED
Binary file (5.07 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/build_scripts.cpython-310.pyc ADDED
Binary file (4.32 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/check.cpython-310.pyc ADDED
Binary file (5.21 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/install.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/install_data.cpython-310.pyc ADDED
Binary file (2.29 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/install_egg_info.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/install_headers.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/install_scripts.cpython-310.pyc ADDED
Binary file (2.4 kB). View file
 
parrot/lib/python3.10/distutils/command/__pycache__/upload.cpython-310.pyc ADDED
Binary file (5.34 kB). View file
 
parrot/lib/python3.10/distutils/command/build_clib.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_clib
2
+
3
+ Implements the Distutils 'build_clib' command, to build a C/C++ library
4
+ that is included in the module distribution and needed by an extension
5
+ module."""
6
+
7
+
8
+ # XXX this module has *lots* of code ripped-off quite transparently from
9
+ # build_ext.py -- not surprisingly really, as the work required to build
10
+ # a static library from a collection of C source files is not really all
11
+ # that different from what's required to build a shared object file from
12
+ # a collection of C source files. Nevertheless, I haven't done the
13
+ # necessary refactoring to account for the overlap in code between the
14
+ # two modules, mainly because a number of subtle details changed in the
15
+ # cut 'n paste. Sigh.
16
+
17
+ import os
18
+ from distutils.core import Command
19
+ from distutils.errors import *
20
+ from distutils.sysconfig import customize_compiler
21
+ from distutils import log
22
+
23
+ def show_compilers():
24
+ from distutils.ccompiler import show_compilers
25
+ show_compilers()
26
+
27
+
28
+ class build_clib(Command):
29
+
30
+ description = "build C/C++ libraries used by Python extensions"
31
+
32
+ user_options = [
33
+ ('build-clib=', 'b',
34
+ "directory to build C/C++ libraries to"),
35
+ ('build-temp=', 't',
36
+ "directory to put temporary build by-products"),
37
+ ('debug', 'g',
38
+ "compile with debugging information"),
39
+ ('force', 'f',
40
+ "forcibly build everything (ignore file timestamps)"),
41
+ ('compiler=', 'c',
42
+ "specify the compiler type"),
43
+ ]
44
+
45
+ boolean_options = ['debug', 'force']
46
+
47
+ help_options = [
48
+ ('help-compiler', None,
49
+ "list available compilers", show_compilers),
50
+ ]
51
+
52
+ def initialize_options(self):
53
+ self.build_clib = None
54
+ self.build_temp = None
55
+
56
+ # List of libraries to build
57
+ self.libraries = None
58
+
59
+ # Compilation options for all libraries
60
+ self.include_dirs = None
61
+ self.define = None
62
+ self.undef = None
63
+ self.debug = None
64
+ self.force = 0
65
+ self.compiler = None
66
+
67
+
68
+ def finalize_options(self):
69
+ # This might be confusing: both build-clib and build-temp default
70
+ # to build-temp as defined by the "build" command. This is because
71
+ # I think that C libraries are really just temporary build
72
+ # by-products, at least from the point of view of building Python
73
+ # extensions -- but I want to keep my options open.
74
+ self.set_undefined_options('build',
75
+ ('build_temp', 'build_clib'),
76
+ ('build_temp', 'build_temp'),
77
+ ('compiler', 'compiler'),
78
+ ('debug', 'debug'),
79
+ ('force', 'force'))
80
+
81
+ self.libraries = self.distribution.libraries
82
+ if self.libraries:
83
+ self.check_library_list(self.libraries)
84
+
85
+ if self.include_dirs is None:
86
+ self.include_dirs = self.distribution.include_dirs or []
87
+ if isinstance(self.include_dirs, str):
88
+ self.include_dirs = self.include_dirs.split(os.pathsep)
89
+
90
+ # XXX same as for build_ext -- what about 'self.define' and
91
+ # 'self.undef' ?
92
+
93
+
94
+ def run(self):
95
+ if not self.libraries:
96
+ return
97
+
98
+ # Yech -- this is cut 'n pasted from build_ext.py!
99
+ from distutils.ccompiler import new_compiler
100
+ self.compiler = new_compiler(compiler=self.compiler,
101
+ dry_run=self.dry_run,
102
+ force=self.force)
103
+ customize_compiler(self.compiler)
104
+
105
+ if self.include_dirs is not None:
106
+ self.compiler.set_include_dirs(self.include_dirs)
107
+ if self.define is not None:
108
+ # 'define' option is a list of (name,value) tuples
109
+ for (name,value) in self.define:
110
+ self.compiler.define_macro(name, value)
111
+ if self.undef is not None:
112
+ for macro in self.undef:
113
+ self.compiler.undefine_macro(macro)
114
+
115
+ self.build_libraries(self.libraries)
116
+
117
+
118
+ def check_library_list(self, libraries):
119
+ """Ensure that the list of libraries is valid.
120
+
121
+ `library` is presumably provided as a command option 'libraries'.
122
+ This method checks that it is a list of 2-tuples, where the tuples
123
+ are (library_name, build_info_dict).
124
+
125
+ Raise DistutilsSetupError if the structure is invalid anywhere;
126
+ just returns otherwise.
127
+ """
128
+ if not isinstance(libraries, list):
129
+ raise DistutilsSetupError(
130
+ "'libraries' option must be a list of tuples")
131
+
132
+ for lib in libraries:
133
+ if not isinstance(lib, tuple) and len(lib) != 2:
134
+ raise DistutilsSetupError(
135
+ "each element of 'libraries' must a 2-tuple")
136
+
137
+ name, build_info = lib
138
+
139
+ if not isinstance(name, str):
140
+ raise DistutilsSetupError(
141
+ "first element of each tuple in 'libraries' "
142
+ "must be a string (the library name)")
143
+
144
+ if '/' in name or (os.sep != '/' and os.sep in name):
145
+ raise DistutilsSetupError("bad library name '%s': "
146
+ "may not contain directory separators" % lib[0])
147
+
148
+ if not isinstance(build_info, dict):
149
+ raise DistutilsSetupError(
150
+ "second element of each tuple in 'libraries' "
151
+ "must be a dictionary (build info)")
152
+
153
+
154
+ def get_library_names(self):
155
+ # Assume the library list is valid -- 'check_library_list()' is
156
+ # called from 'finalize_options()', so it should be!
157
+ if not self.libraries:
158
+ return None
159
+
160
+ lib_names = []
161
+ for (lib_name, build_info) in self.libraries:
162
+ lib_names.append(lib_name)
163
+ return lib_names
164
+
165
+
166
+ def get_source_files(self):
167
+ self.check_library_list(self.libraries)
168
+ filenames = []
169
+ for (lib_name, build_info) in self.libraries:
170
+ sources = build_info.get('sources')
171
+ if sources is None or not isinstance(sources, (list, tuple)):
172
+ raise DistutilsSetupError(
173
+ "in 'libraries' option (library '%s'), "
174
+ "'sources' must be present and must be "
175
+ "a list of source filenames" % lib_name)
176
+
177
+ filenames.extend(sources)
178
+ return filenames
179
+
180
+
181
+ def build_libraries(self, libraries):
182
+ for (lib_name, build_info) in libraries:
183
+ sources = build_info.get('sources')
184
+ if sources is None or not isinstance(sources, (list, tuple)):
185
+ raise DistutilsSetupError(
186
+ "in 'libraries' option (library '%s'), "
187
+ "'sources' must be present and must be "
188
+ "a list of source filenames" % lib_name)
189
+ sources = list(sources)
190
+
191
+ log.info("building '%s' library", lib_name)
192
+
193
+ # First, compile the source code to object files in the library
194
+ # directory. (This should probably change to putting object
195
+ # files in a temporary build directory.)
196
+ macros = build_info.get('macros')
197
+ include_dirs = build_info.get('include_dirs')
198
+ objects = self.compiler.compile(sources,
199
+ output_dir=self.build_temp,
200
+ macros=macros,
201
+ include_dirs=include_dirs,
202
+ debug=self.debug)
203
+
204
+ # Now "link" the object files together into a static library.
205
+ # (On Unix at least, this isn't really linking -- it just
206
+ # builds an archive. Whatever.)
207
+ self.compiler.create_static_lib(objects, lib_name,
208
+ output_dir=self.build_clib,
209
+ debug=self.debug)
parrot/lib/python3.10/distutils/command/build_ext.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_ext
2
+
3
+ Implements the Distutils 'build_ext' command, for building extension
4
+ modules (currently limited to C extensions, should accommodate C++
5
+ extensions ASAP)."""
6
+
7
+ import contextlib
8
+ import os
9
+ import re
10
+ import sys
11
+ from distutils.core import Command
12
+ from distutils.errors import *
13
+ from distutils.sysconfig import customize_compiler, get_python_version
14
+ from distutils.sysconfig import get_config_h_filename
15
+ from distutils.dep_util import newer_group
16
+ from distutils.extension import Extension
17
+ from distutils.util import get_platform
18
+ from distutils import log
19
+
20
+ from site import USER_BASE
21
+
22
+ # An extension name is just a dot-separated list of Python NAMEs (ie.
23
+ # the same as a fully-qualified module name).
24
+ extension_name_re = re.compile \
25
+ (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
26
+
27
+
28
+ def show_compilers ():
29
+ from distutils.ccompiler import show_compilers
30
+ show_compilers()
31
+
32
+
33
+ class build_ext(Command):
34
+
35
+ description = "build C/C++ extensions (compile/link to build directory)"
36
+
37
+ # XXX thoughts on how to deal with complex command-line options like
38
+ # these, i.e. how to make it so fancy_getopt can suck them off the
39
+ # command line and make it look like setup.py defined the appropriate
40
+ # lists of tuples of what-have-you.
41
+ # - each command needs a callback to process its command-line options
42
+ # - Command.__init__() needs access to its share of the whole
43
+ # command line (must ultimately come from
44
+ # Distribution.parse_command_line())
45
+ # - it then calls the current command class' option-parsing
46
+ # callback to deal with weird options like -D, which have to
47
+ # parse the option text and churn out some custom data
48
+ # structure
49
+ # - that data structure (in this case, a list of 2-tuples)
50
+ # will then be present in the command object by the time
51
+ # we get to finalize_options() (i.e. the constructor
52
+ # takes care of both command-line and client options
53
+ # in between initialize_options() and finalize_options())
54
+
55
+ sep_by = " (separated by '%s')" % os.pathsep
56
+ user_options = [
57
+ ('build-lib=', 'b',
58
+ "directory for compiled extension modules"),
59
+ ('build-temp=', 't',
60
+ "directory for temporary files (build by-products)"),
61
+ ('plat-name=', 'p',
62
+ "platform name to cross-compile for, if supported "
63
+ "(default: %s)" % get_platform()),
64
+ ('inplace', 'i',
65
+ "ignore build-lib and put compiled extensions into the source " +
66
+ "directory alongside your pure Python modules"),
67
+ ('include-dirs=', 'I',
68
+ "list of directories to search for header files" + sep_by),
69
+ ('define=', 'D',
70
+ "C preprocessor macros to define"),
71
+ ('undef=', 'U',
72
+ "C preprocessor macros to undefine"),
73
+ ('libraries=', 'l',
74
+ "external C libraries to link with"),
75
+ ('library-dirs=', 'L',
76
+ "directories to search for external C libraries" + sep_by),
77
+ ('rpath=', 'R',
78
+ "directories to search for shared C libraries at runtime"),
79
+ ('link-objects=', 'O',
80
+ "extra explicit link objects to include in the link"),
81
+ ('debug', 'g',
82
+ "compile/link with debugging information"),
83
+ ('force', 'f',
84
+ "forcibly build everything (ignore file timestamps)"),
85
+ ('compiler=', 'c',
86
+ "specify the compiler type"),
87
+ ('parallel=', 'j',
88
+ "number of parallel build jobs"),
89
+ ('swig-cpp', None,
90
+ "make SWIG create C++ files (default is C)"),
91
+ ('swig-opts=', None,
92
+ "list of SWIG command line options"),
93
+ ('swig=', None,
94
+ "path to the SWIG executable"),
95
+ ('user', None,
96
+ "add user include, library and rpath")
97
+ ]
98
+
99
+ boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
100
+
101
+ help_options = [
102
+ ('help-compiler', None,
103
+ "list available compilers", show_compilers),
104
+ ]
105
+
106
+ def initialize_options(self):
107
+ self.extensions = None
108
+ self.build_lib = None
109
+ self.plat_name = None
110
+ self.build_temp = None
111
+ self.inplace = 0
112
+ self.package = None
113
+
114
+ self.include_dirs = None
115
+ self.define = None
116
+ self.undef = None
117
+ self.libraries = None
118
+ self.library_dirs = None
119
+ self.rpath = None
120
+ self.link_objects = None
121
+ self.debug = None
122
+ self.force = None
123
+ self.compiler = None
124
+ self.swig = None
125
+ self.swig_cpp = None
126
+ self.swig_opts = None
127
+ self.user = None
128
+ self.parallel = None
129
+
130
+ def finalize_options(self):
131
+ from distutils import sysconfig
132
+
133
+ self.set_undefined_options('build',
134
+ ('build_lib', 'build_lib'),
135
+ ('build_temp', 'build_temp'),
136
+ ('compiler', 'compiler'),
137
+ ('debug', 'debug'),
138
+ ('force', 'force'),
139
+ ('parallel', 'parallel'),
140
+ ('plat_name', 'plat_name'),
141
+ )
142
+
143
+ if self.package is None:
144
+ self.package = self.distribution.ext_package
145
+
146
+ self.extensions = self.distribution.ext_modules
147
+
148
+ # Make sure Python's include directories (for Python.h, pyconfig.h,
149
+ # etc.) are in the include search path.
150
+ py_include = sysconfig.get_python_inc()
151
+ plat_py_include = sysconfig.get_python_inc(plat_specific=1)
152
+ if self.include_dirs is None:
153
+ self.include_dirs = self.distribution.include_dirs or []
154
+ if isinstance(self.include_dirs, str):
155
+ self.include_dirs = self.include_dirs.split(os.pathsep)
156
+
157
+ # If in a virtualenv, add its include directory
158
+ # Issue 16116
159
+ if sys.exec_prefix != sys.base_exec_prefix:
160
+ self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))
161
+
162
+ # Put the Python "system" include dir at the end, so that
163
+ # any local include dirs take precedence.
164
+ self.include_dirs.extend(py_include.split(os.path.pathsep))
165
+ if plat_py_include != py_include:
166
+ self.include_dirs.extend(
167
+ plat_py_include.split(os.path.pathsep))
168
+
169
+ self.ensure_string_list('libraries')
170
+ self.ensure_string_list('link_objects')
171
+
172
+ # Life is easier if we're not forever checking for None, so
173
+ # simplify these options to empty lists if unset
174
+ if self.libraries is None:
175
+ self.libraries = []
176
+ if self.library_dirs is None:
177
+ self.library_dirs = []
178
+ elif isinstance(self.library_dirs, str):
179
+ self.library_dirs = self.library_dirs.split(os.pathsep)
180
+
181
+ if self.rpath is None:
182
+ self.rpath = []
183
+ elif isinstance(self.rpath, str):
184
+ self.rpath = self.rpath.split(os.pathsep)
185
+
186
+ # for extensions under windows use different directories
187
+ # for Release and Debug builds.
188
+ # also Python's library directory must be appended to library_dirs
189
+ if os.name == 'nt':
190
+ # the 'libs' directory is for binary installs - we assume that
191
+ # must be the *native* platform. But we don't really support
192
+ # cross-compiling via a binary install anyway, so we let it go.
193
+ self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
194
+ if sys.base_exec_prefix != sys.prefix: # Issue 16116
195
+ self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))
196
+ if self.debug:
197
+ self.build_temp = os.path.join(self.build_temp, "Debug")
198
+ else:
199
+ self.build_temp = os.path.join(self.build_temp, "Release")
200
+
201
+ # Append the source distribution include and library directories,
202
+ # this allows distutils on windows to work in the source tree
203
+ self.include_dirs.append(os.path.dirname(get_config_h_filename()))
204
+ _sys_home = getattr(sys, '_home', None)
205
+ if _sys_home:
206
+ self.library_dirs.append(_sys_home)
207
+
208
+ # Use the .lib files for the correct architecture
209
+ if self.plat_name == 'win32':
210
+ suffix = 'win32'
211
+ else:
212
+ # win-amd64
213
+ suffix = self.plat_name[4:]
214
+ new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
215
+ if suffix:
216
+ new_lib = os.path.join(new_lib, suffix)
217
+ self.library_dirs.append(new_lib)
218
+
219
+ # For extensions under Cygwin, Python's library directory must be
220
+ # appended to library_dirs
221
+ if sys.platform[:6] == 'cygwin':
222
+ if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
223
+ # building third party extensions
224
+ self.library_dirs.append(os.path.join(sys.prefix, "lib",
225
+ "python" + get_python_version(),
226
+ "config"))
227
+ else:
228
+ # building python standard extensions
229
+ self.library_dirs.append('.')
230
+
231
+ # For building extensions with a shared Python library,
232
+ # Python's library directory must be appended to library_dirs
233
+ # See Issues: #1600860, #4366
234
+ if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
235
+ if not sysconfig.python_build:
236
+ # building third party extensions
237
+ self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
238
+ else:
239
+ # building python standard extensions
240
+ self.library_dirs.append('.')
241
+
242
+ # The argument parsing will result in self.define being a string, but
243
+ # it has to be a list of 2-tuples. All the preprocessor symbols
244
+ # specified by the 'define' option will be set to '1'. Multiple
245
+ # symbols can be separated with commas.
246
+
247
+ if self.define:
248
+ defines = self.define.split(',')
249
+ self.define = [(symbol, '1') for symbol in defines]
250
+
251
+ # The option for macros to undefine is also a string from the
252
+ # option parsing, but has to be a list. Multiple symbols can also
253
+ # be separated with commas here.
254
+ if self.undef:
255
+ self.undef = self.undef.split(',')
256
+
257
+ if self.swig_opts is None:
258
+ self.swig_opts = []
259
+ else:
260
+ self.swig_opts = self.swig_opts.split(' ')
261
+
262
+ # Finally add the user include and library directories if requested
263
+ if self.user:
264
+ user_include = os.path.join(USER_BASE, "include")
265
+ user_lib = os.path.join(USER_BASE, "lib")
266
+ if os.path.isdir(user_include):
267
+ self.include_dirs.append(user_include)
268
+ if os.path.isdir(user_lib):
269
+ self.library_dirs.append(user_lib)
270
+ self.rpath.append(user_lib)
271
+
272
+ if isinstance(self.parallel, str):
273
+ try:
274
+ self.parallel = int(self.parallel)
275
+ except ValueError:
276
+ raise DistutilsOptionError("parallel should be an integer")
277
+
278
+ def run(self):
279
+ from distutils.ccompiler import new_compiler
280
+
281
+ # 'self.extensions', as supplied by setup.py, is a list of
282
+ # Extension instances. See the documentation for Extension (in
283
+ # distutils.extension) for details.
284
+ #
285
+ # For backwards compatibility with Distutils 0.8.2 and earlier, we
286
+ # also allow the 'extensions' list to be a list of tuples:
287
+ # (ext_name, build_info)
288
+ # where build_info is a dictionary containing everything that
289
+ # Extension instances do except the name, with a few things being
290
+ # differently named. We convert these 2-tuples to Extension
291
+ # instances as needed.
292
+
293
+ if not self.extensions:
294
+ return
295
+
296
+ # If we were asked to build any C/C++ libraries, make sure that the
297
+ # directory where we put them is in the library search path for
298
+ # linking extensions.
299
+ if self.distribution.has_c_libraries():
300
+ build_clib = self.get_finalized_command('build_clib')
301
+ self.libraries.extend(build_clib.get_library_names() or [])
302
+ self.library_dirs.append(build_clib.build_clib)
303
+
304
+ # Setup the CCompiler object that we'll use to do all the
305
+ # compiling and linking
306
+ self.compiler = new_compiler(compiler=self.compiler,
307
+ verbose=self.verbose,
308
+ dry_run=self.dry_run,
309
+ force=self.force)
310
+ customize_compiler(self.compiler)
311
+ # If we are cross-compiling, init the compiler now (if we are not
312
+ # cross-compiling, init would not hurt, but people may rely on
313
+ # late initialization of compiler even if they shouldn't...)
314
+ if os.name == 'nt' and self.plat_name != get_platform():
315
+ self.compiler.initialize(self.plat_name)
316
+
317
+ # And make sure that any compile/link-related options (which might
318
+ # come from the command-line or from the setup script) are set in
319
+ # that CCompiler object -- that way, they automatically apply to
320
+ # all compiling and linking done here.
321
+ if self.include_dirs is not None:
322
+ self.compiler.set_include_dirs(self.include_dirs)
323
+ if self.define is not None:
324
+ # 'define' option is a list of (name,value) tuples
325
+ for (name, value) in self.define:
326
+ self.compiler.define_macro(name, value)
327
+ if self.undef is not None:
328
+ for macro in self.undef:
329
+ self.compiler.undefine_macro(macro)
330
+ if self.libraries is not None:
331
+ self.compiler.set_libraries(self.libraries)
332
+ if self.library_dirs is not None:
333
+ self.compiler.set_library_dirs(self.library_dirs)
334
+ if self.rpath is not None:
335
+ self.compiler.set_runtime_library_dirs(self.rpath)
336
+ if self.link_objects is not None:
337
+ self.compiler.set_link_objects(self.link_objects)
338
+
339
+ # Now actually compile and link everything.
340
+ self.build_extensions()
341
+
342
+ def check_extensions_list(self, extensions):
343
+ """Ensure that the list of extensions (presumably provided as a
344
+ command option 'extensions') is valid, i.e. it is a list of
345
+ Extension objects. We also support the old-style list of 2-tuples,
346
+ where the tuples are (ext_name, build_info), which are converted to
347
+ Extension instances here.
348
+
349
+ Raise DistutilsSetupError if the structure is invalid anywhere;
350
+ just returns otherwise.
351
+ """
352
+ if not isinstance(extensions, list):
353
+ raise DistutilsSetupError(
354
+ "'ext_modules' option must be a list of Extension instances")
355
+
356
+ for i, ext in enumerate(extensions):
357
+ if isinstance(ext, Extension):
358
+ continue # OK! (assume type-checking done
359
+ # by Extension constructor)
360
+
361
+ if not isinstance(ext, tuple) or len(ext) != 2:
362
+ raise DistutilsSetupError(
363
+ "each element of 'ext_modules' option must be an "
364
+ "Extension instance or 2-tuple")
365
+
366
+ ext_name, build_info = ext
367
+
368
+ log.warn("old-style (ext_name, build_info) tuple found in "
369
+ "ext_modules for extension '%s' "
370
+ "-- please convert to Extension instance", ext_name)
371
+
372
+ if not (isinstance(ext_name, str) and
373
+ extension_name_re.match(ext_name)):
374
+ raise DistutilsSetupError(
375
+ "first element of each tuple in 'ext_modules' "
376
+ "must be the extension name (a string)")
377
+
378
+ if not isinstance(build_info, dict):
379
+ raise DistutilsSetupError(
380
+ "second element of each tuple in 'ext_modules' "
381
+ "must be a dictionary (build info)")
382
+
383
+ # OK, the (ext_name, build_info) dict is type-safe: convert it
384
+ # to an Extension instance.
385
+ ext = Extension(ext_name, build_info['sources'])
386
+
387
+ # Easy stuff: one-to-one mapping from dict elements to
388
+ # instance attributes.
389
+ for key in ('include_dirs', 'library_dirs', 'libraries',
390
+ 'extra_objects', 'extra_compile_args',
391
+ 'extra_link_args'):
392
+ val = build_info.get(key)
393
+ if val is not None:
394
+ setattr(ext, key, val)
395
+
396
+ # Medium-easy stuff: same syntax/semantics, different names.
397
+ ext.runtime_library_dirs = build_info.get('rpath')
398
+ if 'def_file' in build_info:
399
+ log.warn("'def_file' element of build info dict "
400
+ "no longer supported")
401
+
402
+ # Non-trivial stuff: 'macros' split into 'define_macros'
403
+ # and 'undef_macros'.
404
+ macros = build_info.get('macros')
405
+ if macros:
406
+ ext.define_macros = []
407
+ ext.undef_macros = []
408
+ for macro in macros:
409
+ if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
410
+ raise DistutilsSetupError(
411
+ "'macros' element of build info dict "
412
+ "must be 1- or 2-tuple")
413
+ if len(macro) == 1:
414
+ ext.undef_macros.append(macro[0])
415
+ elif len(macro) == 2:
416
+ ext.define_macros.append(macro)
417
+
418
+ extensions[i] = ext
419
+
420
+ def get_source_files(self):
421
+ self.check_extensions_list(self.extensions)
422
+ filenames = []
423
+
424
+ # Wouldn't it be neat if we knew the names of header files too...
425
+ for ext in self.extensions:
426
+ filenames.extend(ext.sources)
427
+ return filenames
428
+
429
+ def get_outputs(self):
430
+ # Sanity check the 'extensions' list -- can't assume this is being
431
+ # done in the same run as a 'build_extensions()' call (in fact, we
432
+ # can probably assume that it *isn't*!).
433
+ self.check_extensions_list(self.extensions)
434
+
435
+ # And build the list of output (built) filenames. Note that this
436
+ # ignores the 'inplace' flag, and assumes everything goes in the
437
+ # "build" tree.
438
+ outputs = []
439
+ for ext in self.extensions:
440
+ outputs.append(self.get_ext_fullpath(ext.name))
441
+ return outputs
442
+
443
+ def build_extensions(self):
444
+ # First, sanity-check the 'extensions' list
445
+ self.check_extensions_list(self.extensions)
446
+ if self.parallel:
447
+ self._build_extensions_parallel()
448
+ else:
449
+ self._build_extensions_serial()
450
+
451
+ def _build_extensions_parallel(self):
452
+ workers = self.parallel
453
+ if self.parallel is True:
454
+ workers = os.cpu_count() # may return None
455
+ try:
456
+ from concurrent.futures import ThreadPoolExecutor
457
+ except ImportError:
458
+ workers = None
459
+
460
+ if workers is None:
461
+ self._build_extensions_serial()
462
+ return
463
+
464
+ with ThreadPoolExecutor(max_workers=workers) as executor:
465
+ futures = [executor.submit(self.build_extension, ext)
466
+ for ext in self.extensions]
467
+ for ext, fut in zip(self.extensions, futures):
468
+ with self._filter_build_errors(ext):
469
+ fut.result()
470
+
471
+ def _build_extensions_serial(self):
472
+ for ext in self.extensions:
473
+ with self._filter_build_errors(ext):
474
+ self.build_extension(ext)
475
+
476
+ @contextlib.contextmanager
477
+ def _filter_build_errors(self, ext):
478
+ try:
479
+ yield
480
+ except (CCompilerError, DistutilsError, CompileError) as e:
481
+ if not ext.optional:
482
+ raise
483
+ self.warn('building extension "%s" failed: %s' %
484
+ (ext.name, e))
485
+
486
+ def build_extension(self, ext):
487
+ sources = ext.sources
488
+ if sources is None or not isinstance(sources, (list, tuple)):
489
+ raise DistutilsSetupError(
490
+ "in 'ext_modules' option (extension '%s'), "
491
+ "'sources' must be present and must be "
492
+ "a list of source filenames" % ext.name)
493
+ # sort to make the resulting .so file build reproducible
494
+ sources = sorted(sources)
495
+
496
+ ext_path = self.get_ext_fullpath(ext.name)
497
+ depends = sources + ext.depends
498
+ if not (self.force or newer_group(depends, ext_path, 'newer')):
499
+ log.debug("skipping '%s' extension (up-to-date)", ext.name)
500
+ return
501
+ else:
502
+ log.info("building '%s' extension", ext.name)
503
+
504
+ # First, scan the sources for SWIG definition files (.i), run
505
+ # SWIG on 'em to create .c files, and modify the sources list
506
+ # accordingly.
507
+ sources = self.swig_sources(sources, ext)
508
+
509
+ # Next, compile the source code to object files.
510
+
511
+ # XXX not honouring 'define_macros' or 'undef_macros' -- the
512
+ # CCompiler API needs to change to accommodate this, and I
513
+ # want to do one thing at a time!
514
+
515
+ # Two possible sources for extra compiler arguments:
516
+ # - 'extra_compile_args' in Extension object
517
+ # - CFLAGS environment variable (not particularly
518
+ # elegant, but people seem to expect it and I
519
+ # guess it's useful)
520
+ # The environment variable should take precedence, and
521
+ # any sensible compiler will give precedence to later
522
+ # command line args. Hence we combine them in order:
523
+ extra_args = ext.extra_compile_args or []
524
+
525
+ macros = ext.define_macros[:]
526
+ for undef in ext.undef_macros:
527
+ macros.append((undef,))
528
+
529
+ objects = self.compiler.compile(sources,
530
+ output_dir=self.build_temp,
531
+ macros=macros,
532
+ include_dirs=ext.include_dirs,
533
+ debug=self.debug,
534
+ extra_postargs=extra_args,
535
+ depends=ext.depends)
536
+
537
+ # XXX outdated variable, kept here in case third-part code
538
+ # needs it.
539
+ self._built_objects = objects[:]
540
+
541
+ # Now link the object files together into a "shared object" --
542
+ # of course, first we have to figure out all the other things
543
+ # that go into the mix.
544
+ if ext.extra_objects:
545
+ objects.extend(ext.extra_objects)
546
+ extra_args = ext.extra_link_args or []
547
+
548
+ # Detect target language, if not provided
549
+ language = ext.language or self.compiler.detect_language(sources)
550
+
551
+ self.compiler.link_shared_object(
552
+ objects, ext_path,
553
+ libraries=self.get_libraries(ext),
554
+ library_dirs=ext.library_dirs,
555
+ runtime_library_dirs=ext.runtime_library_dirs,
556
+ extra_postargs=extra_args,
557
+ export_symbols=self.get_export_symbols(ext),
558
+ debug=self.debug,
559
+ build_temp=self.build_temp,
560
+ target_lang=language)
561
+
562
+ def swig_sources(self, sources, extension):
563
+ """Walk the list of source files in 'sources', looking for SWIG
564
+ interface (.i) files. Run SWIG on all that are found, and
565
+ return a modified 'sources' list with SWIG source files replaced
566
+ by the generated C (or C++) files.
567
+ """
568
+ new_sources = []
569
+ swig_sources = []
570
+ swig_targets = {}
571
+
572
+ # XXX this drops generated C/C++ files into the source tree, which
573
+ # is fine for developers who want to distribute the generated
574
+ # source -- but there should be an option to put SWIG output in
575
+ # the temp dir.
576
+
577
+ if self.swig_cpp:
578
+ log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
579
+
580
+ if self.swig_cpp or ('-c++' in self.swig_opts) or \
581
+ ('-c++' in extension.swig_opts):
582
+ target_ext = '.cpp'
583
+ else:
584
+ target_ext = '.c'
585
+
586
+ for source in sources:
587
+ (base, ext) = os.path.splitext(source)
588
+ if ext == ".i": # SWIG interface file
589
+ new_sources.append(base + '_wrap' + target_ext)
590
+ swig_sources.append(source)
591
+ swig_targets[source] = new_sources[-1]
592
+ else:
593
+ new_sources.append(source)
594
+
595
+ if not swig_sources:
596
+ return new_sources
597
+
598
+ swig = self.swig or self.find_swig()
599
+ swig_cmd = [swig, "-python"]
600
+ swig_cmd.extend(self.swig_opts)
601
+ if self.swig_cpp:
602
+ swig_cmd.append("-c++")
603
+
604
+ # Do not override commandline arguments
605
+ if not self.swig_opts:
606
+ for o in extension.swig_opts:
607
+ swig_cmd.append(o)
608
+
609
+ for source in swig_sources:
610
+ target = swig_targets[source]
611
+ log.info("swigging %s to %s", source, target)
612
+ self.spawn(swig_cmd + ["-o", target, source])
613
+
614
+ return new_sources
615
+
616
+ def find_swig(self):
617
+ """Return the name of the SWIG executable. On Unix, this is
618
+ just "swig" -- it should be in the PATH. Tries a bit harder on
619
+ Windows.
620
+ """
621
+ if os.name == "posix":
622
+ return "swig"
623
+ elif os.name == "nt":
624
+ # Look for SWIG in its standard installation directory on
625
+ # Windows (or so I presume!). If we find it there, great;
626
+ # if not, act like Unix and assume it's in the PATH.
627
+ for vers in ("1.3", "1.2", "1.1"):
628
+ fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
629
+ if os.path.isfile(fn):
630
+ return fn
631
+ else:
632
+ return "swig.exe"
633
+ else:
634
+ raise DistutilsPlatformError(
635
+ "I don't know how to find (much less run) SWIG "
636
+ "on platform '%s'" % os.name)
637
+
638
+ # -- Name generators -----------------------------------------------
639
+ # (extension names, filenames, whatever)
640
+ def get_ext_fullpath(self, ext_name):
641
+ """Returns the path of the filename for a given extension.
642
+
643
+ The file is located in `build_lib` or directly in the package
644
+ (inplace option).
645
+ """
646
+ fullname = self.get_ext_fullname(ext_name)
647
+ modpath = fullname.split('.')
648
+ filename = self.get_ext_filename(modpath[-1])
649
+
650
+ if not self.inplace:
651
+ # no further work needed
652
+ # returning :
653
+ # build_dir/package/path/filename
654
+ filename = os.path.join(*modpath[:-1]+[filename])
655
+ return os.path.join(self.build_lib, filename)
656
+
657
+ # the inplace option requires to find the package directory
658
+ # using the build_py command for that
659
+ package = '.'.join(modpath[0:-1])
660
+ build_py = self.get_finalized_command('build_py')
661
+ package_dir = os.path.abspath(build_py.get_package_dir(package))
662
+
663
+ # returning
664
+ # package_dir/filename
665
+ return os.path.join(package_dir, filename)
666
+
667
+ def get_ext_fullname(self, ext_name):
668
+ """Returns the fullname of a given extension name.
669
+
670
+ Adds the `package.` prefix"""
671
+ if self.package is None:
672
+ return ext_name
673
+ else:
674
+ return self.package + '.' + ext_name
675
+
676
+ def get_ext_filename(self, ext_name):
677
+ r"""Convert the name of an extension (eg. "foo.bar") into the name
678
+ of the file from which it will be loaded (eg. "foo/bar.so", or
679
+ "foo\bar.pyd").
680
+ """
681
+ from distutils.sysconfig import get_config_var
682
+ ext_path = ext_name.split('.')
683
+ ext_suffix = get_config_var('EXT_SUFFIX')
684
+ return os.path.join(*ext_path) + ext_suffix
685
+
686
+ def get_export_symbols(self, ext):
687
+ """Return the list of symbols that a shared extension has to
688
+ export. This either uses 'ext.export_symbols' or, if it's not
689
+ provided, "PyInit_" + module_name. Only relevant on Windows, where
690
+ the .pyd file (DLL) must export the module "PyInit_" function.
691
+ """
692
+ suffix = '_' + ext.name.split('.')[-1]
693
+ try:
694
+ # Unicode module name support as defined in PEP-489
695
+ # https://www.python.org/dev/peps/pep-0489/#export-hook-name
696
+ suffix.encode('ascii')
697
+ except UnicodeEncodeError:
698
+ suffix = 'U' + suffix.encode('punycode').replace(b'-', b'_').decode('ascii')
699
+
700
+ initfunc_name = "PyInit" + suffix
701
+ if initfunc_name not in ext.export_symbols:
702
+ ext.export_symbols.append(initfunc_name)
703
+ return ext.export_symbols
704
+
705
+ def get_libraries(self, ext):
706
+ """Return the list of libraries to link against when building a
707
+ shared extension. On most platforms, this is just 'ext.libraries';
708
+ on Windows, we add the Python library (eg. python20.dll).
709
+ """
710
+ # The python library is always needed on Windows. For MSVC, this
711
+ # is redundant, since the library is mentioned in a pragma in
712
+ # pyconfig.h that MSVC groks. The other Windows compilers all seem
713
+ # to need it mentioned explicitly, though, so that's what we do.
714
+ # Append '_d' to the python import library on debug builds.
715
+ if sys.platform == "win32":
716
+ from distutils._msvccompiler import MSVCCompiler
717
+ if not isinstance(self.compiler, MSVCCompiler):
718
+ template = "python%d%d"
719
+ if self.debug:
720
+ template = template + '_d'
721
+ pythonlib = (template %
722
+ (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
723
+ # don't extend ext.libraries, it may be shared with other
724
+ # extensions, it is a reference to the original list
725
+ return ext.libraries + [pythonlib]
726
+ else:
727
+ # On Android only the main executable and LD_PRELOADs are considered
728
+ # to be RTLD_GLOBAL, all the dependencies of the main executable
729
+ # remain RTLD_LOCAL and so the shared libraries must be linked with
730
+ # libpython when python is built with a shared python library (issue
731
+ # bpo-21536).
732
+ # On Cygwin (and if required, other POSIX-like platforms based on
733
+ # Windows like MinGW) it is simply necessary that all symbols in
734
+ # shared libraries are resolved at link time.
735
+ from distutils.sysconfig import get_config_var
736
+ link_libpython = False
737
+ if get_config_var('Py_ENABLE_SHARED'):
738
+ # A native build on an Android device or on Cygwin
739
+ if hasattr(sys, 'getandroidapilevel'):
740
+ link_libpython = True
741
+ elif sys.platform == 'cygwin':
742
+ link_libpython = True
743
+ elif '_PYTHON_HOST_PLATFORM' in os.environ:
744
+ # We are cross-compiling for one of the relevant platforms
745
+ if get_config_var('ANDROID_API_LEVEL') != 0:
746
+ link_libpython = True
747
+ elif get_config_var('MACHDEP') == 'cygwin':
748
+ link_libpython = True
749
+
750
+ if link_libpython:
751
+ ldversion = get_config_var('LDVERSION')
752
+ return ext.libraries + ['python' + ldversion]
753
+
754
+ return ext.libraries
parrot/lib/python3.10/distutils/command/command_template ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.x
2
+
3
+ Implements the Distutils 'x' command.
4
+ """
5
+
6
+ # created 2000/mm/dd, John Doe
7
+
8
+ __revision__ = "$Id$"
9
+
10
+ from distutils.core import Command
11
+
12
+
13
+ class x(Command):
14
+
15
+ # Brief (40-50 characters) description of the command
16
+ description = ""
17
+
18
+ # List of option tuples: long name, short name (None if no short
19
+ # name), and help string.
20
+ user_options = [('', '',
21
+ ""),
22
+ ]
23
+
24
+ def initialize_options(self):
25
+ self. = None
26
+ self. = None
27
+ self. = None
28
+
29
+ def finalize_options(self):
30
+ if self.x is None:
31
+ self.x =
32
+
33
+ def run(self):
parrot/lib/python3.10/distutils/command/config.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.config
2
+
3
+ Implements the Distutils 'config' command, a (mostly) empty command class
4
+ that exists mainly to be sub-classed by specific module distributions and
5
+ applications. The idea is that while every "config" command is different,
6
+ at least they're all named the same, and users always see "config" in the
7
+ list of standard commands. Also, this is a good place to put common
8
+ configure-like tasks: "try to compile this C code", or "figure out where
9
+ this header file lives".
10
+ """
11
+
12
+ import os, re
13
+
14
+ from distutils.core import Command
15
+ from distutils.errors import DistutilsExecError
16
+ from distutils.sysconfig import customize_compiler
17
+ from distutils import log
18
+
19
+ LANG_EXT = {"c": ".c", "c++": ".cxx"}
20
+
21
+ class config(Command):
22
+
23
+ description = "prepare to build"
24
+
25
+ user_options = [
26
+ ('compiler=', None,
27
+ "specify the compiler type"),
28
+ ('cc=', None,
29
+ "specify the compiler executable"),
30
+ ('include-dirs=', 'I',
31
+ "list of directories to search for header files"),
32
+ ('define=', 'D',
33
+ "C preprocessor macros to define"),
34
+ ('undef=', 'U',
35
+ "C preprocessor macros to undefine"),
36
+ ('libraries=', 'l',
37
+ "external C libraries to link with"),
38
+ ('library-dirs=', 'L',
39
+ "directories to search for external C libraries"),
40
+
41
+ ('noisy', None,
42
+ "show every action (compile, link, run, ...) taken"),
43
+ ('dump-source', None,
44
+ "dump generated source files before attempting to compile them"),
45
+ ]
46
+
47
+
48
+ # The three standard command methods: since the "config" command
49
+ # does nothing by default, these are empty.
50
+
51
+ def initialize_options(self):
52
+ self.compiler = None
53
+ self.cc = None
54
+ self.include_dirs = None
55
+ self.libraries = None
56
+ self.library_dirs = None
57
+
58
+ # maximal output for now
59
+ self.noisy = 1
60
+ self.dump_source = 1
61
+
62
+ # list of temporary files generated along-the-way that we have
63
+ # to clean at some point
64
+ self.temp_files = []
65
+
66
+ def finalize_options(self):
67
+ if self.include_dirs is None:
68
+ self.include_dirs = self.distribution.include_dirs or []
69
+ elif isinstance(self.include_dirs, str):
70
+ self.include_dirs = self.include_dirs.split(os.pathsep)
71
+
72
+ if self.libraries is None:
73
+ self.libraries = []
74
+ elif isinstance(self.libraries, str):
75
+ self.libraries = [self.libraries]
76
+
77
+ if self.library_dirs is None:
78
+ self.library_dirs = []
79
+ elif isinstance(self.library_dirs, str):
80
+ self.library_dirs = self.library_dirs.split(os.pathsep)
81
+
82
+ def run(self):
83
+ pass
84
+
85
+ # Utility methods for actual "config" commands. The interfaces are
86
+ # loosely based on Autoconf macros of similar names. Sub-classes
87
+ # may use these freely.
88
+
89
+ def _check_compiler(self):
90
+ """Check that 'self.compiler' really is a CCompiler object;
91
+ if not, make it one.
92
+ """
93
+ # We do this late, and only on-demand, because this is an expensive
94
+ # import.
95
+ from distutils.ccompiler import CCompiler, new_compiler
96
+ if not isinstance(self.compiler, CCompiler):
97
+ self.compiler = new_compiler(compiler=self.compiler,
98
+ dry_run=self.dry_run, force=1)
99
+ customize_compiler(self.compiler)
100
+ if self.include_dirs:
101
+ self.compiler.set_include_dirs(self.include_dirs)
102
+ if self.libraries:
103
+ self.compiler.set_libraries(self.libraries)
104
+ if self.library_dirs:
105
+ self.compiler.set_library_dirs(self.library_dirs)
106
+
107
+ def _gen_temp_sourcefile(self, body, headers, lang):
108
+ filename = "_configtest" + LANG_EXT[lang]
109
+ with open(filename, "w") as file:
110
+ if headers:
111
+ for header in headers:
112
+ file.write("#include <%s>\n" % header)
113
+ file.write("\n")
114
+ file.write(body)
115
+ if body[-1] != "\n":
116
+ file.write("\n")
117
+ return filename
118
+
119
+ def _preprocess(self, body, headers, include_dirs, lang):
120
+ src = self._gen_temp_sourcefile(body, headers, lang)
121
+ out = "_configtest.i"
122
+ self.temp_files.extend([src, out])
123
+ self.compiler.preprocess(src, out, include_dirs=include_dirs)
124
+ return (src, out)
125
+
126
+ def _compile(self, body, headers, include_dirs, lang):
127
+ src = self._gen_temp_sourcefile(body, headers, lang)
128
+ if self.dump_source:
129
+ dump_file(src, "compiling '%s':" % src)
130
+ (obj,) = self.compiler.object_filenames([src])
131
+ self.temp_files.extend([src, obj])
132
+ self.compiler.compile([src], include_dirs=include_dirs)
133
+ return (src, obj)
134
+
135
+ def _link(self, body, headers, include_dirs, libraries, library_dirs,
136
+ lang):
137
+ (src, obj) = self._compile(body, headers, include_dirs, lang)
138
+ prog = os.path.splitext(os.path.basename(src))[0]
139
+ self.compiler.link_executable([obj], prog,
140
+ libraries=libraries,
141
+ library_dirs=library_dirs,
142
+ target_lang=lang)
143
+
144
+ if self.compiler.exe_extension is not None:
145
+ prog = prog + self.compiler.exe_extension
146
+ self.temp_files.append(prog)
147
+
148
+ return (src, obj, prog)
149
+
150
+ def _clean(self, *filenames):
151
+ if not filenames:
152
+ filenames = self.temp_files
153
+ self.temp_files = []
154
+ log.info("removing: %s", ' '.join(filenames))
155
+ for filename in filenames:
156
+ try:
157
+ os.remove(filename)
158
+ except OSError:
159
+ pass
160
+
161
+
162
+ # XXX these ignore the dry-run flag: what to do, what to do? even if
163
+ # you want a dry-run build, you still need some sort of configuration
164
+ # info. My inclination is to make it up to the real config command to
165
+ # consult 'dry_run', and assume a default (minimal) configuration if
166
+ # true. The problem with trying to do it here is that you'd have to
167
+ # return either true or false from all the 'try' methods, neither of
168
+ # which is correct.
169
+
170
+ # XXX need access to the header search path and maybe default macros.
171
+
172
+ def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
173
+ """Construct a source file from 'body' (a string containing lines
174
+ of C/C++ code) and 'headers' (a list of header files to include)
175
+ and run it through the preprocessor. Return true if the
176
+ preprocessor succeeded, false if there were any errors.
177
+ ('body' probably isn't of much use, but what the heck.)
178
+ """
179
+ from distutils.ccompiler import CompileError
180
+ self._check_compiler()
181
+ ok = True
182
+ try:
183
+ self._preprocess(body, headers, include_dirs, lang)
184
+ except CompileError:
185
+ ok = False
186
+
187
+ self._clean()
188
+ return ok
189
+
190
+ def search_cpp(self, pattern, body=None, headers=None, include_dirs=None,
191
+ lang="c"):
192
+ """Construct a source file (just like 'try_cpp()'), run it through
193
+ the preprocessor, and return true if any line of the output matches
194
+ 'pattern'. 'pattern' should either be a compiled regex object or a
195
+ string containing a regex. If both 'body' and 'headers' are None,
196
+ preprocesses an empty file -- which can be useful to determine the
197
+ symbols the preprocessor and compiler set by default.
198
+ """
199
+ self._check_compiler()
200
+ src, out = self._preprocess(body, headers, include_dirs, lang)
201
+
202
+ if isinstance(pattern, str):
203
+ pattern = re.compile(pattern)
204
+
205
+ with open(out) as file:
206
+ match = False
207
+ while True:
208
+ line = file.readline()
209
+ if line == '':
210
+ break
211
+ if pattern.search(line):
212
+ match = True
213
+ break
214
+
215
+ self._clean()
216
+ return match
217
+
218
+ def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
219
+ """Try to compile a source file built from 'body' and 'headers'.
220
+ Return true on success, false otherwise.
221
+ """
222
+ from distutils.ccompiler import CompileError
223
+ self._check_compiler()
224
+ try:
225
+ self._compile(body, headers, include_dirs, lang)
226
+ ok = True
227
+ except CompileError:
228
+ ok = False
229
+
230
+ log.info(ok and "success!" or "failure.")
231
+ self._clean()
232
+ return ok
233
+
234
+ def try_link(self, body, headers=None, include_dirs=None, libraries=None,
235
+ library_dirs=None, lang="c"):
236
+ """Try to compile and link a source file, built from 'body' and
237
+ 'headers', to executable form. Return true on success, false
238
+ otherwise.
239
+ """
240
+ from distutils.ccompiler import CompileError, LinkError
241
+ self._check_compiler()
242
+ try:
243
+ self._link(body, headers, include_dirs,
244
+ libraries, library_dirs, lang)
245
+ ok = True
246
+ except (CompileError, LinkError):
247
+ ok = False
248
+
249
+ log.info(ok and "success!" or "failure.")
250
+ self._clean()
251
+ return ok
252
+
253
+ def try_run(self, body, headers=None, include_dirs=None, libraries=None,
254
+ library_dirs=None, lang="c"):
255
+ """Try to compile, link to an executable, and run a program
256
+ built from 'body' and 'headers'. Return true on success, false
257
+ otherwise.
258
+ """
259
+ from distutils.ccompiler import CompileError, LinkError
260
+ self._check_compiler()
261
+ try:
262
+ src, obj, exe = self._link(body, headers, include_dirs,
263
+ libraries, library_dirs, lang)
264
+ self.spawn([exe])
265
+ ok = True
266
+ except (CompileError, LinkError, DistutilsExecError):
267
+ ok = False
268
+
269
+ log.info(ok and "success!" or "failure.")
270
+ self._clean()
271
+ return ok
272
+
273
+
274
+ # -- High-level methods --------------------------------------------
275
+ # (these are the ones that are actually likely to be useful
276
+ # when implementing a real-world config command!)
277
+
278
+ def check_func(self, func, headers=None, include_dirs=None,
279
+ libraries=None, library_dirs=None, decl=0, call=0):
280
+ """Determine if function 'func' is available by constructing a
281
+ source file that refers to 'func', and compiles and links it.
282
+ If everything succeeds, returns true; otherwise returns false.
283
+
284
+ The constructed source file starts out by including the header
285
+ files listed in 'headers'. If 'decl' is true, it then declares
286
+ 'func' (as "int func()"); you probably shouldn't supply 'headers'
287
+ and set 'decl' true in the same call, or you might get errors about
288
+ a conflicting declarations for 'func'. Finally, the constructed
289
+ 'main()' function either references 'func' or (if 'call' is true)
290
+ calls it. 'libraries' and 'library_dirs' are used when
291
+ linking.
292
+ """
293
+ self._check_compiler()
294
+ body = []
295
+ if decl:
296
+ body.append("int %s ();" % func)
297
+ body.append("int main () {")
298
+ if call:
299
+ body.append(" %s();" % func)
300
+ else:
301
+ body.append(" %s;" % func)
302
+ body.append("}")
303
+ body = "\n".join(body) + "\n"
304
+
305
+ return self.try_link(body, headers, include_dirs,
306
+ libraries, library_dirs)
307
+
308
+ def check_lib(self, library, library_dirs=None, headers=None,
309
+ include_dirs=None, other_libraries=[]):
310
+ """Determine if 'library' is available to be linked against,
311
+ without actually checking that any particular symbols are provided
312
+ by it. 'headers' will be used in constructing the source file to
313
+ be compiled, but the only effect of this is to check if all the
314
+ header files listed are available. Any libraries listed in
315
+ 'other_libraries' will be included in the link, in case 'library'
316
+ has symbols that depend on other libraries.
317
+ """
318
+ self._check_compiler()
319
+ return self.try_link("int main (void) { }", headers, include_dirs,
320
+ [library] + other_libraries, library_dirs)
321
+
322
+ def check_header(self, header, include_dirs=None, library_dirs=None,
323
+ lang="c"):
324
+ """Determine if the system header file named by 'header_file'
325
+ exists and can be found by the preprocessor; return true if so,
326
+ false otherwise.
327
+ """
328
+ return self.try_cpp(body="/* No body */", headers=[header],
329
+ include_dirs=include_dirs)
330
+
331
+ def dump_file(filename, head=None):
332
+ """Dumps a file content into log.info.
333
+
334
+ If head is not None, will be dumped before the file content.
335
+ """
336
+ if head is None:
337
+ log.info('%s', filename)
338
+ else:
339
+ log.info(head)
340
+ file = open(filename)
341
+ try:
342
+ log.info(file.read())
343
+ finally:
344
+ file.close()
parrot/lib/python3.10/distutils/command/install_egg_info.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_egg_info
2
+
3
+ Implements the Distutils 'install_egg_info' command, for installing
4
+ a package's PKG-INFO metadata."""
5
+
6
+
7
+ from distutils.cmd import Command
8
+ from distutils import log, dir_util
9
+ import os, sys, re
10
+
11
+ class install_egg_info(Command):
12
+ """Install an .egg-info file for the package"""
13
+
14
+ description = "Install package's PKG-INFO metadata as an .egg-info file"
15
+ user_options = [
16
+ ('install-dir=', 'd', "directory to install to"),
17
+ ]
18
+
19
+ def initialize_options(self):
20
+ self.install_dir = None
21
+
22
+ def finalize_options(self):
23
+ self.set_undefined_options('install_lib',('install_dir','install_dir'))
24
+ basename = "%s-%s-py%d.%d.egg-info" % (
25
+ to_filename(safe_name(self.distribution.get_name())),
26
+ to_filename(safe_version(self.distribution.get_version())),
27
+ *sys.version_info[:2]
28
+ )
29
+ self.target = os.path.join(self.install_dir, basename)
30
+ self.outputs = [self.target]
31
+
32
+ def run(self):
33
+ target = self.target
34
+ if os.path.isdir(target) and not os.path.islink(target):
35
+ dir_util.remove_tree(target, dry_run=self.dry_run)
36
+ elif os.path.exists(target):
37
+ self.execute(os.unlink,(self.target,),"Removing "+target)
38
+ elif not os.path.isdir(self.install_dir):
39
+ self.execute(os.makedirs, (self.install_dir,),
40
+ "Creating "+self.install_dir)
41
+ log.info("Writing %s", target)
42
+ if not self.dry_run:
43
+ with open(target, 'w', encoding='UTF-8') as f:
44
+ self.distribution.metadata.write_pkg_file(f)
45
+
46
+ def get_outputs(self):
47
+ return self.outputs
48
+
49
+
50
+ # The following routines are taken from setuptools' pkg_resources module and
51
+ # can be replaced by importing them from pkg_resources once it is included
52
+ # in the stdlib.
53
+
54
+ def safe_name(name):
55
+ """Convert an arbitrary string to a standard distribution name
56
+
57
+ Any runs of non-alphanumeric/. characters are replaced with a single '-'.
58
+ """
59
+ return re.sub('[^A-Za-z0-9.]+', '-', name)
60
+
61
+
62
+ def safe_version(version):
63
+ """Convert an arbitrary string to a standard version string
64
+
65
+ Spaces become dots, and all other non-alphanumeric characters become
66
+ dashes, with runs of multiple dashes condensed to a single dash.
67
+ """
68
+ version = version.replace(' ','.')
69
+ return re.sub('[^A-Za-z0-9.]+', '-', version)
70
+
71
+
72
+ def to_filename(name):
73
+ """Convert a project or version name to its filename-escaped form
74
+
75
+ Any '-' characters are currently replaced with '_'.
76
+ """
77
+ return name.replace('-','_')
parrot/lib/python3.10/distutils/command/install_lib.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_lib
2
+
3
+ Implements the Distutils 'install_lib' command
4
+ (install all Python modules)."""
5
+
6
+ import os
7
+ import importlib.util
8
+ import sys
9
+
10
+ from distutils.core import Command
11
+ from distutils.errors import DistutilsOptionError
12
+
13
+
14
+ # Extension for Python source files.
15
+ PYTHON_SOURCE_EXTENSION = ".py"
16
+
17
+ class install_lib(Command):
18
+
19
+ description = "install all Python modules (extensions and pure Python)"
20
+
21
+ # The byte-compilation options are a tad confusing. Here are the
22
+ # possible scenarios:
23
+ # 1) no compilation at all (--no-compile --no-optimize)
24
+ # 2) compile .pyc only (--compile --no-optimize; default)
25
+ # 3) compile .pyc and "opt-1" .pyc (--compile --optimize)
26
+ # 4) compile "opt-1" .pyc only (--no-compile --optimize)
27
+ # 5) compile .pyc and "opt-2" .pyc (--compile --optimize-more)
28
+ # 6) compile "opt-2" .pyc only (--no-compile --optimize-more)
29
+ #
30
+ # The UI for this is two options, 'compile' and 'optimize'.
31
+ # 'compile' is strictly boolean, and only decides whether to
32
+ # generate .pyc files. 'optimize' is three-way (0, 1, or 2), and
33
+ # decides both whether to generate .pyc files and what level of
34
+ # optimization to use.
35
+
36
+ user_options = [
37
+ ('install-dir=', 'd', "directory to install to"),
38
+ ('build-dir=','b', "build directory (where to install from)"),
39
+ ('force', 'f', "force installation (overwrite existing files)"),
40
+ ('compile', 'c', "compile .py to .pyc [default]"),
41
+ ('no-compile', None, "don't compile .py files"),
42
+ ('optimize=', 'O',
43
+ "also compile with optimization: -O1 for \"python -O\", "
44
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
45
+ ('skip-build', None, "skip the build steps"),
46
+ ]
47
+
48
+ boolean_options = ['force', 'compile', 'skip-build']
49
+ negative_opt = {'no-compile' : 'compile'}
50
+
51
+ def initialize_options(self):
52
+ # let the 'install' command dictate our installation directory
53
+ self.install_dir = None
54
+ self.build_dir = None
55
+ self.force = 0
56
+ self.compile = None
57
+ self.optimize = None
58
+ self.skip_build = None
59
+
60
+ def finalize_options(self):
61
+ # Get all the information we need to install pure Python modules
62
+ # from the umbrella 'install' command -- build (source) directory,
63
+ # install (target) directory, and whether to compile .py files.
64
+ self.set_undefined_options('install',
65
+ ('build_lib', 'build_dir'),
66
+ ('install_lib', 'install_dir'),
67
+ ('force', 'force'),
68
+ ('compile', 'compile'),
69
+ ('optimize', 'optimize'),
70
+ ('skip_build', 'skip_build'),
71
+ )
72
+
73
+ if self.compile is None:
74
+ self.compile = True
75
+ if self.optimize is None:
76
+ self.optimize = False
77
+
78
+ if not isinstance(self.optimize, int):
79
+ try:
80
+ self.optimize = int(self.optimize)
81
+ if self.optimize not in (0, 1, 2):
82
+ raise AssertionError
83
+ except (ValueError, AssertionError):
84
+ raise DistutilsOptionError("optimize must be 0, 1, or 2")
85
+
86
+ def run(self):
87
+ # Make sure we have built everything we need first
88
+ self.build()
89
+
90
+ # Install everything: simply dump the entire contents of the build
91
+ # directory to the installation directory (that's the beauty of
92
+ # having a build directory!)
93
+ outfiles = self.install()
94
+
95
+ # (Optionally) compile .py to .pyc
96
+ if outfiles is not None and self.distribution.has_pure_modules():
97
+ self.byte_compile(outfiles)
98
+
99
+ # -- Top-level worker functions ------------------------------------
100
+ # (called from 'run()')
101
+
102
+ def build(self):
103
+ if not self.skip_build:
104
+ if self.distribution.has_pure_modules():
105
+ self.run_command('build_py')
106
+ if self.distribution.has_ext_modules():
107
+ self.run_command('build_ext')
108
+
109
+ def install(self):
110
+ if os.path.isdir(self.build_dir):
111
+ outfiles = self.copy_tree(self.build_dir, self.install_dir)
112
+ else:
113
+ self.warn("'%s' does not exist -- no Python modules to install" %
114
+ self.build_dir)
115
+ return
116
+ return outfiles
117
+
118
+ def byte_compile(self, files):
119
+ if sys.dont_write_bytecode:
120
+ self.warn('byte-compiling is disabled, skipping.')
121
+ return
122
+
123
+ from distutils.util import byte_compile
124
+
125
+ # Get the "--root" directory supplied to the "install" command,
126
+ # and use it as a prefix to strip off the purported filename
127
+ # encoded in bytecode files. This is far from complete, but it
128
+ # should at least generate usable bytecode in RPM distributions.
129
+ install_root = self.get_finalized_command('install').root
130
+
131
+ if self.compile:
132
+ byte_compile(files, optimize=0,
133
+ force=self.force, prefix=install_root,
134
+ dry_run=self.dry_run)
135
+ if self.optimize > 0:
136
+ byte_compile(files, optimize=self.optimize,
137
+ force=self.force, prefix=install_root,
138
+ verbose=self.verbose, dry_run=self.dry_run)
139
+
140
+
141
+ # -- Utility methods -----------------------------------------------
142
+
143
+ def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
144
+ if not has_any:
145
+ return []
146
+
147
+ build_cmd = self.get_finalized_command(build_cmd)
148
+ build_files = build_cmd.get_outputs()
149
+ build_dir = getattr(build_cmd, cmd_option)
150
+
151
+ prefix_len = len(build_dir) + len(os.sep)
152
+ outputs = []
153
+ for file in build_files:
154
+ outputs.append(os.path.join(output_dir, file[prefix_len:]))
155
+
156
+ return outputs
157
+
158
+ def _bytecode_filenames(self, py_filenames):
159
+ bytecode_files = []
160
+ for py_file in py_filenames:
161
+ # Since build_py handles package data installation, the
162
+ # list of outputs can contain more than just .py files.
163
+ # Make sure we only report bytecode for the .py files.
164
+ ext = os.path.splitext(os.path.normcase(py_file))[1]
165
+ if ext != PYTHON_SOURCE_EXTENSION:
166
+ continue
167
+ if self.compile:
168
+ bytecode_files.append(importlib.util.cache_from_source(
169
+ py_file, optimization=''))
170
+ if self.optimize > 0:
171
+ bytecode_files.append(importlib.util.cache_from_source(
172
+ py_file, optimization=self.optimize))
173
+
174
+ return bytecode_files
175
+
176
+
177
+ # -- External interface --------------------------------------------
178
+ # (called by outsiders)
179
+
180
+ def get_outputs(self):
181
+ """Return the list of files that would be installed if this command
182
+ were actually run. Not affected by the "dry-run" flag or whether
183
+ modules have actually been built yet.
184
+ """
185
+ pure_outputs = \
186
+ self._mutate_outputs(self.distribution.has_pure_modules(),
187
+ 'build_py', 'build_lib',
188
+ self.install_dir)
189
+ if self.compile:
190
+ bytecode_outputs = self._bytecode_filenames(pure_outputs)
191
+ else:
192
+ bytecode_outputs = []
193
+
194
+ ext_outputs = \
195
+ self._mutate_outputs(self.distribution.has_ext_modules(),
196
+ 'build_ext', 'build_lib',
197
+ self.install_dir)
198
+
199
+ return pure_outputs + bytecode_outputs + ext_outputs
200
+
201
+ def get_inputs(self):
202
+ """Get the list of files that are input to this command, ie. the
203
+ files that get installed as they are named in the build tree.
204
+ The files in this list correspond one-to-one to the output
205
+ filenames returned by 'get_outputs()'.
206
+ """
207
+ inputs = []
208
+
209
+ if self.distribution.has_pure_modules():
210
+ build_py = self.get_finalized_command('build_py')
211
+ inputs.extend(build_py.get_outputs())
212
+
213
+ if self.distribution.has_ext_modules():
214
+ build_ext = self.get_finalized_command('build_ext')
215
+ inputs.extend(build_ext.get_outputs())
216
+
217
+ return inputs
parrot/lib/python3.10/distutils/command/register.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.register
2
+
3
+ Implements the Distutils 'register' command (register with the repository).
4
+ """
5
+
6
+ # created 2002/10/21, Richard Jones
7
+
8
+ import getpass
9
+ import io
10
+ import urllib.parse, urllib.request
11
+ from warnings import warn
12
+
13
+ from distutils.core import PyPIRCCommand
14
+ from distutils.errors import *
15
+ from distutils import log
16
+
17
+ class register(PyPIRCCommand):
18
+
19
+ description = ("register the distribution with the Python package index")
20
+ user_options = PyPIRCCommand.user_options + [
21
+ ('list-classifiers', None,
22
+ 'list the valid Trove classifiers'),
23
+ ('strict', None ,
24
+ 'Will stop the registering if the meta-data are not fully compliant')
25
+ ]
26
+ boolean_options = PyPIRCCommand.boolean_options + [
27
+ 'verify', 'list-classifiers', 'strict']
28
+
29
+ sub_commands = [('check', lambda self: True)]
30
+
31
+ def initialize_options(self):
32
+ PyPIRCCommand.initialize_options(self)
33
+ self.list_classifiers = 0
34
+ self.strict = 0
35
+
36
+ def finalize_options(self):
37
+ PyPIRCCommand.finalize_options(self)
38
+ # setting options for the `check` subcommand
39
+ check_options = {'strict': ('register', self.strict),
40
+ 'restructuredtext': ('register', 1)}
41
+ self.distribution.command_options['check'] = check_options
42
+
43
+ def run(self):
44
+ self.finalize_options()
45
+ self._set_config()
46
+
47
+ # Run sub commands
48
+ for cmd_name in self.get_sub_commands():
49
+ self.run_command(cmd_name)
50
+
51
+ if self.dry_run:
52
+ self.verify_metadata()
53
+ elif self.list_classifiers:
54
+ self.classifiers()
55
+ else:
56
+ self.send_metadata()
57
+
58
+ def check_metadata(self):
59
+ """Deprecated API."""
60
+ warn("distutils.command.register.check_metadata is deprecated, \
61
+ use the check command instead", PendingDeprecationWarning)
62
+ check = self.distribution.get_command_obj('check')
63
+ check.ensure_finalized()
64
+ check.strict = self.strict
65
+ check.restructuredtext = 1
66
+ check.run()
67
+
68
+ def _set_config(self):
69
+ ''' Reads the configuration file and set attributes.
70
+ '''
71
+ config = self._read_pypirc()
72
+ if config != {}:
73
+ self.username = config['username']
74
+ self.password = config['password']
75
+ self.repository = config['repository']
76
+ self.realm = config['realm']
77
+ self.has_config = True
78
+ else:
79
+ if self.repository not in ('pypi', self.DEFAULT_REPOSITORY):
80
+ raise ValueError('%s not found in .pypirc' % self.repository)
81
+ if self.repository == 'pypi':
82
+ self.repository = self.DEFAULT_REPOSITORY
83
+ self.has_config = False
84
+
85
+ def classifiers(self):
86
+ ''' Fetch the list of classifiers from the server.
87
+ '''
88
+ url = self.repository+'?:action=list_classifiers'
89
+ response = urllib.request.urlopen(url)
90
+ log.info(self._read_pypi_response(response))
91
+
92
+ def verify_metadata(self):
93
+ ''' Send the metadata to the package index server to be checked.
94
+ '''
95
+ # send the info to the server and report the result
96
+ (code, result) = self.post_to_server(self.build_post_data('verify'))
97
+ log.info('Server response (%s): %s', code, result)
98
+
99
+ def send_metadata(self):
100
+ ''' Send the metadata to the package index server.
101
+
102
+ Well, do the following:
103
+ 1. figure who the user is, and then
104
+ 2. send the data as a Basic auth'ed POST.
105
+
106
+ First we try to read the username/password from $HOME/.pypirc,
107
+ which is a ConfigParser-formatted file with a section
108
+ [distutils] containing username and password entries (both
109
+ in clear text). Eg:
110
+
111
+ [distutils]
112
+ index-servers =
113
+ pypi
114
+
115
+ [pypi]
116
+ username: fred
117
+ password: sekrit
118
+
119
+ Otherwise, to figure who the user is, we offer the user three
120
+ choices:
121
+
122
+ 1. use existing login,
123
+ 2. register as a new user, or
124
+ 3. set the password to a random string and email the user.
125
+
126
+ '''
127
+ # see if we can short-cut and get the username/password from the
128
+ # config
129
+ if self.has_config:
130
+ choice = '1'
131
+ username = self.username
132
+ password = self.password
133
+ else:
134
+ choice = 'x'
135
+ username = password = ''
136
+
137
+ # get the user's login info
138
+ choices = '1 2 3 4'.split()
139
+ while choice not in choices:
140
+ self.announce('''\
141
+ We need to know who you are, so please choose either:
142
+ 1. use your existing login,
143
+ 2. register as a new user,
144
+ 3. have the server generate a new password for you (and email it to you), or
145
+ 4. quit
146
+ Your selection [default 1]: ''', log.INFO)
147
+ choice = input()
148
+ if not choice:
149
+ choice = '1'
150
+ elif choice not in choices:
151
+ print('Please choose one of the four options!')
152
+
153
+ if choice == '1':
154
+ # get the username and password
155
+ while not username:
156
+ username = input('Username: ')
157
+ while not password:
158
+ password = getpass.getpass('Password: ')
159
+
160
+ # set up the authentication
161
+ auth = urllib.request.HTTPPasswordMgr()
162
+ host = urllib.parse.urlparse(self.repository)[1]
163
+ auth.add_password(self.realm, host, username, password)
164
+ # send the info to the server and report the result
165
+ code, result = self.post_to_server(self.build_post_data('submit'),
166
+ auth)
167
+ self.announce('Server response (%s): %s' % (code, result),
168
+ log.INFO)
169
+
170
+ # possibly save the login
171
+ if code == 200:
172
+ if self.has_config:
173
+ # sharing the password in the distribution instance
174
+ # so the upload command can reuse it
175
+ self.distribution.password = password
176
+ else:
177
+ self.announce(('I can store your PyPI login so future '
178
+ 'submissions will be faster.'), log.INFO)
179
+ self.announce('(the login will be stored in %s)' % \
180
+ self._get_rc_file(), log.INFO)
181
+ choice = 'X'
182
+ while choice.lower() not in 'yn':
183
+ choice = input('Save your login (y/N)?')
184
+ if not choice:
185
+ choice = 'n'
186
+ if choice.lower() == 'y':
187
+ self._store_pypirc(username, password)
188
+
189
+ elif choice == '2':
190
+ data = {':action': 'user'}
191
+ data['name'] = data['password'] = data['email'] = ''
192
+ data['confirm'] = None
193
+ while not data['name']:
194
+ data['name'] = input('Username: ')
195
+ while data['password'] != data['confirm']:
196
+ while not data['password']:
197
+ data['password'] = getpass.getpass('Password: ')
198
+ while not data['confirm']:
199
+ data['confirm'] = getpass.getpass(' Confirm: ')
200
+ if data['password'] != data['confirm']:
201
+ data['password'] = ''
202
+ data['confirm'] = None
203
+ print("Password and confirm don't match!")
204
+ while not data['email']:
205
+ data['email'] = input(' EMail: ')
206
+ code, result = self.post_to_server(data)
207
+ if code != 200:
208
+ log.info('Server response (%s): %s', code, result)
209
+ else:
210
+ log.info('You will receive an email shortly.')
211
+ log.info(('Follow the instructions in it to '
212
+ 'complete registration.'))
213
+ elif choice == '3':
214
+ data = {':action': 'password_reset'}
215
+ data['email'] = ''
216
+ while not data['email']:
217
+ data['email'] = input('Your email address: ')
218
+ code, result = self.post_to_server(data)
219
+ log.info('Server response (%s): %s', code, result)
220
+
221
+ def build_post_data(self, action):
222
+ # figure the data to send - the metadata plus some additional
223
+ # information used by the package server
224
+ meta = self.distribution.metadata
225
+ data = {
226
+ ':action': action,
227
+ 'metadata_version' : '1.0',
228
+ 'name': meta.get_name(),
229
+ 'version': meta.get_version(),
230
+ 'summary': meta.get_description(),
231
+ 'home_page': meta.get_url(),
232
+ 'author': meta.get_contact(),
233
+ 'author_email': meta.get_contact_email(),
234
+ 'license': meta.get_licence(),
235
+ 'description': meta.get_long_description(),
236
+ 'keywords': meta.get_keywords(),
237
+ 'platform': meta.get_platforms(),
238
+ 'classifiers': meta.get_classifiers(),
239
+ 'download_url': meta.get_download_url(),
240
+ # PEP 314
241
+ 'provides': meta.get_provides(),
242
+ 'requires': meta.get_requires(),
243
+ 'obsoletes': meta.get_obsoletes(),
244
+ }
245
+ if data['provides'] or data['requires'] or data['obsoletes']:
246
+ data['metadata_version'] = '1.1'
247
+ return data
248
+
249
+ def post_to_server(self, data, auth=None):
250
+ ''' Post a query to the server, and return a string response.
251
+ '''
252
+ if 'name' in data:
253
+ self.announce('Registering %s to %s' % (data['name'],
254
+ self.repository),
255
+ log.INFO)
256
+ # Build up the MIME payload for the urllib2 POST data
257
+ boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
258
+ sep_boundary = '\n--' + boundary
259
+ end_boundary = sep_boundary + '--'
260
+ body = io.StringIO()
261
+ for key, value in data.items():
262
+ # handle multiple entries for the same name
263
+ if type(value) not in (type([]), type( () )):
264
+ value = [value]
265
+ for value in value:
266
+ value = str(value)
267
+ body.write(sep_boundary)
268
+ body.write('\nContent-Disposition: form-data; name="%s"'%key)
269
+ body.write("\n\n")
270
+ body.write(value)
271
+ if value and value[-1] == '\r':
272
+ body.write('\n') # write an extra newline (lurve Macs)
273
+ body.write(end_boundary)
274
+ body.write("\n")
275
+ body = body.getvalue().encode("utf-8")
276
+
277
+ # build the Request
278
+ headers = {
279
+ 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary,
280
+ 'Content-length': str(len(body))
281
+ }
282
+ req = urllib.request.Request(self.repository, body, headers)
283
+
284
+ # handle HTTP and include the Basic Auth handler
285
+ opener = urllib.request.build_opener(
286
+ urllib.request.HTTPBasicAuthHandler(password_mgr=auth)
287
+ )
288
+ data = ''
289
+ try:
290
+ result = opener.open(req)
291
+ except urllib.error.HTTPError as e:
292
+ if self.show_response:
293
+ data = e.fp.read()
294
+ result = e.code, e.msg
295
+ except urllib.error.URLError as e:
296
+ result = 500, str(e)
297
+ else:
298
+ if self.show_response:
299
+ data = self._read_pypi_response(result)
300
+ result = 200, 'OK'
301
+ if self.show_response:
302
+ msg = '\n'.join(('-' * 75, data, '-' * 75))
303
+ self.announce(msg, log.INFO)
304
+ return result
parrot/lib/python3.10/distutils/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.65 kB). View file
 
parrot/lib/python3.10/distutils/tests/__pycache__/test_install.cpython-310.pyc ADDED
Binary file (7.63 kB). View file
 
parrot/lib/python3.10/ensurepip/__pycache__/_uninstall.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
parrot/lib/python3.10/json/__pycache__/encoder.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
parrot/lib/python3.10/json/__pycache__/scanner.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
parrot/lib/python3.10/json/encoder.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of JSONEncoder
2
+ """
3
+ import re
4
+
5
+ try:
6
+ from _json import encode_basestring_ascii as c_encode_basestring_ascii
7
+ except ImportError:
8
+ c_encode_basestring_ascii = None
9
+ try:
10
+ from _json import encode_basestring as c_encode_basestring
11
+ except ImportError:
12
+ c_encode_basestring = None
13
+ try:
14
+ from _json import make_encoder as c_make_encoder
15
+ except ImportError:
16
+ c_make_encoder = None
17
+
18
+ ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
19
+ ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
20
+ HAS_UTF8 = re.compile(b'[\x80-\xff]')
21
+ ESCAPE_DCT = {
22
+ '\\': '\\\\',
23
+ '"': '\\"',
24
+ '\b': '\\b',
25
+ '\f': '\\f',
26
+ '\n': '\\n',
27
+ '\r': '\\r',
28
+ '\t': '\\t',
29
+ }
30
+ for i in range(0x20):
31
+ ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
32
+ #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
33
+
34
+ INFINITY = float('inf')
35
+
36
+ def py_encode_basestring(s):
37
+ """Return a JSON representation of a Python string
38
+
39
+ """
40
+ def replace(match):
41
+ return ESCAPE_DCT[match.group(0)]
42
+ return '"' + ESCAPE.sub(replace, s) + '"'
43
+
44
+
45
+ encode_basestring = (c_encode_basestring or py_encode_basestring)
46
+
47
+
48
+ def py_encode_basestring_ascii(s):
49
+ """Return an ASCII-only JSON representation of a Python string
50
+
51
+ """
52
+ def replace(match):
53
+ s = match.group(0)
54
+ try:
55
+ return ESCAPE_DCT[s]
56
+ except KeyError:
57
+ n = ord(s)
58
+ if n < 0x10000:
59
+ return '\\u{0:04x}'.format(n)
60
+ #return '\\u%04x' % (n,)
61
+ else:
62
+ # surrogate pair
63
+ n -= 0x10000
64
+ s1 = 0xd800 | ((n >> 10) & 0x3ff)
65
+ s2 = 0xdc00 | (n & 0x3ff)
66
+ return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
67
+ return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
68
+
69
+
70
+ encode_basestring_ascii = (
71
+ c_encode_basestring_ascii or py_encode_basestring_ascii)
72
+
73
+ class JSONEncoder(object):
74
+ """Extensible JSON <https://json.org> encoder for Python data structures.
75
+
76
+ Supports the following objects and types by default:
77
+
78
+ +-------------------+---------------+
79
+ | Python | JSON |
80
+ +===================+===============+
81
+ | dict | object |
82
+ +-------------------+---------------+
83
+ | list, tuple | array |
84
+ +-------------------+---------------+
85
+ | str | string |
86
+ +-------------------+---------------+
87
+ | int, float | number |
88
+ +-------------------+---------------+
89
+ | True | true |
90
+ +-------------------+---------------+
91
+ | False | false |
92
+ +-------------------+---------------+
93
+ | None | null |
94
+ +-------------------+---------------+
95
+
96
+ To extend this to recognize other objects, subclass and implement a
97
+ ``.default()`` method with another method that returns a serializable
98
+ object for ``o`` if possible, otherwise it should call the superclass
99
+ implementation (to raise ``TypeError``).
100
+
101
+ """
102
+ item_separator = ', '
103
+ key_separator = ': '
104
+ def __init__(self, *, skipkeys=False, ensure_ascii=True,
105
+ check_circular=True, allow_nan=True, sort_keys=False,
106
+ indent=None, separators=None, default=None):
107
+ """Constructor for JSONEncoder, with sensible defaults.
108
+
109
+ If skipkeys is false, then it is a TypeError to attempt
110
+ encoding of keys that are not str, int, float or None. If
111
+ skipkeys is True, such items are simply skipped.
112
+
113
+ If ensure_ascii is true, the output is guaranteed to be str
114
+ objects with all incoming non-ASCII characters escaped. If
115
+ ensure_ascii is false, the output can contain non-ASCII characters.
116
+
117
+ If check_circular is true, then lists, dicts, and custom encoded
118
+ objects will be checked for circular references during encoding to
119
+ prevent an infinite recursion (which would cause an RecursionError).
120
+ Otherwise, no such check takes place.
121
+
122
+ If allow_nan is true, then NaN, Infinity, and -Infinity will be
123
+ encoded as such. This behavior is not JSON specification compliant,
124
+ but is consistent with most JavaScript based encoders and decoders.
125
+ Otherwise, it will be a ValueError to encode such floats.
126
+
127
+ If sort_keys is true, then the output of dictionaries will be
128
+ sorted by key; this is useful for regression tests to ensure
129
+ that JSON serializations can be compared on a day-to-day basis.
130
+
131
+ If indent is a non-negative integer, then JSON array
132
+ elements and object members will be pretty-printed with that
133
+ indent level. An indent level of 0 will only insert newlines.
134
+ None is the most compact representation.
135
+
136
+ If specified, separators should be an (item_separator, key_separator)
137
+ tuple. The default is (', ', ': ') if *indent* is ``None`` and
138
+ (',', ': ') otherwise. To get the most compact JSON representation,
139
+ you should specify (',', ':') to eliminate whitespace.
140
+
141
+ If specified, default is a function that gets called for objects
142
+ that can't otherwise be serialized. It should return a JSON encodable
143
+ version of the object or raise a ``TypeError``.
144
+
145
+ """
146
+
147
+ self.skipkeys = skipkeys
148
+ self.ensure_ascii = ensure_ascii
149
+ self.check_circular = check_circular
150
+ self.allow_nan = allow_nan
151
+ self.sort_keys = sort_keys
152
+ self.indent = indent
153
+ if separators is not None:
154
+ self.item_separator, self.key_separator = separators
155
+ elif indent is not None:
156
+ self.item_separator = ','
157
+ if default is not None:
158
+ self.default = default
159
+
160
+ def default(self, o):
161
+ """Implement this method in a subclass such that it returns
162
+ a serializable object for ``o``, or calls the base implementation
163
+ (to raise a ``TypeError``).
164
+
165
+ For example, to support arbitrary iterators, you could
166
+ implement default like this::
167
+
168
+ def default(self, o):
169
+ try:
170
+ iterable = iter(o)
171
+ except TypeError:
172
+ pass
173
+ else:
174
+ return list(iterable)
175
+ # Let the base class default method raise the TypeError
176
+ return JSONEncoder.default(self, o)
177
+
178
+ """
179
+ raise TypeError(f'Object of type {o.__class__.__name__} '
180
+ f'is not JSON serializable')
181
+
182
+ def encode(self, o):
183
+ """Return a JSON string representation of a Python data structure.
184
+
185
+ >>> from json.encoder import JSONEncoder
186
+ >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
187
+ '{"foo": ["bar", "baz"]}'
188
+
189
+ """
190
+ # This is for extremely simple cases and benchmarks.
191
+ if isinstance(o, str):
192
+ if self.ensure_ascii:
193
+ return encode_basestring_ascii(o)
194
+ else:
195
+ return encode_basestring(o)
196
+ # This doesn't pass the iterator directly to ''.join() because the
197
+ # exceptions aren't as detailed. The list call should be roughly
198
+ # equivalent to the PySequence_Fast that ''.join() would do.
199
+ chunks = self.iterencode(o, _one_shot=True)
200
+ if not isinstance(chunks, (list, tuple)):
201
+ chunks = list(chunks)
202
+ return ''.join(chunks)
203
+
204
+ def iterencode(self, o, _one_shot=False):
205
+ """Encode the given object and yield each string
206
+ representation as available.
207
+
208
+ For example::
209
+
210
+ for chunk in JSONEncoder().iterencode(bigobject):
211
+ mysocket.write(chunk)
212
+
213
+ """
214
+ if self.check_circular:
215
+ markers = {}
216
+ else:
217
+ markers = None
218
+ if self.ensure_ascii:
219
+ _encoder = encode_basestring_ascii
220
+ else:
221
+ _encoder = encode_basestring
222
+
223
+ def floatstr(o, allow_nan=self.allow_nan,
224
+ _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
225
+ # Check for specials. Note that this type of test is processor
226
+ # and/or platform-specific, so do tests which don't depend on the
227
+ # internals.
228
+
229
+ if o != o:
230
+ text = 'NaN'
231
+ elif o == _inf:
232
+ text = 'Infinity'
233
+ elif o == _neginf:
234
+ text = '-Infinity'
235
+ else:
236
+ return _repr(o)
237
+
238
+ if not allow_nan:
239
+ raise ValueError(
240
+ "Out of range float values are not JSON compliant: " +
241
+ repr(o))
242
+
243
+ return text
244
+
245
+
246
+ if (_one_shot and c_make_encoder is not None
247
+ and self.indent is None):
248
+ _iterencode = c_make_encoder(
249
+ markers, self.default, _encoder, self.indent,
250
+ self.key_separator, self.item_separator, self.sort_keys,
251
+ self.skipkeys, self.allow_nan)
252
+ else:
253
+ _iterencode = _make_iterencode(
254
+ markers, self.default, _encoder, self.indent, floatstr,
255
+ self.key_separator, self.item_separator, self.sort_keys,
256
+ self.skipkeys, _one_shot)
257
+ return _iterencode(o, 0)
258
+
259
+ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
260
+ _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
261
+ ## HACK: hand-optimized bytecode; turn globals into locals
262
+ ValueError=ValueError,
263
+ dict=dict,
264
+ float=float,
265
+ id=id,
266
+ int=int,
267
+ isinstance=isinstance,
268
+ list=list,
269
+ str=str,
270
+ tuple=tuple,
271
+ _intstr=int.__repr__,
272
+ ):
273
+
274
+ if _indent is not None and not isinstance(_indent, str):
275
+ _indent = ' ' * _indent
276
+
277
+ def _iterencode_list(lst, _current_indent_level):
278
+ if not lst:
279
+ yield '[]'
280
+ return
281
+ if markers is not None:
282
+ markerid = id(lst)
283
+ if markerid in markers:
284
+ raise ValueError("Circular reference detected")
285
+ markers[markerid] = lst
286
+ buf = '['
287
+ if _indent is not None:
288
+ _current_indent_level += 1
289
+ newline_indent = '\n' + _indent * _current_indent_level
290
+ separator = _item_separator + newline_indent
291
+ buf += newline_indent
292
+ else:
293
+ newline_indent = None
294
+ separator = _item_separator
295
+ first = True
296
+ for value in lst:
297
+ if first:
298
+ first = False
299
+ else:
300
+ buf = separator
301
+ if isinstance(value, str):
302
+ yield buf + _encoder(value)
303
+ elif value is None:
304
+ yield buf + 'null'
305
+ elif value is True:
306
+ yield buf + 'true'
307
+ elif value is False:
308
+ yield buf + 'false'
309
+ elif isinstance(value, int):
310
+ # Subclasses of int/float may override __repr__, but we still
311
+ # want to encode them as integers/floats in JSON. One example
312
+ # within the standard library is IntEnum.
313
+ yield buf + _intstr(value)
314
+ elif isinstance(value, float):
315
+ # see comment above for int
316
+ yield buf + _floatstr(value)
317
+ else:
318
+ yield buf
319
+ if isinstance(value, (list, tuple)):
320
+ chunks = _iterencode_list(value, _current_indent_level)
321
+ elif isinstance(value, dict):
322
+ chunks = _iterencode_dict(value, _current_indent_level)
323
+ else:
324
+ chunks = _iterencode(value, _current_indent_level)
325
+ yield from chunks
326
+ if newline_indent is not None:
327
+ _current_indent_level -= 1
328
+ yield '\n' + _indent * _current_indent_level
329
+ yield ']'
330
+ if markers is not None:
331
+ del markers[markerid]
332
+
333
+ def _iterencode_dict(dct, _current_indent_level):
334
+ if not dct:
335
+ yield '{}'
336
+ return
337
+ if markers is not None:
338
+ markerid = id(dct)
339
+ if markerid in markers:
340
+ raise ValueError("Circular reference detected")
341
+ markers[markerid] = dct
342
+ yield '{'
343
+ if _indent is not None:
344
+ _current_indent_level += 1
345
+ newline_indent = '\n' + _indent * _current_indent_level
346
+ item_separator = _item_separator + newline_indent
347
+ yield newline_indent
348
+ else:
349
+ newline_indent = None
350
+ item_separator = _item_separator
351
+ first = True
352
+ if _sort_keys:
353
+ items = sorted(dct.items())
354
+ else:
355
+ items = dct.items()
356
+ for key, value in items:
357
+ if isinstance(key, str):
358
+ pass
359
+ # JavaScript is weakly typed for these, so it makes sense to
360
+ # also allow them. Many encoders seem to do something like this.
361
+ elif isinstance(key, float):
362
+ # see comment for int/float in _make_iterencode
363
+ key = _floatstr(key)
364
+ elif key is True:
365
+ key = 'true'
366
+ elif key is False:
367
+ key = 'false'
368
+ elif key is None:
369
+ key = 'null'
370
+ elif isinstance(key, int):
371
+ # see comment for int/float in _make_iterencode
372
+ key = _intstr(key)
373
+ elif _skipkeys:
374
+ continue
375
+ else:
376
+ raise TypeError(f'keys must be str, int, float, bool or None, '
377
+ f'not {key.__class__.__name__}')
378
+ if first:
379
+ first = False
380
+ else:
381
+ yield item_separator
382
+ yield _encoder(key)
383
+ yield _key_separator
384
+ if isinstance(value, str):
385
+ yield _encoder(value)
386
+ elif value is None:
387
+ yield 'null'
388
+ elif value is True:
389
+ yield 'true'
390
+ elif value is False:
391
+ yield 'false'
392
+ elif isinstance(value, int):
393
+ # see comment for int/float in _make_iterencode
394
+ yield _intstr(value)
395
+ elif isinstance(value, float):
396
+ # see comment for int/float in _make_iterencode
397
+ yield _floatstr(value)
398
+ else:
399
+ if isinstance(value, (list, tuple)):
400
+ chunks = _iterencode_list(value, _current_indent_level)
401
+ elif isinstance(value, dict):
402
+ chunks = _iterencode_dict(value, _current_indent_level)
403
+ else:
404
+ chunks = _iterencode(value, _current_indent_level)
405
+ yield from chunks
406
+ if newline_indent is not None:
407
+ _current_indent_level -= 1
408
+ yield '\n' + _indent * _current_indent_level
409
+ yield '}'
410
+ if markers is not None:
411
+ del markers[markerid]
412
+
413
+ def _iterencode(o, _current_indent_level):
414
+ if isinstance(o, str):
415
+ yield _encoder(o)
416
+ elif o is None:
417
+ yield 'null'
418
+ elif o is True:
419
+ yield 'true'
420
+ elif o is False:
421
+ yield 'false'
422
+ elif isinstance(o, int):
423
+ # see comment for int/float in _make_iterencode
424
+ yield _intstr(o)
425
+ elif isinstance(o, float):
426
+ # see comment for int/float in _make_iterencode
427
+ yield _floatstr(o)
428
+ elif isinstance(o, (list, tuple)):
429
+ yield from _iterencode_list(o, _current_indent_level)
430
+ elif isinstance(o, dict):
431
+ yield from _iterencode_dict(o, _current_indent_level)
432
+ else:
433
+ if markers is not None:
434
+ markerid = id(o)
435
+ if markerid in markers:
436
+ raise ValueError("Circular reference detected")
437
+ markers[markerid] = o
438
+ o = _default(o)
439
+ yield from _iterencode(o, _current_indent_level)
440
+ if markers is not None:
441
+ del markers[markerid]
442
+ return _iterencode
parrot/lib/python3.10/json/tool.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Command-line tool to validate and pretty-print JSON
2
+
3
+ Usage::
4
+
5
+ $ echo '{"json":"obj"}' | python -m json.tool
6
+ {
7
+ "json": "obj"
8
+ }
9
+ $ echo '{ 1.2:3.4}' | python -m json.tool
10
+ Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
11
+
12
+ """
13
+ import argparse
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+
19
+ def main():
20
+ prog = 'python -m json.tool'
21
+ description = ('A simple command line interface for json module '
22
+ 'to validate and pretty-print JSON objects.')
23
+ parser = argparse.ArgumentParser(prog=prog, description=description)
24
+ parser.add_argument('infile', nargs='?',
25
+ type=argparse.FileType(encoding="utf-8"),
26
+ help='a JSON file to be validated or pretty-printed',
27
+ default=sys.stdin)
28
+ parser.add_argument('outfile', nargs='?',
29
+ type=Path,
30
+ help='write the output of infile to outfile',
31
+ default=None)
32
+ parser.add_argument('--sort-keys', action='store_true', default=False,
33
+ help='sort the output of dictionaries alphabetically by key')
34
+ parser.add_argument('--no-ensure-ascii', dest='ensure_ascii', action='store_false',
35
+ help='disable escaping of non-ASCII characters')
36
+ parser.add_argument('--json-lines', action='store_true', default=False,
37
+ help='parse input using the JSON Lines format. '
38
+ 'Use with --no-indent or --compact to produce valid JSON Lines output.')
39
+ group = parser.add_mutually_exclusive_group()
40
+ group.add_argument('--indent', default=4, type=int,
41
+ help='separate items with newlines and use this number '
42
+ 'of spaces for indentation')
43
+ group.add_argument('--tab', action='store_const', dest='indent',
44
+ const='\t', help='separate items with newlines and use '
45
+ 'tabs for indentation')
46
+ group.add_argument('--no-indent', action='store_const', dest='indent',
47
+ const=None,
48
+ help='separate items with spaces rather than newlines')
49
+ group.add_argument('--compact', action='store_true',
50
+ help='suppress all whitespace separation (most compact)')
51
+ options = parser.parse_args()
52
+
53
+ dump_args = {
54
+ 'sort_keys': options.sort_keys,
55
+ 'indent': options.indent,
56
+ 'ensure_ascii': options.ensure_ascii,
57
+ }
58
+ if options.compact:
59
+ dump_args['indent'] = None
60
+ dump_args['separators'] = ',', ':'
61
+
62
+ with options.infile as infile:
63
+ try:
64
+ if options.json_lines:
65
+ objs = (json.loads(line) for line in infile)
66
+ else:
67
+ objs = (json.load(infile),)
68
+
69
+ if options.outfile is None:
70
+ out = sys.stdout
71
+ else:
72
+ out = options.outfile.open('w', encoding='utf-8')
73
+ with out as outfile:
74
+ for obj in objs:
75
+ json.dump(obj, outfile, **dump_args)
76
+ outfile.write('\n')
77
+ except ValueError as e:
78
+ raise SystemExit(e)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ try:
83
+ main()
84
+ except BrokenPipeError as exc:
85
+ sys.exit(exc.errno)
parrot/lib/python3.10/lib2to3/fixes/__pycache__/fix_except.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
parrot/lib/python3.10/lib2to3/fixes/__pycache__/fix_sys_exc.cpython-310.pyc ADDED
Binary file (1.67 kB). View file
 
parrot/lib/python3.10/lib2to3/fixes/__pycache__/fix_throw.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
parrot/lib/python3.10/lib2to3/fixes/fix_apply.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer for apply().
5
+
6
+ This converts apply(func, v, k) into (func)(*v, **k)."""
7
+
8
+ # Local imports
9
+ from .. import pytree
10
+ from ..pgen2 import token
11
+ from .. import fixer_base
12
+ from ..fixer_util import Call, Comma, parenthesize
13
+
14
+ class FixApply(fixer_base.BaseFix):
15
+ BM_compatible = True
16
+
17
+ PATTERN = """
18
+ power< 'apply'
19
+ trailer<
20
+ '('
21
+ arglist<
22
+ (not argument<NAME '=' any>) func=any ','
23
+ (not argument<NAME '=' any>) args=any [','
24
+ (not argument<NAME '=' any>) kwds=any] [',']
25
+ >
26
+ ')'
27
+ >
28
+ >
29
+ """
30
+
31
+ def transform(self, node, results):
32
+ syms = self.syms
33
+ assert results
34
+ func = results["func"]
35
+ args = results["args"]
36
+ kwds = results.get("kwds")
37
+ # I feel like we should be able to express this logic in the
38
+ # PATTERN above but I don't know how to do it so...
39
+ if args:
40
+ if (args.type == self.syms.argument and
41
+ args.children[0].value in {'**', '*'}):
42
+ return # Make no change.
43
+ if kwds and (kwds.type == self.syms.argument and
44
+ kwds.children[0].value == '**'):
45
+ return # Make no change.
46
+ prefix = node.prefix
47
+ func = func.clone()
48
+ if (func.type not in (token.NAME, syms.atom) and
49
+ (func.type != syms.power or
50
+ func.children[-2].type == token.DOUBLESTAR)):
51
+ # Need to parenthesize
52
+ func = parenthesize(func)
53
+ func.prefix = ""
54
+ args = args.clone()
55
+ args.prefix = ""
56
+ if kwds is not None:
57
+ kwds = kwds.clone()
58
+ kwds.prefix = ""
59
+ l_newargs = [pytree.Leaf(token.STAR, "*"), args]
60
+ if kwds is not None:
61
+ l_newargs.extend([Comma(),
62
+ pytree.Leaf(token.DOUBLESTAR, "**"),
63
+ kwds])
64
+ l_newargs[-2].prefix = " " # that's the ** token
65
+ # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t)
66
+ # can be translated into f(x, y, *t) instead of f(*(x, y) + t)
67
+ #new = pytree.Node(syms.power, (func, ArgList(l_newargs)))
68
+ return Call(func, l_newargs, prefix=prefix)
parrot/lib/python3.10/lib2to3/fixes/fix_exitfunc.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert use of sys.exitfunc to use the atexit module.
3
+ """
4
+
5
+ # Author: Benjamin Peterson
6
+
7
+ from lib2to3 import pytree, fixer_base
8
+ from lib2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms
9
+
10
+
11
+ class FixExitfunc(fixer_base.BaseFix):
12
+ keep_line_order = True
13
+ BM_compatible = True
14
+
15
+ PATTERN = """
16
+ (
17
+ sys_import=import_name<'import'
18
+ ('sys'
19
+ |
20
+ dotted_as_names< (any ',')* 'sys' (',' any)* >
21
+ )
22
+ >
23
+ |
24
+ expr_stmt<
25
+ power< 'sys' trailer< '.' 'exitfunc' > >
26
+ '=' func=any >
27
+ )
28
+ """
29
+
30
+ def __init__(self, *args):
31
+ super(FixExitfunc, self).__init__(*args)
32
+
33
+ def start_tree(self, tree, filename):
34
+ super(FixExitfunc, self).start_tree(tree, filename)
35
+ self.sys_import = None
36
+
37
+ def transform(self, node, results):
38
+ # First, find the sys import. We'll just hope it's global scope.
39
+ if "sys_import" in results:
40
+ if self.sys_import is None:
41
+ self.sys_import = results["sys_import"]
42
+ return
43
+
44
+ func = results["func"].clone()
45
+ func.prefix = ""
46
+ register = pytree.Node(syms.power,
47
+ Attr(Name("atexit"), Name("register"))
48
+ )
49
+ call = Call(register, [func], node.prefix)
50
+ node.replace(call)
51
+
52
+ if self.sys_import is None:
53
+ # That's interesting.
54
+ self.warning(node, "Can't find sys import; Please add an atexit "
55
+ "import at the top of your file.")
56
+ return
57
+
58
+ # Now add an atexit import after the sys import.
59
+ names = self.sys_import.children[1]
60
+ if names.type == syms.dotted_as_names:
61
+ names.append_child(Comma())
62
+ names.append_child(Name("atexit", " "))
63
+ else:
64
+ containing_stmt = self.sys_import.parent
65
+ position = containing_stmt.children.index(self.sys_import)
66
+ stmt_container = containing_stmt.parent
67
+ new_import = pytree.Node(syms.import_name,
68
+ [Name("import"), Name("atexit", " ")]
69
+ )
70
+ new = pytree.Node(syms.simple_stmt, [new_import])
71
+ containing_stmt.insert_child(position + 1, Newline())
72
+ containing_stmt.insert_child(position + 2, new)
parrot/lib/python3.10/lib2to3/fixes/fix_idioms.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adjust some old Python 2 idioms to their modern counterparts.
2
+
3
+ * Change some type comparisons to isinstance() calls:
4
+ type(x) == T -> isinstance(x, T)
5
+ type(x) is T -> isinstance(x, T)
6
+ type(x) != T -> not isinstance(x, T)
7
+ type(x) is not T -> not isinstance(x, T)
8
+
9
+ * Change "while 1:" into "while True:".
10
+
11
+ * Change both
12
+
13
+ v = list(EXPR)
14
+ v.sort()
15
+ foo(v)
16
+
17
+ and the more general
18
+
19
+ v = EXPR
20
+ v.sort()
21
+ foo(v)
22
+
23
+ into
24
+
25
+ v = sorted(EXPR)
26
+ foo(v)
27
+ """
28
+ # Author: Jacques Frechet, Collin Winter
29
+
30
+ # Local imports
31
+ from .. import fixer_base
32
+ from ..fixer_util import Call, Comma, Name, Node, BlankLine, syms
33
+
34
+ CMP = "(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)"
35
+ TYPE = "power< 'type' trailer< '(' x=any ')' > >"
36
+
37
+ class FixIdioms(fixer_base.BaseFix):
38
+ explicit = True # The user must ask for this fixer
39
+
40
+ PATTERN = r"""
41
+ isinstance=comparison< %s %s T=any >
42
+ |
43
+ isinstance=comparison< T=any %s %s >
44
+ |
45
+ while_stmt< 'while' while='1' ':' any+ >
46
+ |
47
+ sorted=any<
48
+ any*
49
+ simple_stmt<
50
+ expr_stmt< id1=any '='
51
+ power< list='list' trailer< '(' (not arglist<any+>) any ')' > >
52
+ >
53
+ '\n'
54
+ >
55
+ sort=
56
+ simple_stmt<
57
+ power< id2=any
58
+ trailer< '.' 'sort' > trailer< '(' ')' >
59
+ >
60
+ '\n'
61
+ >
62
+ next=any*
63
+ >
64
+ |
65
+ sorted=any<
66
+ any*
67
+ simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' >
68
+ sort=
69
+ simple_stmt<
70
+ power< id2=any
71
+ trailer< '.' 'sort' > trailer< '(' ')' >
72
+ >
73
+ '\n'
74
+ >
75
+ next=any*
76
+ >
77
+ """ % (TYPE, CMP, CMP, TYPE)
78
+
79
+ def match(self, node):
80
+ r = super(FixIdioms, self).match(node)
81
+ # If we've matched one of the sort/sorted subpatterns above, we
82
+ # want to reject matches where the initial assignment and the
83
+ # subsequent .sort() call involve different identifiers.
84
+ if r and "sorted" in r:
85
+ if r["id1"] == r["id2"]:
86
+ return r
87
+ return None
88
+ return r
89
+
90
+ def transform(self, node, results):
91
+ if "isinstance" in results:
92
+ return self.transform_isinstance(node, results)
93
+ elif "while" in results:
94
+ return self.transform_while(node, results)
95
+ elif "sorted" in results:
96
+ return self.transform_sort(node, results)
97
+ else:
98
+ raise RuntimeError("Invalid match")
99
+
100
+ def transform_isinstance(self, node, results):
101
+ x = results["x"].clone() # The thing inside of type()
102
+ T = results["T"].clone() # The type being compared against
103
+ x.prefix = ""
104
+ T.prefix = " "
105
+ test = Call(Name("isinstance"), [x, Comma(), T])
106
+ if "n" in results:
107
+ test.prefix = " "
108
+ test = Node(syms.not_test, [Name("not"), test])
109
+ test.prefix = node.prefix
110
+ return test
111
+
112
+ def transform_while(self, node, results):
113
+ one = results["while"]
114
+ one.replace(Name("True", prefix=one.prefix))
115
+
116
+ def transform_sort(self, node, results):
117
+ sort_stmt = results["sort"]
118
+ next_stmt = results["next"]
119
+ list_call = results.get("list")
120
+ simple_expr = results.get("expr")
121
+
122
+ if list_call:
123
+ list_call.replace(Name("sorted", prefix=list_call.prefix))
124
+ elif simple_expr:
125
+ new = simple_expr.clone()
126
+ new.prefix = ""
127
+ simple_expr.replace(Call(Name("sorted"), [new],
128
+ prefix=simple_expr.prefix))
129
+ else:
130
+ raise RuntimeError("should not have reached here")
131
+ sort_stmt.remove()
132
+
133
+ btwn = sort_stmt.prefix
134
+ # Keep any prefix lines between the sort_stmt and the list_call and
135
+ # shove them right after the sorted() call.
136
+ if "\n" in btwn:
137
+ if next_stmt:
138
+ # The new prefix should be everything from the sort_stmt's
139
+ # prefix up to the last newline, then the old prefix after a new
140
+ # line.
141
+ prefix_lines = (btwn.rpartition("\n")[0], next_stmt[0].prefix)
142
+ next_stmt[0].prefix = "\n".join(prefix_lines)
143
+ else:
144
+ assert list_call.parent
145
+ assert list_call.next_sibling is None
146
+ # Put a blank line after list_call and set its prefix.
147
+ end_line = BlankLine()
148
+ list_call.parent.append_child(end_line)
149
+ assert list_call.next_sibling is end_line
150
+ # The new prefix should be everything up to the first new line
151
+ # of sort_stmt's prefix.
152
+ end_line.prefix = btwn.rpartition("\n")[0]
parrot/lib/python3.10/lib2to3/fixes/fix_imports.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix incompatible imports and module references."""
2
+ # Authors: Collin Winter, Nick Edds
3
+
4
+ # Local imports
5
+ from .. import fixer_base
6
+ from ..fixer_util import Name, attr_chain
7
+
8
+ MAPPING = {'StringIO': 'io',
9
+ 'cStringIO': 'io',
10
+ 'cPickle': 'pickle',
11
+ '__builtin__' : 'builtins',
12
+ 'copy_reg': 'copyreg',
13
+ 'Queue': 'queue',
14
+ 'SocketServer': 'socketserver',
15
+ 'ConfigParser': 'configparser',
16
+ 'repr': 'reprlib',
17
+ 'FileDialog': 'tkinter.filedialog',
18
+ 'tkFileDialog': 'tkinter.filedialog',
19
+ 'SimpleDialog': 'tkinter.simpledialog',
20
+ 'tkSimpleDialog': 'tkinter.simpledialog',
21
+ 'tkColorChooser': 'tkinter.colorchooser',
22
+ 'tkCommonDialog': 'tkinter.commondialog',
23
+ 'Dialog': 'tkinter.dialog',
24
+ 'Tkdnd': 'tkinter.dnd',
25
+ 'tkFont': 'tkinter.font',
26
+ 'tkMessageBox': 'tkinter.messagebox',
27
+ 'ScrolledText': 'tkinter.scrolledtext',
28
+ 'Tkconstants': 'tkinter.constants',
29
+ 'Tix': 'tkinter.tix',
30
+ 'ttk': 'tkinter.ttk',
31
+ 'Tkinter': 'tkinter',
32
+ 'markupbase': '_markupbase',
33
+ '_winreg': 'winreg',
34
+ 'thread': '_thread',
35
+ 'dummy_thread': '_dummy_thread',
36
+ # anydbm and whichdb are handled by fix_imports2
37
+ 'dbhash': 'dbm.bsd',
38
+ 'dumbdbm': 'dbm.dumb',
39
+ 'dbm': 'dbm.ndbm',
40
+ 'gdbm': 'dbm.gnu',
41
+ 'xmlrpclib': 'xmlrpc.client',
42
+ 'DocXMLRPCServer': 'xmlrpc.server',
43
+ 'SimpleXMLRPCServer': 'xmlrpc.server',
44
+ 'httplib': 'http.client',
45
+ 'htmlentitydefs' : 'html.entities',
46
+ 'HTMLParser' : 'html.parser',
47
+ 'Cookie': 'http.cookies',
48
+ 'cookielib': 'http.cookiejar',
49
+ 'BaseHTTPServer': 'http.server',
50
+ 'SimpleHTTPServer': 'http.server',
51
+ 'CGIHTTPServer': 'http.server',
52
+ #'test.test_support': 'test.support',
53
+ 'commands': 'subprocess',
54
+ 'UserString' : 'collections',
55
+ 'UserList' : 'collections',
56
+ 'urlparse' : 'urllib.parse',
57
+ 'robotparser' : 'urllib.robotparser',
58
+ }
59
+
60
+
61
+ def alternates(members):
62
+ return "(" + "|".join(map(repr, members)) + ")"
63
+
64
+
65
+ def build_pattern(mapping=MAPPING):
66
+ mod_list = ' | '.join(["module_name='%s'" % key for key in mapping])
67
+ bare_names = alternates(mapping.keys())
68
+
69
+ yield """name_import=import_name< 'import' ((%s) |
70
+ multiple_imports=dotted_as_names< any* (%s) any* >) >
71
+ """ % (mod_list, mod_list)
72
+ yield """import_from< 'from' (%s) 'import' ['(']
73
+ ( any | import_as_name< any 'as' any > |
74
+ import_as_names< any* >) [')'] >
75
+ """ % mod_list
76
+ yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > |
77
+ multiple_imports=dotted_as_names<
78
+ any* dotted_as_name< (%s) 'as' any > any* >) >
79
+ """ % (mod_list, mod_list)
80
+
81
+ # Find usages of module members in code e.g. thread.foo(bar)
82
+ yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names
83
+
84
+
85
+ class FixImports(fixer_base.BaseFix):
86
+
87
+ BM_compatible = True
88
+ keep_line_order = True
89
+ # This is overridden in fix_imports2.
90
+ mapping = MAPPING
91
+
92
+ # We want to run this fixer late, so fix_import doesn't try to make stdlib
93
+ # renames into relative imports.
94
+ run_order = 6
95
+
96
+ def build_pattern(self):
97
+ return "|".join(build_pattern(self.mapping))
98
+
99
+ def compile_pattern(self):
100
+ # We override this, so MAPPING can be pragmatically altered and the
101
+ # changes will be reflected in PATTERN.
102
+ self.PATTERN = self.build_pattern()
103
+ super(FixImports, self).compile_pattern()
104
+
105
+ # Don't match the node if it's within another match.
106
+ def match(self, node):
107
+ match = super(FixImports, self).match
108
+ results = match(node)
109
+ if results:
110
+ # Module usage could be in the trailer of an attribute lookup, so we
111
+ # might have nested matches when "bare_with_attr" is present.
112
+ if "bare_with_attr" not in results and \
113
+ any(match(obj) for obj in attr_chain(node, "parent")):
114
+ return False
115
+ return results
116
+ return False
117
+
118
+ def start_tree(self, tree, filename):
119
+ super(FixImports, self).start_tree(tree, filename)
120
+ self.replace = {}
121
+
122
+ def transform(self, node, results):
123
+ import_mod = results.get("module_name")
124
+ if import_mod:
125
+ mod_name = import_mod.value
126
+ new_name = self.mapping[mod_name]
127
+ import_mod.replace(Name(new_name, prefix=import_mod.prefix))
128
+ if "name_import" in results:
129
+ # If it's not a "from x import x, y" or "import x as y" import,
130
+ # marked its usage to be replaced.
131
+ self.replace[mod_name] = new_name
132
+ if "multiple_imports" in results:
133
+ # This is a nasty hack to fix multiple imports on a line (e.g.,
134
+ # "import StringIO, urlparse"). The problem is that I can't
135
+ # figure out an easy way to make a pattern recognize the keys of
136
+ # MAPPING randomly sprinkled in an import statement.
137
+ results = self.match(node)
138
+ if results:
139
+ self.transform(node, results)
140
+ else:
141
+ # Replace usage of the module.
142
+ bare_name = results["bare_with_attr"][0]
143
+ new_name = self.replace.get(bare_name.value)
144
+ if new_name:
145
+ bare_name.replace(Name(new_name, prefix=bare_name.prefix))
parrot/lib/python3.10/lib2to3/fixes/fix_isinstance.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008 Armin Ronacher.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer that cleans up a tuple argument to isinstance after the tokens
5
+ in it were fixed. This is mainly used to remove double occurrences of
6
+ tokens as a leftover of the long -> int / unicode -> str conversion.
7
+
8
+ eg. isinstance(x, (int, long)) -> isinstance(x, (int, int))
9
+ -> isinstance(x, int)
10
+ """
11
+
12
+ from .. import fixer_base
13
+ from ..fixer_util import token
14
+
15
+
16
+ class FixIsinstance(fixer_base.BaseFix):
17
+ BM_compatible = True
18
+ PATTERN = """
19
+ power<
20
+ 'isinstance'
21
+ trailer< '(' arglist< any ',' atom< '('
22
+ args=testlist_gexp< any+ >
23
+ ')' > > ')' >
24
+ >
25
+ """
26
+
27
+ run_order = 6
28
+
29
+ def transform(self, node, results):
30
+ names_inserted = set()
31
+ testlist = results["args"]
32
+ args = testlist.children
33
+ new_args = []
34
+ iterator = enumerate(args)
35
+ for idx, arg in iterator:
36
+ if arg.type == token.NAME and arg.value in names_inserted:
37
+ if idx < len(args) - 1 and args[idx + 1].type == token.COMMA:
38
+ next(iterator)
39
+ continue
40
+ else:
41
+ new_args.append(arg)
42
+ if arg.type == token.NAME:
43
+ names_inserted.add(arg.value)
44
+ if new_args and new_args[-1].type == token.COMMA:
45
+ del new_args[-1]
46
+ if len(new_args) == 1:
47
+ atom = testlist.parent
48
+ new_args[0].prefix = atom.prefix
49
+ atom.replace(new_args[0])
50
+ else:
51
+ args[:] = new_args
52
+ node.changed()
parrot/lib/python3.10/lib2to3/fixes/fix_map.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer that changes map(F, ...) into list(map(F, ...)) unless there
5
+ exists a 'from future_builtins import map' statement in the top-level
6
+ namespace.
7
+
8
+ As a special case, map(None, X) is changed into list(X). (This is
9
+ necessary because the semantics are changed in this case -- the new
10
+ map(None, X) is equivalent to [(x,) for x in X].)
11
+
12
+ We avoid the transformation (except for the special case mentioned
13
+ above) if the map() call is directly contained in iter(<>), list(<>),
14
+ tuple(<>), sorted(<>), ...join(<>), or for V in <>:.
15
+
16
+ NOTE: This is still not correct if the original code was depending on
17
+ map(F, X, Y, ...) to go on until the longest argument is exhausted,
18
+ substituting None for missing values -- like zip(), it now stops as
19
+ soon as the shortest argument is exhausted.
20
+ """
21
+
22
+ # Local imports
23
+ from ..pgen2 import token
24
+ from .. import fixer_base
25
+ from ..fixer_util import Name, ArgList, Call, ListComp, in_special_context
26
+ from ..pygram import python_symbols as syms
27
+ from ..pytree import Node
28
+
29
+
30
+ class FixMap(fixer_base.ConditionalFix):
31
+ BM_compatible = True
32
+
33
+ PATTERN = """
34
+ map_none=power<
35
+ 'map'
36
+ trailer< '(' arglist< 'None' ',' arg=any [','] > ')' >
37
+ [extra_trailers=trailer*]
38
+ >
39
+ |
40
+ map_lambda=power<
41
+ 'map'
42
+ trailer<
43
+ '('
44
+ arglist<
45
+ lambdef< 'lambda'
46
+ (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
47
+ >
48
+ ','
49
+ it=any
50
+ >
51
+ ')'
52
+ >
53
+ [extra_trailers=trailer*]
54
+ >
55
+ |
56
+ power<
57
+ 'map' args=trailer< '(' [any] ')' >
58
+ [extra_trailers=trailer*]
59
+ >
60
+ """
61
+
62
+ skip_on = 'future_builtins.map'
63
+
64
+ def transform(self, node, results):
65
+ if self.should_skip(node):
66
+ return
67
+
68
+ trailers = []
69
+ if 'extra_trailers' in results:
70
+ for t in results['extra_trailers']:
71
+ trailers.append(t.clone())
72
+
73
+ if node.parent.type == syms.simple_stmt:
74
+ self.warning(node, "You should use a for loop here")
75
+ new = node.clone()
76
+ new.prefix = ""
77
+ new = Call(Name("list"), [new])
78
+ elif "map_lambda" in results:
79
+ new = ListComp(results["xp"].clone(),
80
+ results["fp"].clone(),
81
+ results["it"].clone())
82
+ new = Node(syms.power, [new] + trailers, prefix="")
83
+
84
+ else:
85
+ if "map_none" in results:
86
+ new = results["arg"].clone()
87
+ new.prefix = ""
88
+ else:
89
+ if "args" in results:
90
+ args = results["args"]
91
+ if args.type == syms.trailer and \
92
+ args.children[1].type == syms.arglist and \
93
+ args.children[1].children[0].type == token.NAME and \
94
+ args.children[1].children[0].value == "None":
95
+ self.warning(node, "cannot convert map(None, ...) "
96
+ "with multiple arguments because map() "
97
+ "now truncates to the shortest sequence")
98
+ return
99
+
100
+ new = Node(syms.power, [Name("map"), args.clone()])
101
+ new.prefix = ""
102
+
103
+ if in_special_context(node):
104
+ return None
105
+
106
+ new = Node(syms.power, [Name("list"), ArgList([new])] + trailers)
107
+ new.prefix = ""
108
+
109
+ new.prefix = node.prefix
110
+ return new
parrot/lib/python3.10/lib2to3/fixes/fix_operator.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for operator functions.
2
+
3
+ operator.isCallable(obj) -> callable(obj)
4
+ operator.sequenceIncludes(obj) -> operator.contains(obj)
5
+ operator.isSequenceType(obj) -> isinstance(obj, collections.abc.Sequence)
6
+ operator.isMappingType(obj) -> isinstance(obj, collections.abc.Mapping)
7
+ operator.isNumberType(obj) -> isinstance(obj, numbers.Number)
8
+ operator.repeat(obj, n) -> operator.mul(obj, n)
9
+ operator.irepeat(obj, n) -> operator.imul(obj, n)
10
+ """
11
+
12
+ import collections.abc
13
+
14
+ # Local imports
15
+ from lib2to3 import fixer_base
16
+ from lib2to3.fixer_util import Call, Name, String, touch_import
17
+
18
+
19
+ def invocation(s):
20
+ def dec(f):
21
+ f.invocation = s
22
+ return f
23
+ return dec
24
+
25
+
26
+ class FixOperator(fixer_base.BaseFix):
27
+ BM_compatible = True
28
+ order = "pre"
29
+
30
+ methods = """
31
+ method=('isCallable'|'sequenceIncludes'
32
+ |'isSequenceType'|'isMappingType'|'isNumberType'
33
+ |'repeat'|'irepeat')
34
+ """
35
+ obj = "'(' obj=any ')'"
36
+ PATTERN = """
37
+ power< module='operator'
38
+ trailer< '.' %(methods)s > trailer< %(obj)s > >
39
+ |
40
+ power< %(methods)s trailer< %(obj)s > >
41
+ """ % dict(methods=methods, obj=obj)
42
+
43
+ def transform(self, node, results):
44
+ method = self._check_method(node, results)
45
+ if method is not None:
46
+ return method(node, results)
47
+
48
+ @invocation("operator.contains(%s)")
49
+ def _sequenceIncludes(self, node, results):
50
+ return self._handle_rename(node, results, "contains")
51
+
52
+ @invocation("callable(%s)")
53
+ def _isCallable(self, node, results):
54
+ obj = results["obj"]
55
+ return Call(Name("callable"), [obj.clone()], prefix=node.prefix)
56
+
57
+ @invocation("operator.mul(%s)")
58
+ def _repeat(self, node, results):
59
+ return self._handle_rename(node, results, "mul")
60
+
61
+ @invocation("operator.imul(%s)")
62
+ def _irepeat(self, node, results):
63
+ return self._handle_rename(node, results, "imul")
64
+
65
+ @invocation("isinstance(%s, collections.abc.Sequence)")
66
+ def _isSequenceType(self, node, results):
67
+ return self._handle_type2abc(node, results, "collections.abc", "Sequence")
68
+
69
+ @invocation("isinstance(%s, collections.abc.Mapping)")
70
+ def _isMappingType(self, node, results):
71
+ return self._handle_type2abc(node, results, "collections.abc", "Mapping")
72
+
73
+ @invocation("isinstance(%s, numbers.Number)")
74
+ def _isNumberType(self, node, results):
75
+ return self._handle_type2abc(node, results, "numbers", "Number")
76
+
77
+ def _handle_rename(self, node, results, name):
78
+ method = results["method"][0]
79
+ method.value = name
80
+ method.changed()
81
+
82
+ def _handle_type2abc(self, node, results, module, abc):
83
+ touch_import(None, module, node)
84
+ obj = results["obj"]
85
+ args = [obj.clone(), String(", " + ".".join([module, abc]))]
86
+ return Call(Name("isinstance"), args, prefix=node.prefix)
87
+
88
+ def _check_method(self, node, results):
89
+ method = getattr(self, "_" + results["method"][0].value)
90
+ if isinstance(method, collections.abc.Callable):
91
+ if "module" in results:
92
+ return method
93
+ else:
94
+ sub = (str(results["obj"]),)
95
+ invocation_str = method.invocation % sub
96
+ self.warning(node, "You should use '%s' here." % invocation_str)
97
+ return None
parrot/lib/python3.10/lib2to3/fixes/fix_print.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer for print.
5
+
6
+ Change:
7
+ 'print' into 'print()'
8
+ 'print ...' into 'print(...)'
9
+ 'print ... ,' into 'print(..., end=" ")'
10
+ 'print >>x, ...' into 'print(..., file=x)'
11
+
12
+ No changes are applied if print_function is imported from __future__
13
+
14
+ """
15
+
16
+ # Local imports
17
+ from .. import patcomp
18
+ from .. import pytree
19
+ from ..pgen2 import token
20
+ from .. import fixer_base
21
+ from ..fixer_util import Name, Call, Comma, String
22
+
23
+
24
+ parend_expr = patcomp.compile_pattern(
25
+ """atom< '(' [atom|STRING|NAME] ')' >"""
26
+ )
27
+
28
+
29
+ class FixPrint(fixer_base.BaseFix):
30
+
31
+ BM_compatible = True
32
+
33
+ PATTERN = """
34
+ simple_stmt< any* bare='print' any* > | print_stmt
35
+ """
36
+
37
+ def transform(self, node, results):
38
+ assert results
39
+
40
+ bare_print = results.get("bare")
41
+
42
+ if bare_print:
43
+ # Special-case print all by itself
44
+ bare_print.replace(Call(Name("print"), [],
45
+ prefix=bare_print.prefix))
46
+ return
47
+ assert node.children[0] == Name("print")
48
+ args = node.children[1:]
49
+ if len(args) == 1 and parend_expr.match(args[0]):
50
+ # We don't want to keep sticking parens around an
51
+ # already-parenthesised expression.
52
+ return
53
+
54
+ sep = end = file = None
55
+ if args and args[-1] == Comma():
56
+ args = args[:-1]
57
+ end = " "
58
+ if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"):
59
+ assert len(args) >= 2
60
+ file = args[1].clone()
61
+ args = args[3:] # Strip a possible comma after the file expression
62
+ # Now synthesize a print(args, sep=..., end=..., file=...) node.
63
+ l_args = [arg.clone() for arg in args]
64
+ if l_args:
65
+ l_args[0].prefix = ""
66
+ if sep is not None or end is not None or file is not None:
67
+ if sep is not None:
68
+ self.add_kwarg(l_args, "sep", String(repr(sep)))
69
+ if end is not None:
70
+ self.add_kwarg(l_args, "end", String(repr(end)))
71
+ if file is not None:
72
+ self.add_kwarg(l_args, "file", file)
73
+ n_stmt = Call(Name("print"), l_args)
74
+ n_stmt.prefix = node.prefix
75
+ return n_stmt
76
+
77
+ def add_kwarg(self, l_nodes, s_kwd, n_expr):
78
+ # XXX All this prefix-setting may lose comments (though rarely)
79
+ n_expr.prefix = ""
80
+ n_argument = pytree.Node(self.syms.argument,
81
+ (Name(s_kwd),
82
+ pytree.Leaf(token.EQUAL, "="),
83
+ n_expr))
84
+ if l_nodes:
85
+ l_nodes.append(Comma())
86
+ n_argument.prefix = " "
87
+ l_nodes.append(n_argument)
parrot/lib/python3.10/lib2to3/fixes/fix_raw_input.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer that changes raw_input(...) into input(...)."""
2
+ # Author: Andre Roberge
3
+
4
+ # Local imports
5
+ from .. import fixer_base
6
+ from ..fixer_util import Name
7
+
8
+ class FixRawInput(fixer_base.BaseFix):
9
+
10
+ BM_compatible = True
11
+ PATTERN = """
12
+ power< name='raw_input' trailer< '(' [any] ')' > any* >
13
+ """
14
+
15
+ def transform(self, node, results):
16
+ name = results["name"]
17
+ name.replace(Name("input", prefix=name.prefix))
parrot/lib/python3.10/lib2to3/fixes/fix_reduce.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008 Armin Ronacher.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer for reduce().
5
+
6
+ Makes sure reduce() is imported from the functools module if reduce is
7
+ used in that module.
8
+ """
9
+
10
+ from lib2to3 import fixer_base
11
+ from lib2to3.fixer_util import touch_import
12
+
13
+
14
+
15
+ class FixReduce(fixer_base.BaseFix):
16
+
17
+ BM_compatible = True
18
+ order = "pre"
19
+
20
+ PATTERN = """
21
+ power< 'reduce'
22
+ trailer< '('
23
+ arglist< (
24
+ (not(argument<any '=' any>) any ','
25
+ not(argument<any '=' any>) any) |
26
+ (not(argument<any '=' any>) any ','
27
+ not(argument<any '=' any>) any ','
28
+ not(argument<any '=' any>) any)
29
+ ) >
30
+ ')' >
31
+ >
32
+ """
33
+
34
+ def transform(self, node, results):
35
+ touch_import('functools', 'reduce', node)
parrot/lib/python3.10/lib2to3/fixes/fix_sys_exc.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for sys.exc_{type, value, traceback}
2
+
3
+ sys.exc_type -> sys.exc_info()[0]
4
+ sys.exc_value -> sys.exc_info()[1]
5
+ sys.exc_traceback -> sys.exc_info()[2]
6
+ """
7
+
8
+ # By Jeff Balogh and Benjamin Peterson
9
+
10
+ # Local imports
11
+ from .. import fixer_base
12
+ from ..fixer_util import Attr, Call, Name, Number, Subscript, Node, syms
13
+
14
+ class FixSysExc(fixer_base.BaseFix):
15
+ # This order matches the ordering of sys.exc_info().
16
+ exc_info = ["exc_type", "exc_value", "exc_traceback"]
17
+ BM_compatible = True
18
+ PATTERN = """
19
+ power< 'sys' trailer< dot='.' attribute=(%s) > >
20
+ """ % '|'.join("'%s'" % e for e in exc_info)
21
+
22
+ def transform(self, node, results):
23
+ sys_attr = results["attribute"][0]
24
+ index = Number(self.exc_info.index(sys_attr.value))
25
+
26
+ call = Call(Name("exc_info"), prefix=sys_attr.prefix)
27
+ attr = Attr(Name("sys"), call)
28
+ attr[1].children[0].prefix = results["dot"].prefix
29
+ attr.append(Subscript(index))
30
+ return Node(syms.power, attr, prefix=node.prefix)
parrot/lib/python3.10/lib2to3/fixes/fix_xreadlines.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix "for x in f.xreadlines()" -> "for x in f".
2
+
3
+ This fixer will also convert g(f.xreadlines) into g(f.__iter__)."""
4
+ # Author: Collin Winter
5
+
6
+ # Local imports
7
+ from .. import fixer_base
8
+ from ..fixer_util import Name
9
+
10
+
11
+ class FixXreadlines(fixer_base.BaseFix):
12
+ BM_compatible = True
13
+ PATTERN = """
14
+ power< call=any+ trailer< '.' 'xreadlines' > trailer< '(' ')' > >
15
+ |
16
+ power< any+ trailer< '.' no_call='xreadlines' > >
17
+ """
18
+
19
+ def transform(self, node, results):
20
+ no_call = results.get("no_call")
21
+
22
+ if no_call:
23
+ no_call.replace(Name("__iter__", prefix=no_call.prefix))
24
+ else:
25
+ node.replace([x.clone() for x in results["call"]])