jasonfan commited on
Commit
c9a3b6f
·
verified ·
1 Parent(s): 4472180

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. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_isinstance.py +52 -0
  2. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_itertools.py +43 -0
  3. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_itertools_imports.py +57 -0
  4. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_long.py +19 -0
  5. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_map.py +110 -0
  6. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_metaclass.py +228 -0
  7. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_methodattrs.py +24 -0
  8. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_ne.py +23 -0
  9. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_next.py +103 -0
  10. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_nonzero.py +21 -0
  11. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_numliterals.py +28 -0
  12. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_operator.py +97 -0
  13. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_paren.py +44 -0
  14. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_print.py +87 -0
  15. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_raise.py +90 -0
  16. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_raw_input.py +17 -0
  17. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_reduce.py +35 -0
  18. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_reload.py +36 -0
  19. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_renames.py +70 -0
  20. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_repr.py +23 -0
  21. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_set_literal.py +53 -0
  22. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_standarderror.py +18 -0
  23. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_sys_exc.py +30 -0
  24. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_throw.py +56 -0
  25. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_tuple_params.py +175 -0
  26. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_types.py +61 -0
  27. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_unicode.py +42 -0
  28. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_urllib.py +196 -0
  29. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_ws_comma.py +39 -0
  30. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_xrange.py +73 -0
  31. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_xreadlines.py +25 -0
  32. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_zip.py +46 -0
  33. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/__init__.py +4 -0
  34. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/conv.py +257 -0
  35. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/driver.py +177 -0
  36. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/grammar.py +188 -0
  37. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/literals.py +60 -0
  38. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/parse.py +204 -0
  39. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/pgen.py +386 -0
  40. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/token.py +86 -0
  41. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/tokenize.py +564 -0
  42. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/__init__.py +8 -0
  43. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/__main__.py +4 -0
  44. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/README +6 -0
  45. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/bom.py +2 -0
  46. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/crlf.py +3 -0
  47. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/different_encoding.py +6 -0
  48. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/false_encoding.py +2 -0
  49. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/fixers/bad_order.py +5 -0
  50. miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/fixers/myfixes/__init__.py +0 -0
miniconda3/pkgs/python-3.10.20-h741d88c_0/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()
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_itertools.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Fixer for itertools.(imap|ifilter|izip) --> (map|filter|zip) and
2
+ itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363)
3
+
4
+ imports from itertools are fixed in fix_itertools_import.py
5
+
6
+ If itertools is imported as something else (ie: import itertools as it;
7
+ it.izip(spam, eggs)) method calls will not get fixed.
8
+ """
9
+
10
+ # Local imports
11
+ from .. import fixer_base
12
+ from ..fixer_util import Name
13
+
14
+ class FixItertools(fixer_base.BaseFix):
15
+ BM_compatible = True
16
+ it_funcs = "('imap'|'ifilter'|'izip'|'izip_longest'|'ifilterfalse')"
17
+ PATTERN = """
18
+ power< it='itertools'
19
+ trailer<
20
+ dot='.' func=%(it_funcs)s > trailer< '(' [any] ')' > >
21
+ |
22
+ power< func=%(it_funcs)s trailer< '(' [any] ')' > >
23
+ """ %(locals())
24
+
25
+ # Needs to be run after fix_(map|zip|filter)
26
+ run_order = 6
27
+
28
+ def transform(self, node, results):
29
+ prefix = None
30
+ func = results['func'][0]
31
+ if ('it' in results and
32
+ func.value not in ('ifilterfalse', 'izip_longest')):
33
+ dot, it = (results['dot'], results['it'])
34
+ # Remove the 'itertools'
35
+ prefix = it.prefix
36
+ it.remove()
37
+ # Replace the node which contains ('.', 'function') with the
38
+ # function (to be consistent with the second part of the pattern)
39
+ dot.remove()
40
+ func.parent.replace(func)
41
+
42
+ prefix = prefix or func.prefix
43
+ func.replace(Name(func.value[1:], prefix=prefix))
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_itertools_imports.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """
2
+
3
+ # Local imports
4
+ from lib2to3 import fixer_base
5
+ from lib2to3.fixer_util import BlankLine, syms, token
6
+
7
+
8
+ class FixItertoolsImports(fixer_base.BaseFix):
9
+ BM_compatible = True
10
+ PATTERN = """
11
+ import_from< 'from' 'itertools' 'import' imports=any >
12
+ """ %(locals())
13
+
14
+ def transform(self, node, results):
15
+ imports = results['imports']
16
+ if imports.type == syms.import_as_name or not imports.children:
17
+ children = [imports]
18
+ else:
19
+ children = imports.children
20
+ for child in children[::2]:
21
+ if child.type == token.NAME:
22
+ member = child.value
23
+ name_node = child
24
+ elif child.type == token.STAR:
25
+ # Just leave the import as is.
26
+ return
27
+ else:
28
+ assert child.type == syms.import_as_name
29
+ name_node = child.children[0]
30
+ member_name = name_node.value
31
+ if member_name in ('imap', 'izip', 'ifilter'):
32
+ child.value = None
33
+ child.remove()
34
+ elif member_name in ('ifilterfalse', 'izip_longest'):
35
+ node.changed()
36
+ name_node.value = ('filterfalse' if member_name[1] == 'f'
37
+ else 'zip_longest')
38
+
39
+ # Make sure the import statement is still sane
40
+ children = imports.children[:] or [imports]
41
+ remove_comma = True
42
+ for child in children:
43
+ if remove_comma and child.type == token.COMMA:
44
+ child.remove()
45
+ else:
46
+ remove_comma ^= True
47
+
48
+ while children and children[-1].type == token.COMMA:
49
+ children.pop().remove()
50
+
51
+ # If there are no imports left, just get rid of the entire statement
52
+ if (not (imports.children or getattr(imports, 'value', None)) or
53
+ imports.parent is None):
54
+ p = node.prefix
55
+ node = BlankLine()
56
+ node.prefix = p
57
+ return node
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_long.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer that turns 'long' into 'int' everywhere.
5
+ """
6
+
7
+ # Local imports
8
+ from lib2to3 import fixer_base
9
+ from lib2to3.fixer_util import is_probably_builtin
10
+
11
+
12
+ class FixLong(fixer_base.BaseFix):
13
+ BM_compatible = True
14
+ PATTERN = "'long'"
15
+
16
+ def transform(self, node, results):
17
+ if is_probably_builtin(node):
18
+ node.value = "int"
19
+ node.changed()
miniconda3/pkgs/python-3.10.20-h741d88c_0/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
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_metaclass.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for __metaclass__ = X -> (metaclass=X) methods.
2
+
3
+ The various forms of classef (inherits nothing, inherits once, inherits
4
+ many) don't parse the same in the CST so we look at ALL classes for
5
+ a __metaclass__ and if we find one normalize the inherits to all be
6
+ an arglist.
7
+
8
+ For one-liner classes ('class X: pass') there is no indent/dedent so
9
+ we normalize those into having a suite.
10
+
11
+ Moving the __metaclass__ into the classdef can also cause the class
12
+ body to be empty so there is some special casing for that as well.
13
+
14
+ This fixer also tries very hard to keep original indenting and spacing
15
+ in all those corner cases.
16
+
17
+ """
18
+ # Author: Jack Diederich
19
+
20
+ # Local imports
21
+ from .. import fixer_base
22
+ from ..pygram import token
23
+ from ..fixer_util import syms, Node, Leaf
24
+
25
+
26
+ def has_metaclass(parent):
27
+ """ we have to check the cls_node without changing it.
28
+ There are two possibilities:
29
+ 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
30
+ 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta')
31
+ """
32
+ for node in parent.children:
33
+ if node.type == syms.suite:
34
+ return has_metaclass(node)
35
+ elif node.type == syms.simple_stmt and node.children:
36
+ expr_node = node.children[0]
37
+ if expr_node.type == syms.expr_stmt and expr_node.children:
38
+ left_side = expr_node.children[0]
39
+ if isinstance(left_side, Leaf) and \
40
+ left_side.value == '__metaclass__':
41
+ return True
42
+ return False
43
+
44
+
45
+ def fixup_parse_tree(cls_node):
46
+ """ one-line classes don't get a suite in the parse tree so we add
47
+ one to normalize the tree
48
+ """
49
+ for node in cls_node.children:
50
+ if node.type == syms.suite:
51
+ # already in the preferred format, do nothing
52
+ return
53
+
54
+ # !%@#! one-liners have no suite node, we have to fake one up
55
+ for i, node in enumerate(cls_node.children):
56
+ if node.type == token.COLON:
57
+ break
58
+ else:
59
+ raise ValueError("No class suite and no ':'!")
60
+
61
+ # move everything into a suite node
62
+ suite = Node(syms.suite, [])
63
+ while cls_node.children[i+1:]:
64
+ move_node = cls_node.children[i+1]
65
+ suite.append_child(move_node.clone())
66
+ move_node.remove()
67
+ cls_node.append_child(suite)
68
+ node = suite
69
+
70
+
71
+ def fixup_simple_stmt(parent, i, stmt_node):
72
+ """ if there is a semi-colon all the parts count as part of the same
73
+ simple_stmt. We just want the __metaclass__ part so we move
74
+ everything after the semi-colon into its own simple_stmt node
75
+ """
76
+ for semi_ind, node in enumerate(stmt_node.children):
77
+ if node.type == token.SEMI: # *sigh*
78
+ break
79
+ else:
80
+ return
81
+
82
+ node.remove() # kill the semicolon
83
+ new_expr = Node(syms.expr_stmt, [])
84
+ new_stmt = Node(syms.simple_stmt, [new_expr])
85
+ while stmt_node.children[semi_ind:]:
86
+ move_node = stmt_node.children[semi_ind]
87
+ new_expr.append_child(move_node.clone())
88
+ move_node.remove()
89
+ parent.insert_child(i, new_stmt)
90
+ new_leaf1 = new_stmt.children[0].children[0]
91
+ old_leaf1 = stmt_node.children[0].children[0]
92
+ new_leaf1.prefix = old_leaf1.prefix
93
+
94
+
95
+ def remove_trailing_newline(node):
96
+ if node.children and node.children[-1].type == token.NEWLINE:
97
+ node.children[-1].remove()
98
+
99
+
100
+ def find_metas(cls_node):
101
+ # find the suite node (Mmm, sweet nodes)
102
+ for node in cls_node.children:
103
+ if node.type == syms.suite:
104
+ break
105
+ else:
106
+ raise ValueError("No class suite!")
107
+
108
+ # look for simple_stmt[ expr_stmt[ Leaf('__metaclass__') ] ]
109
+ for i, simple_node in list(enumerate(node.children)):
110
+ if simple_node.type == syms.simple_stmt and simple_node.children:
111
+ expr_node = simple_node.children[0]
112
+ if expr_node.type == syms.expr_stmt and expr_node.children:
113
+ # Check if the expr_node is a simple assignment.
114
+ left_node = expr_node.children[0]
115
+ if isinstance(left_node, Leaf) and \
116
+ left_node.value == '__metaclass__':
117
+ # We found an assignment to __metaclass__.
118
+ fixup_simple_stmt(node, i, simple_node)
119
+ remove_trailing_newline(simple_node)
120
+ yield (node, i, simple_node)
121
+
122
+
123
+ def fixup_indent(suite):
124
+ """ If an INDENT is followed by a thing with a prefix then nuke the prefix
125
+ Otherwise we get in trouble when removing __metaclass__ at suite start
126
+ """
127
+ kids = suite.children[::-1]
128
+ # find the first indent
129
+ while kids:
130
+ node = kids.pop()
131
+ if node.type == token.INDENT:
132
+ break
133
+
134
+ # find the first Leaf
135
+ while kids:
136
+ node = kids.pop()
137
+ if isinstance(node, Leaf) and node.type != token.DEDENT:
138
+ if node.prefix:
139
+ node.prefix = ''
140
+ return
141
+ else:
142
+ kids.extend(node.children[::-1])
143
+
144
+
145
+ class FixMetaclass(fixer_base.BaseFix):
146
+ BM_compatible = True
147
+
148
+ PATTERN = """
149
+ classdef<any*>
150
+ """
151
+
152
+ def transform(self, node, results):
153
+ if not has_metaclass(node):
154
+ return
155
+
156
+ fixup_parse_tree(node)
157
+
158
+ # find metaclasses, keep the last one
159
+ last_metaclass = None
160
+ for suite, i, stmt in find_metas(node):
161
+ last_metaclass = stmt
162
+ stmt.remove()
163
+
164
+ text_type = node.children[0].type # always Leaf(nnn, 'class')
165
+
166
+ # figure out what kind of classdef we have
167
+ if len(node.children) == 7:
168
+ # Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite])
169
+ # 0 1 2 3 4 5 6
170
+ if node.children[3].type == syms.arglist:
171
+ arglist = node.children[3]
172
+ # Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite])
173
+ else:
174
+ parent = node.children[3].clone()
175
+ arglist = Node(syms.arglist, [parent])
176
+ node.set_child(3, arglist)
177
+ elif len(node.children) == 6:
178
+ # Node(classdef, ['class', 'name', '(', ')', ':', suite])
179
+ # 0 1 2 3 4 5
180
+ arglist = Node(syms.arglist, [])
181
+ node.insert_child(3, arglist)
182
+ elif len(node.children) == 4:
183
+ # Node(classdef, ['class', 'name', ':', suite])
184
+ # 0 1 2 3
185
+ arglist = Node(syms.arglist, [])
186
+ node.insert_child(2, Leaf(token.RPAR, ')'))
187
+ node.insert_child(2, arglist)
188
+ node.insert_child(2, Leaf(token.LPAR, '('))
189
+ else:
190
+ raise ValueError("Unexpected class definition")
191
+
192
+ # now stick the metaclass in the arglist
193
+ meta_txt = last_metaclass.children[0].children[0]
194
+ meta_txt.value = 'metaclass'
195
+ orig_meta_prefix = meta_txt.prefix
196
+
197
+ if arglist.children:
198
+ arglist.append_child(Leaf(token.COMMA, ','))
199
+ meta_txt.prefix = ' '
200
+ else:
201
+ meta_txt.prefix = ''
202
+
203
+ # compact the expression "metaclass = Meta" -> "metaclass=Meta"
204
+ expr_stmt = last_metaclass.children[0]
205
+ assert expr_stmt.type == syms.expr_stmt
206
+ expr_stmt.children[1].prefix = ''
207
+ expr_stmt.children[2].prefix = ''
208
+
209
+ arglist.append_child(last_metaclass)
210
+
211
+ fixup_indent(suite)
212
+
213
+ # check for empty suite
214
+ if not suite.children:
215
+ # one-liner that was just __metaclass_
216
+ suite.remove()
217
+ pass_leaf = Leaf(text_type, 'pass')
218
+ pass_leaf.prefix = orig_meta_prefix
219
+ node.append_child(pass_leaf)
220
+ node.append_child(Leaf(token.NEWLINE, '\n'))
221
+
222
+ elif len(suite.children) > 1 and \
223
+ (suite.children[-2].type == token.INDENT and
224
+ suite.children[-1].type == token.DEDENT):
225
+ # there was only one line in the class body and it was __metaclass__
226
+ pass_leaf = Leaf(text_type, 'pass')
227
+ suite.insert_child(-1, pass_leaf)
228
+ suite.insert_child(-1, Leaf(token.NEWLINE, '\n'))
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_methodattrs.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix bound method attributes (method.im_? -> method.__?__).
2
+ """
3
+ # Author: Christian Heimes
4
+
5
+ # Local imports
6
+ from .. import fixer_base
7
+ from ..fixer_util import Name
8
+
9
+ MAP = {
10
+ "im_func" : "__func__",
11
+ "im_self" : "__self__",
12
+ "im_class" : "__self__.__class__"
13
+ }
14
+
15
+ class FixMethodattrs(fixer_base.BaseFix):
16
+ BM_compatible = True
17
+ PATTERN = """
18
+ power< any+ trailer< '.' attr=('im_func' | 'im_self' | 'im_class') > any* >
19
+ """
20
+
21
+ def transform(self, node, results):
22
+ attr = results["attr"][0]
23
+ new = MAP[attr.value]
24
+ attr.replace(Name(new, prefix=attr.prefix))
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_ne.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer that turns <> into !=."""
5
+
6
+ # Local imports
7
+ from .. import pytree
8
+ from ..pgen2 import token
9
+ from .. import fixer_base
10
+
11
+
12
+ class FixNe(fixer_base.BaseFix):
13
+ # This is so simple that we don't need the pattern compiler.
14
+
15
+ _accept_type = token.NOTEQUAL
16
+
17
+ def match(self, node):
18
+ # Override
19
+ return node.value == "<>"
20
+
21
+ def transform(self, node, results):
22
+ new = pytree.Leaf(token.NOTEQUAL, "!=", prefix=node.prefix)
23
+ return new
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_next.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for it.next() -> next(it), per PEP 3114."""
2
+ # Author: Collin Winter
3
+
4
+ # Things that currently aren't covered:
5
+ # - listcomp "next" names aren't warned
6
+ # - "with" statement targets aren't checked
7
+
8
+ # Local imports
9
+ from ..pgen2 import token
10
+ from ..pygram import python_symbols as syms
11
+ from .. import fixer_base
12
+ from ..fixer_util import Name, Call, find_binding
13
+
14
+ bind_warning = "Calls to builtin next() possibly shadowed by global binding"
15
+
16
+
17
+ class FixNext(fixer_base.BaseFix):
18
+ BM_compatible = True
19
+ PATTERN = """
20
+ power< base=any+ trailer< '.' attr='next' > trailer< '(' ')' > >
21
+ |
22
+ power< head=any+ trailer< '.' attr='next' > not trailer< '(' ')' > >
23
+ |
24
+ classdef< 'class' any+ ':'
25
+ suite< any*
26
+ funcdef< 'def'
27
+ name='next'
28
+ parameters< '(' NAME ')' > any+ >
29
+ any* > >
30
+ |
31
+ global=global_stmt< 'global' any* 'next' any* >
32
+ """
33
+
34
+ order = "pre" # Pre-order tree traversal
35
+
36
+ def start_tree(self, tree, filename):
37
+ super(FixNext, self).start_tree(tree, filename)
38
+
39
+ n = find_binding('next', tree)
40
+ if n:
41
+ self.warning(n, bind_warning)
42
+ self.shadowed_next = True
43
+ else:
44
+ self.shadowed_next = False
45
+
46
+ def transform(self, node, results):
47
+ assert results
48
+
49
+ base = results.get("base")
50
+ attr = results.get("attr")
51
+ name = results.get("name")
52
+
53
+ if base:
54
+ if self.shadowed_next:
55
+ attr.replace(Name("__next__", prefix=attr.prefix))
56
+ else:
57
+ base = [n.clone() for n in base]
58
+ base[0].prefix = ""
59
+ node.replace(Call(Name("next", prefix=node.prefix), base))
60
+ elif name:
61
+ n = Name("__next__", prefix=name.prefix)
62
+ name.replace(n)
63
+ elif attr:
64
+ # We don't do this transformation if we're assigning to "x.next".
65
+ # Unfortunately, it doesn't seem possible to do this in PATTERN,
66
+ # so it's being done here.
67
+ if is_assign_target(node):
68
+ head = results["head"]
69
+ if "".join([str(n) for n in head]).strip() == '__builtin__':
70
+ self.warning(node, bind_warning)
71
+ return
72
+ attr.replace(Name("__next__"))
73
+ elif "global" in results:
74
+ self.warning(node, bind_warning)
75
+ self.shadowed_next = True
76
+
77
+
78
+ ### The following functions help test if node is part of an assignment
79
+ ### target.
80
+
81
+ def is_assign_target(node):
82
+ assign = find_assign(node)
83
+ if assign is None:
84
+ return False
85
+
86
+ for child in assign.children:
87
+ if child.type == token.EQUAL:
88
+ return False
89
+ elif is_subtree(child, node):
90
+ return True
91
+ return False
92
+
93
+ def find_assign(node):
94
+ if node.type == syms.expr_stmt:
95
+ return node
96
+ if node.type == syms.simple_stmt or node.parent is None:
97
+ return None
98
+ return find_assign(node.parent)
99
+
100
+ def is_subtree(root, node):
101
+ if root == node:
102
+ return True
103
+ return any(is_subtree(c, node) for c in root.children)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_nonzero.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for __nonzero__ -> __bool__ methods."""
2
+ # Author: Collin Winter
3
+
4
+ # Local imports
5
+ from .. import fixer_base
6
+ from ..fixer_util import Name
7
+
8
+ class FixNonzero(fixer_base.BaseFix):
9
+ BM_compatible = True
10
+ PATTERN = """
11
+ classdef< 'class' any+ ':'
12
+ suite< any*
13
+ funcdef< 'def' name='__nonzero__'
14
+ parameters< '(' NAME ')' > any+ >
15
+ any* > >
16
+ """
17
+
18
+ def transform(self, node, results):
19
+ name = results["name"]
20
+ new = Name("__bool__", prefix=name.prefix)
21
+ name.replace(new)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_numliterals.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer that turns 1L into 1, 0755 into 0o755.
2
+ """
3
+ # Copyright 2007 Georg Brandl.
4
+ # Licensed to PSF under a Contributor Agreement.
5
+
6
+ # Local imports
7
+ from ..pgen2 import token
8
+ from .. import fixer_base
9
+ from ..fixer_util import Number
10
+
11
+
12
+ class FixNumliterals(fixer_base.BaseFix):
13
+ # This is so simple that we don't need the pattern compiler.
14
+
15
+ _accept_type = token.NUMBER
16
+
17
+ def match(self, node):
18
+ # Override
19
+ return (node.value.startswith("0") or node.value[-1] in "Ll")
20
+
21
+ def transform(self, node, results):
22
+ val = node.value
23
+ if val[-1] in 'Ll':
24
+ val = val[:-1]
25
+ elif val.startswith('0') and val.isdigit() and len(set(val)) > 1:
26
+ val = "0o" + val[1:]
27
+
28
+ return Number(val, prefix=node.prefix)
miniconda3/pkgs/python-3.10.20-h741d88c_0/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
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_paren.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer that adds parentheses where they are required
2
+
3
+ This converts ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``."""
4
+
5
+ # By Taek Joo Kim and Benjamin Peterson
6
+
7
+ # Local imports
8
+ from .. import fixer_base
9
+ from ..fixer_util import LParen, RParen
10
+
11
+ # XXX This doesn't support nested for loops like [x for x in 1, 2 for x in 1, 2]
12
+ class FixParen(fixer_base.BaseFix):
13
+ BM_compatible = True
14
+
15
+ PATTERN = """
16
+ atom< ('[' | '(')
17
+ (listmaker< any
18
+ comp_for<
19
+ 'for' NAME 'in'
20
+ target=testlist_safe< any (',' any)+ [',']
21
+ >
22
+ [any]
23
+ >
24
+ >
25
+ |
26
+ testlist_gexp< any
27
+ comp_for<
28
+ 'for' NAME 'in'
29
+ target=testlist_safe< any (',' any)+ [',']
30
+ >
31
+ [any]
32
+ >
33
+ >)
34
+ (']' | ')') >
35
+ """
36
+
37
+ def transform(self, node, results):
38
+ target = results["target"]
39
+
40
+ lparen = LParen()
41
+ lparen.prefix = target.prefix
42
+ target.prefix = "" # Make it hug the parentheses
43
+ target.insert_child(0, lparen)
44
+ target.append_child(RParen())
miniconda3/pkgs/python-3.10.20-h741d88c_0/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)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_raise.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for 'raise E, V, T'
2
+
3
+ raise -> raise
4
+ raise E -> raise E
5
+ raise E, V -> raise E(V)
6
+ raise E, V, T -> raise E(V).with_traceback(T)
7
+ raise E, None, T -> raise E.with_traceback(T)
8
+
9
+ raise (((E, E'), E''), E'''), V -> raise E(V)
10
+ raise "foo", V, T -> warns about string exceptions
11
+
12
+
13
+ CAVEATS:
14
+ 1) "raise E, V" will be incorrectly translated if V is an exception
15
+ instance. The correct Python 3 idiom is
16
+
17
+ raise E from V
18
+
19
+ but since we can't detect instance-hood by syntax alone and since
20
+ any client code would have to be changed as well, we don't automate
21
+ this.
22
+ """
23
+ # Author: Collin Winter
24
+
25
+ # Local imports
26
+ from .. import pytree
27
+ from ..pgen2 import token
28
+ from .. import fixer_base
29
+ from ..fixer_util import Name, Call, Attr, ArgList, is_tuple
30
+
31
+ class FixRaise(fixer_base.BaseFix):
32
+
33
+ BM_compatible = True
34
+ PATTERN = """
35
+ raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] >
36
+ """
37
+
38
+ def transform(self, node, results):
39
+ syms = self.syms
40
+
41
+ exc = results["exc"].clone()
42
+ if exc.type == token.STRING:
43
+ msg = "Python 3 does not support string exceptions"
44
+ self.cannot_convert(node, msg)
45
+ return
46
+
47
+ # Python 2 supports
48
+ # raise ((((E1, E2), E3), E4), E5), V
49
+ # as a synonym for
50
+ # raise E1, V
51
+ # Since Python 3 will not support this, we recurse down any tuple
52
+ # literals, always taking the first element.
53
+ if is_tuple(exc):
54
+ while is_tuple(exc):
55
+ # exc.children[1:-1] is the unparenthesized tuple
56
+ # exc.children[1].children[0] is the first element of the tuple
57
+ exc = exc.children[1].children[0].clone()
58
+ exc.prefix = " "
59
+
60
+ if "val" not in results:
61
+ # One-argument raise
62
+ new = pytree.Node(syms.raise_stmt, [Name("raise"), exc])
63
+ new.prefix = node.prefix
64
+ return new
65
+
66
+ val = results["val"].clone()
67
+ if is_tuple(val):
68
+ args = [c.clone() for c in val.children[1:-1]]
69
+ else:
70
+ val.prefix = ""
71
+ args = [val]
72
+
73
+ if "tb" in results:
74
+ tb = results["tb"].clone()
75
+ tb.prefix = ""
76
+
77
+ e = exc
78
+ # If there's a traceback and None is passed as the value, then don't
79
+ # add a call, since the user probably just wants to add a
80
+ # traceback. See issue #9661.
81
+ if val.type != token.NAME or val.value != "None":
82
+ e = Call(exc, args)
83
+ with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])]
84
+ new = pytree.Node(syms.simple_stmt, [Name("raise")] + with_tb)
85
+ new.prefix = node.prefix
86
+ return new
87
+ else:
88
+ return pytree.Node(syms.raise_stmt,
89
+ [Name("raise"), Call(exc, args)],
90
+ prefix=node.prefix)
miniconda3/pkgs/python-3.10.20-h741d88c_0/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))
miniconda3/pkgs/python-3.10.20-h741d88c_0/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)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_reload.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for reload().
2
+
3
+ reload(s) -> importlib.reload(s)"""
4
+
5
+ # Local imports
6
+ from .. import fixer_base
7
+ from ..fixer_util import ImportAndCall, touch_import
8
+
9
+
10
+ class FixReload(fixer_base.BaseFix):
11
+ BM_compatible = True
12
+ order = "pre"
13
+
14
+ PATTERN = """
15
+ power< 'reload'
16
+ trailer< lpar='('
17
+ ( not(arglist | argument<any '=' any>) obj=any
18
+ | obj=arglist<(not argument<any '=' any>) any ','> )
19
+ rpar=')' >
20
+ after=any*
21
+ >
22
+ """
23
+
24
+ def transform(self, node, results):
25
+ if results:
26
+ # I feel like we should be able to express this logic in the
27
+ # PATTERN above but I don't know how to do it so...
28
+ obj = results['obj']
29
+ if obj:
30
+ if (obj.type == self.syms.argument and
31
+ obj.children[0].value in {'**', '*'}):
32
+ return # Make no change.
33
+ names = ('importlib', 'reload')
34
+ new = ImportAndCall(node, results, names)
35
+ touch_import(None, 'importlib', node)
36
+ return new
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_renames.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix incompatible renames
2
+
3
+ Fixes:
4
+ * sys.maxint -> sys.maxsize
5
+ """
6
+ # Author: Christian Heimes
7
+ # based on Collin Winter's fix_import
8
+
9
+ # Local imports
10
+ from .. import fixer_base
11
+ from ..fixer_util import Name, attr_chain
12
+
13
+ MAPPING = {"sys": {"maxint" : "maxsize"},
14
+ }
15
+ LOOKUP = {}
16
+
17
+ def alternates(members):
18
+ return "(" + "|".join(map(repr, members)) + ")"
19
+
20
+
21
+ def build_pattern():
22
+ #bare = set()
23
+ for module, replace in list(MAPPING.items()):
24
+ for old_attr, new_attr in list(replace.items()):
25
+ LOOKUP[(module, old_attr)] = new_attr
26
+ #bare.add(module)
27
+ #bare.add(old_attr)
28
+ #yield """
29
+ # import_name< 'import' (module=%r
30
+ # | dotted_as_names< any* module=%r any* >) >
31
+ # """ % (module, module)
32
+ yield """
33
+ import_from< 'from' module_name=%r 'import'
34
+ ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
35
+ """ % (module, old_attr, old_attr)
36
+ yield """
37
+ power< module_name=%r trailer< '.' attr_name=%r > any* >
38
+ """ % (module, old_attr)
39
+ #yield """bare_name=%s""" % alternates(bare)
40
+
41
+
42
+ class FixRenames(fixer_base.BaseFix):
43
+ BM_compatible = True
44
+ PATTERN = "|".join(build_pattern())
45
+
46
+ order = "pre" # Pre-order tree traversal
47
+
48
+ # Don't match the node if it's within another match
49
+ def match(self, node):
50
+ match = super(FixRenames, self).match
51
+ results = match(node)
52
+ if results:
53
+ if any(match(obj) for obj in attr_chain(node, "parent")):
54
+ return False
55
+ return results
56
+ return False
57
+
58
+ #def start_tree(self, tree, filename):
59
+ # super(FixRenames, self).start_tree(tree, filename)
60
+ # self.replace = {}
61
+
62
+ def transform(self, node, results):
63
+ mod_name = results.get("module_name")
64
+ attr_name = results.get("attr_name")
65
+ #bare_name = results.get("bare_name")
66
+ #import_mod = results.get("module")
67
+
68
+ if mod_name and attr_name:
69
+ new_attr = LOOKUP[(mod_name.value, attr_name.value)]
70
+ attr_name.replace(Name(new_attr, prefix=attr_name.prefix))
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_repr.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer that transforms `xyzzy` into repr(xyzzy)."""
5
+
6
+ # Local imports
7
+ from .. import fixer_base
8
+ from ..fixer_util import Call, Name, parenthesize
9
+
10
+
11
+ class FixRepr(fixer_base.BaseFix):
12
+
13
+ BM_compatible = True
14
+ PATTERN = """
15
+ atom < '`' expr=any '`' >
16
+ """
17
+
18
+ def transform(self, node, results):
19
+ expr = results["expr"].clone()
20
+
21
+ if expr.type == self.syms.testlist1:
22
+ expr = parenthesize(expr)
23
+ return Call(Name("repr"), [expr], prefix=node.prefix)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_set_literal.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optional fixer to transform set() calls to set literals.
3
+ """
4
+
5
+ # Author: Benjamin Peterson
6
+
7
+ from lib2to3 import fixer_base, pytree
8
+ from lib2to3.fixer_util import token, syms
9
+
10
+
11
+
12
+ class FixSetLiteral(fixer_base.BaseFix):
13
+
14
+ BM_compatible = True
15
+ explicit = True
16
+
17
+ PATTERN = """power< 'set' trailer< '('
18
+ (atom=atom< '[' (items=listmaker< any ((',' any)* [',']) >
19
+ |
20
+ single=any) ']' >
21
+ |
22
+ atom< '(' items=testlist_gexp< any ((',' any)* [',']) > ')' >
23
+ )
24
+ ')' > >
25
+ """
26
+
27
+ def transform(self, node, results):
28
+ single = results.get("single")
29
+ if single:
30
+ # Make a fake listmaker
31
+ fake = pytree.Node(syms.listmaker, [single.clone()])
32
+ single.replace(fake)
33
+ items = fake
34
+ else:
35
+ items = results["items"]
36
+
37
+ # Build the contents of the literal
38
+ literal = [pytree.Leaf(token.LBRACE, "{")]
39
+ literal.extend(n.clone() for n in items.children)
40
+ literal.append(pytree.Leaf(token.RBRACE, "}"))
41
+ # Set the prefix of the right brace to that of the ')' or ']'
42
+ literal[-1].prefix = items.next_sibling.prefix
43
+ maker = pytree.Node(syms.dictsetmaker, literal)
44
+ maker.prefix = node.prefix
45
+
46
+ # If the original was a one tuple, we need to remove the extra comma.
47
+ if len(maker.children) == 4:
48
+ n = maker.children[2]
49
+ n.remove()
50
+ maker.children[-1].prefix = n.prefix
51
+
52
+ # Finally, replace the set call with our shiny new literal.
53
+ return maker
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_standarderror.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer for StandardError -> Exception."""
5
+
6
+ # Local imports
7
+ from .. import fixer_base
8
+ from ..fixer_util import Name
9
+
10
+
11
+ class FixStandarderror(fixer_base.BaseFix):
12
+ BM_compatible = True
13
+ PATTERN = """
14
+ 'StandardError'
15
+ """
16
+
17
+ def transform(self, node, results):
18
+ return Name("Exception", prefix=node.prefix)
miniconda3/pkgs/python-3.10.20-h741d88c_0/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)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_throw.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for generator.throw(E, V, T).
2
+
3
+ g.throw(E) -> g.throw(E)
4
+ g.throw(E, V) -> g.throw(E(V))
5
+ g.throw(E, V, T) -> g.throw(E(V).with_traceback(T))
6
+
7
+ g.throw("foo"[, V[, T]]) will warn about string exceptions."""
8
+ # Author: Collin Winter
9
+
10
+ # Local imports
11
+ from .. import pytree
12
+ from ..pgen2 import token
13
+ from .. import fixer_base
14
+ from ..fixer_util import Name, Call, ArgList, Attr, is_tuple
15
+
16
+ class FixThrow(fixer_base.BaseFix):
17
+ BM_compatible = True
18
+ PATTERN = """
19
+ power< any trailer< '.' 'throw' >
20
+ trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' >
21
+ >
22
+ |
23
+ power< any trailer< '.' 'throw' > trailer< '(' exc=any ')' > >
24
+ """
25
+
26
+ def transform(self, node, results):
27
+ syms = self.syms
28
+
29
+ exc = results["exc"].clone()
30
+ if exc.type is token.STRING:
31
+ self.cannot_convert(node, "Python 3 does not support string exceptions")
32
+ return
33
+
34
+ # Leave "g.throw(E)" alone
35
+ val = results.get("val")
36
+ if val is None:
37
+ return
38
+
39
+ val = val.clone()
40
+ if is_tuple(val):
41
+ args = [c.clone() for c in val.children[1:-1]]
42
+ else:
43
+ val.prefix = ""
44
+ args = [val]
45
+
46
+ throw_args = results["args"]
47
+
48
+ if "tb" in results:
49
+ tb = results["tb"].clone()
50
+ tb.prefix = ""
51
+
52
+ e = Call(exc, args)
53
+ with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])]
54
+ throw_args.replace(pytree.Node(syms.power, with_tb))
55
+ else:
56
+ throw_args.replace(Call(exc, args))
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_tuple_params.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer for function definitions with tuple parameters.
2
+
3
+ def func(((a, b), c), d):
4
+ ...
5
+
6
+ ->
7
+
8
+ def func(x, d):
9
+ ((a, b), c) = x
10
+ ...
11
+
12
+ It will also support lambdas:
13
+
14
+ lambda (x, y): x + y -> lambda t: t[0] + t[1]
15
+
16
+ # The parens are a syntax error in Python 3
17
+ lambda (x): x + y -> lambda x: x + y
18
+ """
19
+ # Author: Collin Winter
20
+
21
+ # Local imports
22
+ from .. import pytree
23
+ from ..pgen2 import token
24
+ from .. import fixer_base
25
+ from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms
26
+
27
+ def is_docstring(stmt):
28
+ return isinstance(stmt, pytree.Node) and \
29
+ stmt.children[0].type == token.STRING
30
+
31
+ class FixTupleParams(fixer_base.BaseFix):
32
+ run_order = 4 #use a lower order since lambda is part of other
33
+ #patterns
34
+ BM_compatible = True
35
+
36
+ PATTERN = """
37
+ funcdef< 'def' any parameters< '(' args=any ')' >
38
+ ['->' any] ':' suite=any+ >
39
+ |
40
+ lambda=
41
+ lambdef< 'lambda' args=vfpdef< '(' inner=any ')' >
42
+ ':' body=any
43
+ >
44
+ """
45
+
46
+ def transform(self, node, results):
47
+ if "lambda" in results:
48
+ return self.transform_lambda(node, results)
49
+
50
+ new_lines = []
51
+ suite = results["suite"]
52
+ args = results["args"]
53
+ # This crap is so "def foo(...): x = 5; y = 7" is handled correctly.
54
+ # TODO(cwinter): suite-cleanup
55
+ if suite[0].children[1].type == token.INDENT:
56
+ start = 2
57
+ indent = suite[0].children[1].value
58
+ end = Newline()
59
+ else:
60
+ start = 0
61
+ indent = "; "
62
+ end = pytree.Leaf(token.INDENT, "")
63
+
64
+ # We need access to self for new_name(), and making this a method
65
+ # doesn't feel right. Closing over self and new_lines makes the
66
+ # code below cleaner.
67
+ def handle_tuple(tuple_arg, add_prefix=False):
68
+ n = Name(self.new_name())
69
+ arg = tuple_arg.clone()
70
+ arg.prefix = ""
71
+ stmt = Assign(arg, n.clone())
72
+ if add_prefix:
73
+ n.prefix = " "
74
+ tuple_arg.replace(n)
75
+ new_lines.append(pytree.Node(syms.simple_stmt,
76
+ [stmt, end.clone()]))
77
+
78
+ if args.type == syms.tfpdef:
79
+ handle_tuple(args)
80
+ elif args.type == syms.typedargslist:
81
+ for i, arg in enumerate(args.children):
82
+ if arg.type == syms.tfpdef:
83
+ # Without add_prefix, the emitted code is correct,
84
+ # just ugly.
85
+ handle_tuple(arg, add_prefix=(i > 0))
86
+
87
+ if not new_lines:
88
+ return
89
+
90
+ # This isn't strictly necessary, but it plays nicely with other fixers.
91
+ # TODO(cwinter) get rid of this when children becomes a smart list
92
+ for line in new_lines:
93
+ line.parent = suite[0]
94
+
95
+ # TODO(cwinter) suite-cleanup
96
+ after = start
97
+ if start == 0:
98
+ new_lines[0].prefix = " "
99
+ elif is_docstring(suite[0].children[start]):
100
+ new_lines[0].prefix = indent
101
+ after = start + 1
102
+
103
+ for line in new_lines:
104
+ line.parent = suite[0]
105
+ suite[0].children[after:after] = new_lines
106
+ for i in range(after+1, after+len(new_lines)+1):
107
+ suite[0].children[i].prefix = indent
108
+ suite[0].changed()
109
+
110
+ def transform_lambda(self, node, results):
111
+ args = results["args"]
112
+ body = results["body"]
113
+ inner = simplify_args(results["inner"])
114
+
115
+ # Replace lambda ((((x)))): x with lambda x: x
116
+ if inner.type == token.NAME:
117
+ inner = inner.clone()
118
+ inner.prefix = " "
119
+ args.replace(inner)
120
+ return
121
+
122
+ params = find_params(args)
123
+ to_index = map_to_index(params)
124
+ tup_name = self.new_name(tuple_name(params))
125
+
126
+ new_param = Name(tup_name, prefix=" ")
127
+ args.replace(new_param.clone())
128
+ for n in body.post_order():
129
+ if n.type == token.NAME and n.value in to_index:
130
+ subscripts = [c.clone() for c in to_index[n.value]]
131
+ new = pytree.Node(syms.power,
132
+ [new_param.clone()] + subscripts)
133
+ new.prefix = n.prefix
134
+ n.replace(new)
135
+
136
+
137
+ ### Helper functions for transform_lambda()
138
+
139
+ def simplify_args(node):
140
+ if node.type in (syms.vfplist, token.NAME):
141
+ return node
142
+ elif node.type == syms.vfpdef:
143
+ # These look like vfpdef< '(' x ')' > where x is NAME
144
+ # or another vfpdef instance (leading to recursion).
145
+ while node.type == syms.vfpdef:
146
+ node = node.children[1]
147
+ return node
148
+ raise RuntimeError("Received unexpected node %s" % node)
149
+
150
+ def find_params(node):
151
+ if node.type == syms.vfpdef:
152
+ return find_params(node.children[1])
153
+ elif node.type == token.NAME:
154
+ return node.value
155
+ return [find_params(c) for c in node.children if c.type != token.COMMA]
156
+
157
+ def map_to_index(param_list, prefix=[], d=None):
158
+ if d is None:
159
+ d = {}
160
+ for i, obj in enumerate(param_list):
161
+ trailer = [Subscript(Number(str(i)))]
162
+ if isinstance(obj, list):
163
+ map_to_index(obj, trailer, d=d)
164
+ else:
165
+ d[obj] = prefix + trailer
166
+ return d
167
+
168
+ def tuple_name(param_list):
169
+ l = []
170
+ for obj in param_list:
171
+ if isinstance(obj, list):
172
+ l.append(tuple_name(obj))
173
+ else:
174
+ l.append(obj)
175
+ return "_".join(l)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_types.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer for removing uses of the types module.
5
+
6
+ These work for only the known names in the types module. The forms above
7
+ can include types. or not. ie, It is assumed the module is imported either as:
8
+
9
+ import types
10
+ from types import ... # either * or specific types
11
+
12
+ The import statements are not modified.
13
+
14
+ There should be another fixer that handles at least the following constants:
15
+
16
+ type([]) -> list
17
+ type(()) -> tuple
18
+ type('') -> str
19
+
20
+ """
21
+
22
+ # Local imports
23
+ from .. import fixer_base
24
+ from ..fixer_util import Name
25
+
26
+ _TYPE_MAPPING = {
27
+ 'BooleanType' : 'bool',
28
+ 'BufferType' : 'memoryview',
29
+ 'ClassType' : 'type',
30
+ 'ComplexType' : 'complex',
31
+ 'DictType': 'dict',
32
+ 'DictionaryType' : 'dict',
33
+ 'EllipsisType' : 'type(Ellipsis)',
34
+ #'FileType' : 'io.IOBase',
35
+ 'FloatType': 'float',
36
+ 'IntType': 'int',
37
+ 'ListType': 'list',
38
+ 'LongType': 'int',
39
+ 'ObjectType' : 'object',
40
+ 'NoneType': 'type(None)',
41
+ 'NotImplementedType' : 'type(NotImplemented)',
42
+ 'SliceType' : 'slice',
43
+ 'StringType': 'bytes', # XXX ?
44
+ 'StringTypes' : '(str,)', # XXX ?
45
+ 'TupleType': 'tuple',
46
+ 'TypeType' : 'type',
47
+ 'UnicodeType': 'str',
48
+ 'XRangeType' : 'range',
49
+ }
50
+
51
+ _pats = ["power< 'types' trailer< '.' name='%s' > >" % t for t in _TYPE_MAPPING]
52
+
53
+ class FixTypes(fixer_base.BaseFix):
54
+ BM_compatible = True
55
+ PATTERN = '|'.join(_pats)
56
+
57
+ def transform(self, node, results):
58
+ new_value = _TYPE_MAPPING.get(results["name"].value)
59
+ if new_value:
60
+ return Name(new_value, prefix=node.prefix)
61
+ return None
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_unicode.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Fixer for unicode.
2
+
3
+ * Changes unicode to str and unichr to chr.
4
+
5
+ * If "...\u..." is not unicode literal change it into "...\\u...".
6
+
7
+ * Change u"..." into "...".
8
+
9
+ """
10
+
11
+ from ..pgen2 import token
12
+ from .. import fixer_base
13
+
14
+ _mapping = {"unichr" : "chr", "unicode" : "str"}
15
+
16
+ class FixUnicode(fixer_base.BaseFix):
17
+ BM_compatible = True
18
+ PATTERN = "STRING | 'unicode' | 'unichr'"
19
+
20
+ def start_tree(self, tree, filename):
21
+ super(FixUnicode, self).start_tree(tree, filename)
22
+ self.unicode_literals = 'unicode_literals' in tree.future_features
23
+
24
+ def transform(self, node, results):
25
+ if node.type == token.NAME:
26
+ new = node.clone()
27
+ new.value = _mapping[node.value]
28
+ return new
29
+ elif node.type == token.STRING:
30
+ val = node.value
31
+ if not self.unicode_literals and val[0] in '\'"' and '\\' in val:
32
+ val = r'\\'.join([
33
+ v.replace('\\u', r'\\u').replace('\\U', r'\\U')
34
+ for v in val.split(r'\\')
35
+ ])
36
+ if val[0] in 'uU':
37
+ val = val[1:]
38
+ if val == node.value:
39
+ return node
40
+ new = node.clone()
41
+ new.value = val
42
+ return new
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_urllib.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix changes imports of urllib which are now incompatible.
2
+ This is rather similar to fix_imports, but because of the more
3
+ complex nature of the fixing for urllib, it has its own fixer.
4
+ """
5
+ # Author: Nick Edds
6
+
7
+ # Local imports
8
+ from lib2to3.fixes.fix_imports import alternates, FixImports
9
+ from lib2to3.fixer_util import (Name, Comma, FromImport, Newline,
10
+ find_indentation, Node, syms)
11
+
12
+ MAPPING = {"urllib": [
13
+ ("urllib.request",
14
+ ["URLopener", "FancyURLopener", "urlretrieve",
15
+ "_urlopener", "urlopen", "urlcleanup",
16
+ "pathname2url", "url2pathname", "getproxies"]),
17
+ ("urllib.parse",
18
+ ["quote", "quote_plus", "unquote", "unquote_plus",
19
+ "urlencode", "splitattr", "splithost", "splitnport",
20
+ "splitpasswd", "splitport", "splitquery", "splittag",
21
+ "splittype", "splituser", "splitvalue", ]),
22
+ ("urllib.error",
23
+ ["ContentTooShortError"])],
24
+ "urllib2" : [
25
+ ("urllib.request",
26
+ ["urlopen", "install_opener", "build_opener",
27
+ "Request", "OpenerDirector", "BaseHandler",
28
+ "HTTPDefaultErrorHandler", "HTTPRedirectHandler",
29
+ "HTTPCookieProcessor", "ProxyHandler",
30
+ "HTTPPasswordMgr",
31
+ "HTTPPasswordMgrWithDefaultRealm",
32
+ "AbstractBasicAuthHandler",
33
+ "HTTPBasicAuthHandler", "ProxyBasicAuthHandler",
34
+ "AbstractDigestAuthHandler",
35
+ "HTTPDigestAuthHandler", "ProxyDigestAuthHandler",
36
+ "HTTPHandler", "HTTPSHandler", "FileHandler",
37
+ "FTPHandler", "CacheFTPHandler",
38
+ "UnknownHandler"]),
39
+ ("urllib.error",
40
+ ["URLError", "HTTPError"]),
41
+ ]
42
+ }
43
+
44
+ # Duplicate the url parsing functions for urllib2.
45
+ MAPPING["urllib2"].append(MAPPING["urllib"][1])
46
+
47
+
48
+ def build_pattern():
49
+ bare = set()
50
+ for old_module, changes in MAPPING.items():
51
+ for change in changes:
52
+ new_module, members = change
53
+ members = alternates(members)
54
+ yield """import_name< 'import' (module=%r
55
+ | dotted_as_names< any* module=%r any* >) >
56
+ """ % (old_module, old_module)
57
+ yield """import_from< 'from' mod_member=%r 'import'
58
+ ( member=%s | import_as_name< member=%s 'as' any > |
59
+ import_as_names< members=any* >) >
60
+ """ % (old_module, members, members)
61
+ yield """import_from< 'from' module_star=%r 'import' star='*' >
62
+ """ % old_module
63
+ yield """import_name< 'import'
64
+ dotted_as_name< module_as=%r 'as' any > >
65
+ """ % old_module
66
+ # bare_with_attr has a special significance for FixImports.match().
67
+ yield """power< bare_with_attr=%r trailer< '.' member=%s > any* >
68
+ """ % (old_module, members)
69
+
70
+
71
+ class FixUrllib(FixImports):
72
+
73
+ def build_pattern(self):
74
+ return "|".join(build_pattern())
75
+
76
+ def transform_import(self, node, results):
77
+ """Transform for the basic import case. Replaces the old
78
+ import name with a comma separated list of its
79
+ replacements.
80
+ """
81
+ import_mod = results.get("module")
82
+ pref = import_mod.prefix
83
+
84
+ names = []
85
+
86
+ # create a Node list of the replacement modules
87
+ for name in MAPPING[import_mod.value][:-1]:
88
+ names.extend([Name(name[0], prefix=pref), Comma()])
89
+ names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
90
+ import_mod.replace(names)
91
+
92
+ def transform_member(self, node, results):
93
+ """Transform for imports of specific module elements. Replaces
94
+ the module to be imported from with the appropriate new
95
+ module.
96
+ """
97
+ mod_member = results.get("mod_member")
98
+ pref = mod_member.prefix
99
+ member = results.get("member")
100
+
101
+ # Simple case with only a single member being imported
102
+ if member:
103
+ # this may be a list of length one, or just a node
104
+ if isinstance(member, list):
105
+ member = member[0]
106
+ new_name = None
107
+ for change in MAPPING[mod_member.value]:
108
+ if member.value in change[1]:
109
+ new_name = change[0]
110
+ break
111
+ if new_name:
112
+ mod_member.replace(Name(new_name, prefix=pref))
113
+ else:
114
+ self.cannot_convert(node, "This is an invalid module element")
115
+
116
+ # Multiple members being imported
117
+ else:
118
+ # a dictionary for replacements, order matters
119
+ modules = []
120
+ mod_dict = {}
121
+ members = results["members"]
122
+ for member in members:
123
+ # we only care about the actual members
124
+ if member.type == syms.import_as_name:
125
+ as_name = member.children[2].value
126
+ member_name = member.children[0].value
127
+ else:
128
+ member_name = member.value
129
+ as_name = None
130
+ if member_name != ",":
131
+ for change in MAPPING[mod_member.value]:
132
+ if member_name in change[1]:
133
+ if change[0] not in mod_dict:
134
+ modules.append(change[0])
135
+ mod_dict.setdefault(change[0], []).append(member)
136
+
137
+ new_nodes = []
138
+ indentation = find_indentation(node)
139
+ first = True
140
+ def handle_name(name, prefix):
141
+ if name.type == syms.import_as_name:
142
+ kids = [Name(name.children[0].value, prefix=prefix),
143
+ name.children[1].clone(),
144
+ name.children[2].clone()]
145
+ return [Node(syms.import_as_name, kids)]
146
+ return [Name(name.value, prefix=prefix)]
147
+ for module in modules:
148
+ elts = mod_dict[module]
149
+ names = []
150
+ for elt in elts[:-1]:
151
+ names.extend(handle_name(elt, pref))
152
+ names.append(Comma())
153
+ names.extend(handle_name(elts[-1], pref))
154
+ new = FromImport(module, names)
155
+ if not first or node.parent.prefix.endswith(indentation):
156
+ new.prefix = indentation
157
+ new_nodes.append(new)
158
+ first = False
159
+ if new_nodes:
160
+ nodes = []
161
+ for new_node in new_nodes[:-1]:
162
+ nodes.extend([new_node, Newline()])
163
+ nodes.append(new_nodes[-1])
164
+ node.replace(nodes)
165
+ else:
166
+ self.cannot_convert(node, "All module elements are invalid")
167
+
168
+ def transform_dot(self, node, results):
169
+ """Transform for calls to module members in code."""
170
+ module_dot = results.get("bare_with_attr")
171
+ member = results.get("member")
172
+ new_name = None
173
+ if isinstance(member, list):
174
+ member = member[0]
175
+ for change in MAPPING[module_dot.value]:
176
+ if member.value in change[1]:
177
+ new_name = change[0]
178
+ break
179
+ if new_name:
180
+ module_dot.replace(Name(new_name,
181
+ prefix=module_dot.prefix))
182
+ else:
183
+ self.cannot_convert(node, "This is an invalid module element")
184
+
185
+ def transform(self, node, results):
186
+ if results.get("module"):
187
+ self.transform_import(node, results)
188
+ elif results.get("mod_member"):
189
+ self.transform_member(node, results)
190
+ elif results.get("bare_with_attr"):
191
+ self.transform_dot(node, results)
192
+ # Renaming and star imports are not supported for these modules.
193
+ elif results.get("module_star"):
194
+ self.cannot_convert(node, "Cannot handle star imports.")
195
+ elif results.get("module_as"):
196
+ self.cannot_convert(node, "This module is now multiple modules")
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_ws_comma.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixer that changes 'a ,b' into 'a, b'.
2
+
3
+ This also changes '{a :b}' into '{a: b}', but does not touch other
4
+ uses of colons. It does not touch other uses of whitespace.
5
+
6
+ """
7
+
8
+ from .. import pytree
9
+ from ..pgen2 import token
10
+ from .. import fixer_base
11
+
12
+ class FixWsComma(fixer_base.BaseFix):
13
+
14
+ explicit = True # The user must ask for this fixers
15
+
16
+ PATTERN = """
17
+ any<(not(',') any)+ ',' ((not(',') any)+ ',')* [not(',') any]>
18
+ """
19
+
20
+ COMMA = pytree.Leaf(token.COMMA, ",")
21
+ COLON = pytree.Leaf(token.COLON, ":")
22
+ SEPS = (COMMA, COLON)
23
+
24
+ def transform(self, node, results):
25
+ new = node.clone()
26
+ comma = False
27
+ for child in new.children:
28
+ if child in self.SEPS:
29
+ prefix = child.prefix
30
+ if prefix.isspace() and "\n" not in prefix:
31
+ child.prefix = ""
32
+ comma = True
33
+ else:
34
+ if comma:
35
+ prefix = child.prefix
36
+ if not prefix:
37
+ child.prefix = " "
38
+ comma = False
39
+ return new
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_xrange.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2007 Google, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Fixer that changes xrange(...) into range(...)."""
5
+
6
+ # Local imports
7
+ from .. import fixer_base
8
+ from ..fixer_util import Name, Call, consuming_calls
9
+ from .. import patcomp
10
+
11
+
12
+ class FixXrange(fixer_base.BaseFix):
13
+ BM_compatible = True
14
+ PATTERN = """
15
+ power<
16
+ (name='range'|name='xrange') trailer< '(' args=any ')' >
17
+ rest=any* >
18
+ """
19
+
20
+ def start_tree(self, tree, filename):
21
+ super(FixXrange, self).start_tree(tree, filename)
22
+ self.transformed_xranges = set()
23
+
24
+ def finish_tree(self, tree, filename):
25
+ self.transformed_xranges = None
26
+
27
+ def transform(self, node, results):
28
+ name = results["name"]
29
+ if name.value == "xrange":
30
+ return self.transform_xrange(node, results)
31
+ elif name.value == "range":
32
+ return self.transform_range(node, results)
33
+ else:
34
+ raise ValueError(repr(name))
35
+
36
+ def transform_xrange(self, node, results):
37
+ name = results["name"]
38
+ name.replace(Name("range", prefix=name.prefix))
39
+ # This prevents the new range call from being wrapped in a list later.
40
+ self.transformed_xranges.add(id(node))
41
+
42
+ def transform_range(self, node, results):
43
+ if (id(node) not in self.transformed_xranges and
44
+ not self.in_special_context(node)):
45
+ range_call = Call(Name("range"), [results["args"].clone()])
46
+ # Encase the range call in list().
47
+ list_call = Call(Name("list"), [range_call],
48
+ prefix=node.prefix)
49
+ # Put things that were after the range() call after the list call.
50
+ for n in results["rest"]:
51
+ list_call.append_child(n)
52
+ return list_call
53
+
54
+ P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"
55
+ p1 = patcomp.compile_pattern(P1)
56
+
57
+ P2 = """for_stmt< 'for' any 'in' node=any ':' any* >
58
+ | comp_for< 'for' any 'in' node=any any* >
59
+ | comparison< any 'in' node=any any*>
60
+ """
61
+ p2 = patcomp.compile_pattern(P2)
62
+
63
+ def in_special_context(self, node):
64
+ if node.parent is None:
65
+ return False
66
+ results = {}
67
+ if (node.parent.parent is not None and
68
+ self.p1.match(node.parent.parent, results) and
69
+ results["node"] is node):
70
+ # list(d.keys()) -> list(d.keys()), etc.
71
+ return results["func"].value in consuming_calls
72
+ # for ... in d.iterkeys() -> for ... in d.keys(), etc.
73
+ return self.p2.match(node.parent, results) and results["node"] is node
miniconda3/pkgs/python-3.10.20-h741d88c_0/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"]])
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/fixes/fix_zip.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...)
3
+ unless there exists a 'from future_builtins import zip' statement in the
4
+ top-level namespace.
5
+
6
+ We avoid the transformation if the zip() call is directly contained in
7
+ iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:.
8
+ """
9
+
10
+ # Local imports
11
+ from .. import fixer_base
12
+ from ..pytree import Node
13
+ from ..pygram import python_symbols as syms
14
+ from ..fixer_util import Name, ArgList, in_special_context
15
+
16
+
17
+ class FixZip(fixer_base.ConditionalFix):
18
+
19
+ BM_compatible = True
20
+ PATTERN = """
21
+ power< 'zip' args=trailer< '(' [any] ')' > [trailers=trailer*]
22
+ >
23
+ """
24
+
25
+ skip_on = "future_builtins.zip"
26
+
27
+ def transform(self, node, results):
28
+ if self.should_skip(node):
29
+ return
30
+
31
+ if in_special_context(node):
32
+ return None
33
+
34
+ args = results['args'].clone()
35
+ args.prefix = ""
36
+
37
+ trailers = []
38
+ if 'trailers' in results:
39
+ trailers = [n.clone() for n in results['trailers']]
40
+ for n in trailers:
41
+ n.prefix = ""
42
+
43
+ new = Node(syms.power, [Name("zip"), args], prefix="")
44
+ new = Node(syms.power, [Name("list"), ArgList([new])] + trailers)
45
+ new.prefix = node.prefix
46
+ return new
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """The pgen2 package."""
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/conv.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Convert graminit.[ch] spit out by pgen to Python code.
5
+
6
+ Pgen is the Python parser generator. It is useful to quickly create a
7
+ parser from a grammar file in Python's grammar notation. But I don't
8
+ want my parsers to be written in C (yet), so I'm translating the
9
+ parsing tables to Python data structures and writing a Python parse
10
+ engine.
11
+
12
+ Note that the token numbers are constants determined by the standard
13
+ Python tokenizer. The standard token module defines these numbers and
14
+ their names (the names are not used much). The token numbers are
15
+ hardcoded into the Python tokenizer and into pgen. A Python
16
+ implementation of the Python tokenizer is also available, in the
17
+ standard tokenize module.
18
+
19
+ On the other hand, symbol numbers (representing the grammar's
20
+ non-terminals) are assigned by pgen based on the actual grammar
21
+ input.
22
+
23
+ Note: this module is pretty much obsolete; the pgen module generates
24
+ equivalent grammar tables directly from the Grammar.txt input file
25
+ without having to invoke the Python pgen C program.
26
+
27
+ """
28
+
29
+ # Python imports
30
+ import re
31
+
32
+ # Local imports
33
+ from pgen2 import grammar, token
34
+
35
+
36
+ class Converter(grammar.Grammar):
37
+ """Grammar subclass that reads classic pgen output files.
38
+
39
+ The run() method reads the tables as produced by the pgen parser
40
+ generator, typically contained in two C files, graminit.h and
41
+ graminit.c. The other methods are for internal use only.
42
+
43
+ See the base class for more documentation.
44
+
45
+ """
46
+
47
+ def run(self, graminit_h, graminit_c):
48
+ """Load the grammar tables from the text files written by pgen."""
49
+ self.parse_graminit_h(graminit_h)
50
+ self.parse_graminit_c(graminit_c)
51
+ self.finish_off()
52
+
53
+ def parse_graminit_h(self, filename):
54
+ """Parse the .h file written by pgen. (Internal)
55
+
56
+ This file is a sequence of #define statements defining the
57
+ nonterminals of the grammar as numbers. We build two tables
58
+ mapping the numbers to names and back.
59
+
60
+ """
61
+ try:
62
+ f = open(filename)
63
+ except OSError as err:
64
+ print("Can't open %s: %s" % (filename, err))
65
+ return False
66
+ self.symbol2number = {}
67
+ self.number2symbol = {}
68
+ lineno = 0
69
+ for line in f:
70
+ lineno += 1
71
+ mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line)
72
+ if not mo and line.strip():
73
+ print("%s(%s): can't parse %s" % (filename, lineno,
74
+ line.strip()))
75
+ else:
76
+ symbol, number = mo.groups()
77
+ number = int(number)
78
+ assert symbol not in self.symbol2number
79
+ assert number not in self.number2symbol
80
+ self.symbol2number[symbol] = number
81
+ self.number2symbol[number] = symbol
82
+ return True
83
+
84
+ def parse_graminit_c(self, filename):
85
+ """Parse the .c file written by pgen. (Internal)
86
+
87
+ The file looks as follows. The first two lines are always this:
88
+
89
+ #include "pgenheaders.h"
90
+ #include "grammar.h"
91
+
92
+ After that come four blocks:
93
+
94
+ 1) one or more state definitions
95
+ 2) a table defining dfas
96
+ 3) a table defining labels
97
+ 4) a struct defining the grammar
98
+
99
+ A state definition has the following form:
100
+ - one or more arc arrays, each of the form:
101
+ static arc arcs_<n>_<m>[<k>] = {
102
+ {<i>, <j>},
103
+ ...
104
+ };
105
+ - followed by a state array, of the form:
106
+ static state states_<s>[<t>] = {
107
+ {<k>, arcs_<n>_<m>},
108
+ ...
109
+ };
110
+
111
+ """
112
+ try:
113
+ f = open(filename)
114
+ except OSError as err:
115
+ print("Can't open %s: %s" % (filename, err))
116
+ return False
117
+ # The code below essentially uses f's iterator-ness!
118
+ lineno = 0
119
+
120
+ # Expect the two #include lines
121
+ lineno, line = lineno+1, next(f)
122
+ assert line == '#include "pgenheaders.h"\n', (lineno, line)
123
+ lineno, line = lineno+1, next(f)
124
+ assert line == '#include "grammar.h"\n', (lineno, line)
125
+
126
+ # Parse the state definitions
127
+ lineno, line = lineno+1, next(f)
128
+ allarcs = {}
129
+ states = []
130
+ while line.startswith("static arc "):
131
+ while line.startswith("static arc "):
132
+ mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$",
133
+ line)
134
+ assert mo, (lineno, line)
135
+ n, m, k = list(map(int, mo.groups()))
136
+ arcs = []
137
+ for _ in range(k):
138
+ lineno, line = lineno+1, next(f)
139
+ mo = re.match(r"\s+{(\d+), (\d+)},$", line)
140
+ assert mo, (lineno, line)
141
+ i, j = list(map(int, mo.groups()))
142
+ arcs.append((i, j))
143
+ lineno, line = lineno+1, next(f)
144
+ assert line == "};\n", (lineno, line)
145
+ allarcs[(n, m)] = arcs
146
+ lineno, line = lineno+1, next(f)
147
+ mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line)
148
+ assert mo, (lineno, line)
149
+ s, t = list(map(int, mo.groups()))
150
+ assert s == len(states), (lineno, line)
151
+ state = []
152
+ for _ in range(t):
153
+ lineno, line = lineno+1, next(f)
154
+ mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line)
155
+ assert mo, (lineno, line)
156
+ k, n, m = list(map(int, mo.groups()))
157
+ arcs = allarcs[n, m]
158
+ assert k == len(arcs), (lineno, line)
159
+ state.append(arcs)
160
+ states.append(state)
161
+ lineno, line = lineno+1, next(f)
162
+ assert line == "};\n", (lineno, line)
163
+ lineno, line = lineno+1, next(f)
164
+ self.states = states
165
+
166
+ # Parse the dfas
167
+ dfas = {}
168
+ mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line)
169
+ assert mo, (lineno, line)
170
+ ndfas = int(mo.group(1))
171
+ for i in range(ndfas):
172
+ lineno, line = lineno+1, next(f)
173
+ mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$',
174
+ line)
175
+ assert mo, (lineno, line)
176
+ symbol = mo.group(2)
177
+ number, x, y, z = list(map(int, mo.group(1, 3, 4, 5)))
178
+ assert self.symbol2number[symbol] == number, (lineno, line)
179
+ assert self.number2symbol[number] == symbol, (lineno, line)
180
+ assert x == 0, (lineno, line)
181
+ state = states[z]
182
+ assert y == len(state), (lineno, line)
183
+ lineno, line = lineno+1, next(f)
184
+ mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line)
185
+ assert mo, (lineno, line)
186
+ first = {}
187
+ rawbitset = eval(mo.group(1))
188
+ for i, c in enumerate(rawbitset):
189
+ byte = ord(c)
190
+ for j in range(8):
191
+ if byte & (1<<j):
192
+ first[i*8 + j] = 1
193
+ dfas[number] = (state, first)
194
+ lineno, line = lineno+1, next(f)
195
+ assert line == "};\n", (lineno, line)
196
+ self.dfas = dfas
197
+
198
+ # Parse the labels
199
+ labels = []
200
+ lineno, line = lineno+1, next(f)
201
+ mo = re.match(r"static label labels\[(\d+)\] = {$", line)
202
+ assert mo, (lineno, line)
203
+ nlabels = int(mo.group(1))
204
+ for i in range(nlabels):
205
+ lineno, line = lineno+1, next(f)
206
+ mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line)
207
+ assert mo, (lineno, line)
208
+ x, y = mo.groups()
209
+ x = int(x)
210
+ if y == "0":
211
+ y = None
212
+ else:
213
+ y = eval(y)
214
+ labels.append((x, y))
215
+ lineno, line = lineno+1, next(f)
216
+ assert line == "};\n", (lineno, line)
217
+ self.labels = labels
218
+
219
+ # Parse the grammar struct
220
+ lineno, line = lineno+1, next(f)
221
+ assert line == "grammar _PyParser_Grammar = {\n", (lineno, line)
222
+ lineno, line = lineno+1, next(f)
223
+ mo = re.match(r"\s+(\d+),$", line)
224
+ assert mo, (lineno, line)
225
+ ndfas = int(mo.group(1))
226
+ assert ndfas == len(self.dfas)
227
+ lineno, line = lineno+1, next(f)
228
+ assert line == "\tdfas,\n", (lineno, line)
229
+ lineno, line = lineno+1, next(f)
230
+ mo = re.match(r"\s+{(\d+), labels},$", line)
231
+ assert mo, (lineno, line)
232
+ nlabels = int(mo.group(1))
233
+ assert nlabels == len(self.labels), (lineno, line)
234
+ lineno, line = lineno+1, next(f)
235
+ mo = re.match(r"\s+(\d+)$", line)
236
+ assert mo, (lineno, line)
237
+ start = int(mo.group(1))
238
+ assert start in self.number2symbol, (lineno, line)
239
+ self.start = start
240
+ lineno, line = lineno+1, next(f)
241
+ assert line == "};\n", (lineno, line)
242
+ try:
243
+ lineno, line = lineno+1, next(f)
244
+ except StopIteration:
245
+ pass
246
+ else:
247
+ assert 0, (lineno, line)
248
+
249
+ def finish_off(self):
250
+ """Create additional useful structures. (Internal)."""
251
+ self.keywords = {} # map from keyword strings to arc labels
252
+ self.tokens = {} # map from numeric token values to arc labels
253
+ for ilabel, (type, value) in enumerate(self.labels):
254
+ if type == token.NAME and value is not None:
255
+ self.keywords[value] = ilabel
256
+ elif value is None:
257
+ self.tokens[type] = ilabel
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/driver.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ # Modifications:
5
+ # Copyright 2006 Google, Inc. All Rights Reserved.
6
+ # Licensed to PSF under a Contributor Agreement.
7
+
8
+ """Parser driver.
9
+
10
+ This provides a high-level interface to parse a file into a syntax tree.
11
+
12
+ """
13
+
14
+ __author__ = "Guido van Rossum <guido@python.org>"
15
+
16
+ __all__ = ["Driver", "load_grammar"]
17
+
18
+ # Python imports
19
+ import io
20
+ import os
21
+ import logging
22
+ import pkgutil
23
+ import sys
24
+
25
+ # Pgen imports
26
+ from . import grammar, parse, token, tokenize, pgen
27
+
28
+
29
+ class Driver(object):
30
+
31
+ def __init__(self, grammar, convert=None, logger=None):
32
+ self.grammar = grammar
33
+ if logger is None:
34
+ logger = logging.getLogger()
35
+ self.logger = logger
36
+ self.convert = convert
37
+
38
+ def parse_tokens(self, tokens, debug=False):
39
+ """Parse a series of tokens and return the syntax tree."""
40
+ # XXX Move the prefix computation into a wrapper around tokenize.
41
+ p = parse.Parser(self.grammar, self.convert)
42
+ p.setup()
43
+ lineno = 1
44
+ column = 0
45
+ type = value = start = end = line_text = None
46
+ prefix = ""
47
+ for quintuple in tokens:
48
+ type, value, start, end, line_text = quintuple
49
+ if start != (lineno, column):
50
+ assert (lineno, column) <= start, ((lineno, column), start)
51
+ s_lineno, s_column = start
52
+ if lineno < s_lineno:
53
+ prefix += "\n" * (s_lineno - lineno)
54
+ lineno = s_lineno
55
+ column = 0
56
+ if column < s_column:
57
+ prefix += line_text[column:s_column]
58
+ column = s_column
59
+ if type in (tokenize.COMMENT, tokenize.NL):
60
+ prefix += value
61
+ lineno, column = end
62
+ if value.endswith("\n"):
63
+ lineno += 1
64
+ column = 0
65
+ continue
66
+ if type == token.OP:
67
+ type = grammar.opmap[value]
68
+ if debug:
69
+ self.logger.debug("%s %r (prefix=%r)",
70
+ token.tok_name[type], value, prefix)
71
+ if p.addtoken(type, value, (prefix, start)):
72
+ if debug:
73
+ self.logger.debug("Stop.")
74
+ break
75
+ prefix = ""
76
+ lineno, column = end
77
+ if value.endswith("\n"):
78
+ lineno += 1
79
+ column = 0
80
+ else:
81
+ # We never broke out -- EOF is too soon (how can this happen???)
82
+ raise parse.ParseError("incomplete input",
83
+ type, value, (prefix, start))
84
+ return p.rootnode
85
+
86
+ def parse_stream_raw(self, stream, debug=False):
87
+ """Parse a stream and return the syntax tree."""
88
+ tokens = tokenize.generate_tokens(stream.readline)
89
+ return self.parse_tokens(tokens, debug)
90
+
91
+ def parse_stream(self, stream, debug=False):
92
+ """Parse a stream and return the syntax tree."""
93
+ return self.parse_stream_raw(stream, debug)
94
+
95
+ def parse_file(self, filename, encoding=None, debug=False):
96
+ """Parse a file and return the syntax tree."""
97
+ with io.open(filename, "r", encoding=encoding) as stream:
98
+ return self.parse_stream(stream, debug)
99
+
100
+ def parse_string(self, text, debug=False):
101
+ """Parse a string and return the syntax tree."""
102
+ tokens = tokenize.generate_tokens(io.StringIO(text).readline)
103
+ return self.parse_tokens(tokens, debug)
104
+
105
+
106
+ def _generate_pickle_name(gt):
107
+ head, tail = os.path.splitext(gt)
108
+ if tail == ".txt":
109
+ tail = ""
110
+ return head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
111
+
112
+
113
+ def load_grammar(gt="Grammar.txt", gp=None,
114
+ save=True, force=False, logger=None):
115
+ """Load the grammar (maybe from a pickle)."""
116
+ if logger is None:
117
+ logger = logging.getLogger()
118
+ gp = _generate_pickle_name(gt) if gp is None else gp
119
+ if force or not _newer(gp, gt):
120
+ logger.info("Generating grammar tables from %s", gt)
121
+ g = pgen.generate_grammar(gt)
122
+ if save:
123
+ logger.info("Writing grammar tables to %s", gp)
124
+ try:
125
+ g.dump(gp)
126
+ except OSError as e:
127
+ logger.info("Writing failed: %s", e)
128
+ else:
129
+ g = grammar.Grammar()
130
+ g.load(gp)
131
+ return g
132
+
133
+
134
+ def _newer(a, b):
135
+ """Inquire whether file a was written since file b."""
136
+ if not os.path.exists(a):
137
+ return False
138
+ if not os.path.exists(b):
139
+ return True
140
+ return os.path.getmtime(a) >= os.path.getmtime(b)
141
+
142
+
143
+ def load_packaged_grammar(package, grammar_source):
144
+ """Normally, loads a pickled grammar by doing
145
+ pkgutil.get_data(package, pickled_grammar)
146
+ where *pickled_grammar* is computed from *grammar_source* by adding the
147
+ Python version and using a ``.pickle`` extension.
148
+
149
+ However, if *grammar_source* is an extant file, load_grammar(grammar_source)
150
+ is called instead. This facilitates using a packaged grammar file when needed
151
+ but preserves load_grammar's automatic regeneration behavior when possible.
152
+
153
+ """
154
+ if os.path.isfile(grammar_source):
155
+ return load_grammar(grammar_source)
156
+ pickled_name = _generate_pickle_name(os.path.basename(grammar_source))
157
+ data = pkgutil.get_data(package, pickled_name)
158
+ g = grammar.Grammar()
159
+ g.loads(data)
160
+ return g
161
+
162
+
163
+ def main(*args):
164
+ """Main program, when run as a script: produce grammar pickle files.
165
+
166
+ Calls load_grammar for each argument, a path to a grammar text file.
167
+ """
168
+ if not args:
169
+ args = sys.argv[1:]
170
+ logging.basicConfig(level=logging.INFO, stream=sys.stdout,
171
+ format='%(message)s')
172
+ for gt in args:
173
+ load_grammar(gt, save=True, force=True)
174
+ return True
175
+
176
+ if __name__ == "__main__":
177
+ sys.exit(int(not main()))
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/grammar.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """This module defines the data structures used to represent a grammar.
5
+
6
+ These are a bit arcane because they are derived from the data
7
+ structures used by Python's 'pgen' parser generator.
8
+
9
+ There's also a table here mapping operators to their names in the
10
+ token module; the Python tokenize module reports all operators as the
11
+ fallback token code OP, but the parser needs the actual token code.
12
+
13
+ """
14
+
15
+ # Python imports
16
+ import pickle
17
+
18
+ # Local imports
19
+ from . import token
20
+
21
+
22
+ class Grammar(object):
23
+ """Pgen parsing tables conversion class.
24
+
25
+ Once initialized, this class supplies the grammar tables for the
26
+ parsing engine implemented by parse.py. The parsing engine
27
+ accesses the instance variables directly. The class here does not
28
+ provide initialization of the tables; several subclasses exist to
29
+ do this (see the conv and pgen modules).
30
+
31
+ The load() method reads the tables from a pickle file, which is
32
+ much faster than the other ways offered by subclasses. The pickle
33
+ file is written by calling dump() (after loading the grammar
34
+ tables using a subclass). The report() method prints a readable
35
+ representation of the tables to stdout, for debugging.
36
+
37
+ The instance variables are as follows:
38
+
39
+ symbol2number -- a dict mapping symbol names to numbers. Symbol
40
+ numbers are always 256 or higher, to distinguish
41
+ them from token numbers, which are between 0 and
42
+ 255 (inclusive).
43
+
44
+ number2symbol -- a dict mapping numbers to symbol names;
45
+ these two are each other's inverse.
46
+
47
+ states -- a list of DFAs, where each DFA is a list of
48
+ states, each state is a list of arcs, and each
49
+ arc is a (i, j) pair where i is a label and j is
50
+ a state number. The DFA number is the index into
51
+ this list. (This name is slightly confusing.)
52
+ Final states are represented by a special arc of
53
+ the form (0, j) where j is its own state number.
54
+
55
+ dfas -- a dict mapping symbol numbers to (DFA, first)
56
+ pairs, where DFA is an item from the states list
57
+ above, and first is a set of tokens that can
58
+ begin this grammar rule (represented by a dict
59
+ whose values are always 1).
60
+
61
+ labels -- a list of (x, y) pairs where x is either a token
62
+ number or a symbol number, and y is either None
63
+ or a string; the strings are keywords. The label
64
+ number is the index in this list; label numbers
65
+ are used to mark state transitions (arcs) in the
66
+ DFAs.
67
+
68
+ start -- the number of the grammar's start symbol.
69
+
70
+ keywords -- a dict mapping keyword strings to arc labels.
71
+
72
+ tokens -- a dict mapping token numbers to arc labels.
73
+
74
+ """
75
+
76
+ def __init__(self):
77
+ self.symbol2number = {}
78
+ self.number2symbol = {}
79
+ self.states = []
80
+ self.dfas = {}
81
+ self.labels = [(0, "EMPTY")]
82
+ self.keywords = {}
83
+ self.tokens = {}
84
+ self.symbol2label = {}
85
+ self.start = 256
86
+
87
+ def dump(self, filename):
88
+ """Dump the grammar tables to a pickle file."""
89
+ with open(filename, "wb") as f:
90
+ pickle.dump(self.__dict__, f, pickle.HIGHEST_PROTOCOL)
91
+
92
+ def load(self, filename):
93
+ """Load the grammar tables from a pickle file."""
94
+ with open(filename, "rb") as f:
95
+ d = pickle.load(f)
96
+ self.__dict__.update(d)
97
+
98
+ def loads(self, pkl):
99
+ """Load the grammar tables from a pickle bytes object."""
100
+ self.__dict__.update(pickle.loads(pkl))
101
+
102
+ def copy(self):
103
+ """
104
+ Copy the grammar.
105
+ """
106
+ new = self.__class__()
107
+ for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords",
108
+ "tokens", "symbol2label"):
109
+ setattr(new, dict_attr, getattr(self, dict_attr).copy())
110
+ new.labels = self.labels[:]
111
+ new.states = self.states[:]
112
+ new.start = self.start
113
+ return new
114
+
115
+ def report(self):
116
+ """Dump the grammar tables to standard output, for debugging."""
117
+ from pprint import pprint
118
+ print("s2n")
119
+ pprint(self.symbol2number)
120
+ print("n2s")
121
+ pprint(self.number2symbol)
122
+ print("states")
123
+ pprint(self.states)
124
+ print("dfas")
125
+ pprint(self.dfas)
126
+ print("labels")
127
+ pprint(self.labels)
128
+ print("start", self.start)
129
+
130
+
131
+ # Map from operator to number (since tokenize doesn't do this)
132
+
133
+ opmap_raw = """
134
+ ( LPAR
135
+ ) RPAR
136
+ [ LSQB
137
+ ] RSQB
138
+ : COLON
139
+ , COMMA
140
+ ; SEMI
141
+ + PLUS
142
+ - MINUS
143
+ * STAR
144
+ / SLASH
145
+ | VBAR
146
+ & AMPER
147
+ < LESS
148
+ > GREATER
149
+ = EQUAL
150
+ . DOT
151
+ % PERCENT
152
+ ` BACKQUOTE
153
+ { LBRACE
154
+ } RBRACE
155
+ @ AT
156
+ @= ATEQUAL
157
+ == EQEQUAL
158
+ != NOTEQUAL
159
+ <> NOTEQUAL
160
+ <= LESSEQUAL
161
+ >= GREATEREQUAL
162
+ ~ TILDE
163
+ ^ CIRCUMFLEX
164
+ << LEFTSHIFT
165
+ >> RIGHTSHIFT
166
+ ** DOUBLESTAR
167
+ += PLUSEQUAL
168
+ -= MINEQUAL
169
+ *= STAREQUAL
170
+ /= SLASHEQUAL
171
+ %= PERCENTEQUAL
172
+ &= AMPEREQUAL
173
+ |= VBAREQUAL
174
+ ^= CIRCUMFLEXEQUAL
175
+ <<= LEFTSHIFTEQUAL
176
+ >>= RIGHTSHIFTEQUAL
177
+ **= DOUBLESTAREQUAL
178
+ // DOUBLESLASH
179
+ //= DOUBLESLASHEQUAL
180
+ -> RARROW
181
+ := COLONEQUAL
182
+ """
183
+
184
+ opmap = {}
185
+ for line in opmap_raw.splitlines():
186
+ if line:
187
+ op, name = line.split()
188
+ opmap[op] = getattr(token, name)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/literals.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Safely evaluate Python string literals without using eval()."""
5
+
6
+ import re
7
+
8
+ simple_escapes = {"a": "\a",
9
+ "b": "\b",
10
+ "f": "\f",
11
+ "n": "\n",
12
+ "r": "\r",
13
+ "t": "\t",
14
+ "v": "\v",
15
+ "'": "'",
16
+ '"': '"',
17
+ "\\": "\\"}
18
+
19
+ def escape(m):
20
+ all, tail = m.group(0, 1)
21
+ assert all.startswith("\\")
22
+ esc = simple_escapes.get(tail)
23
+ if esc is not None:
24
+ return esc
25
+ if tail.startswith("x"):
26
+ hexes = tail[1:]
27
+ if len(hexes) < 2:
28
+ raise ValueError("invalid hex string escape ('\\%s')" % tail)
29
+ try:
30
+ i = int(hexes, 16)
31
+ except ValueError:
32
+ raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
33
+ else:
34
+ try:
35
+ i = int(tail, 8)
36
+ except ValueError:
37
+ raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
38
+ return chr(i)
39
+
40
+ def evalString(s):
41
+ assert s.startswith("'") or s.startswith('"'), repr(s[:1])
42
+ q = s[0]
43
+ if s[:3] == q*3:
44
+ q = q*3
45
+ assert s.endswith(q), repr(s[-len(q):])
46
+ assert len(s) >= 2*len(q)
47
+ s = s[len(q):-len(q)]
48
+ return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
49
+
50
+ def test():
51
+ for i in range(256):
52
+ c = chr(i)
53
+ s = repr(c)
54
+ e = evalString(s)
55
+ if e != c:
56
+ print(i, c, s, e)
57
+
58
+
59
+ if __name__ == "__main__":
60
+ test()
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/parse.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ """Parser engine for the grammar tables generated by pgen.
5
+
6
+ The grammar table must be loaded first.
7
+
8
+ See Parser/parser.c in the Python distribution for additional info on
9
+ how this parsing engine works.
10
+
11
+ """
12
+
13
+ # Local imports
14
+ from . import token
15
+
16
+ class ParseError(Exception):
17
+ """Exception to signal the parser is stuck."""
18
+
19
+ def __init__(self, msg, type, value, context):
20
+ Exception.__init__(self, "%s: type=%r, value=%r, context=%r" %
21
+ (msg, type, value, context))
22
+ self.msg = msg
23
+ self.type = type
24
+ self.value = value
25
+ self.context = context
26
+
27
+ def __reduce__(self):
28
+ return type(self), (self.msg, self.type, self.value, self.context)
29
+
30
+ class Parser(object):
31
+ """Parser engine.
32
+
33
+ The proper usage sequence is:
34
+
35
+ p = Parser(grammar, [converter]) # create instance
36
+ p.setup([start]) # prepare for parsing
37
+ <for each input token>:
38
+ if p.addtoken(...): # parse a token; may raise ParseError
39
+ break
40
+ root = p.rootnode # root of abstract syntax tree
41
+
42
+ A Parser instance may be reused by calling setup() repeatedly.
43
+
44
+ A Parser instance contains state pertaining to the current token
45
+ sequence, and should not be used concurrently by different threads
46
+ to parse separate token sequences.
47
+
48
+ See driver.py for how to get input tokens by tokenizing a file or
49
+ string.
50
+
51
+ Parsing is complete when addtoken() returns True; the root of the
52
+ abstract syntax tree can then be retrieved from the rootnode
53
+ instance variable. When a syntax error occurs, addtoken() raises
54
+ the ParseError exception. There is no error recovery; the parser
55
+ cannot be used after a syntax error was reported (but it can be
56
+ reinitialized by calling setup()).
57
+
58
+ """
59
+
60
+ def __init__(self, grammar, convert=None):
61
+ """Constructor.
62
+
63
+ The grammar argument is a grammar.Grammar instance; see the
64
+ grammar module for more information.
65
+
66
+ The parser is not ready yet for parsing; you must call the
67
+ setup() method to get it started.
68
+
69
+ The optional convert argument is a function mapping concrete
70
+ syntax tree nodes to abstract syntax tree nodes. If not
71
+ given, no conversion is done and the syntax tree produced is
72
+ the concrete syntax tree. If given, it must be a function of
73
+ two arguments, the first being the grammar (a grammar.Grammar
74
+ instance), and the second being the concrete syntax tree node
75
+ to be converted. The syntax tree is converted from the bottom
76
+ up.
77
+
78
+ A concrete syntax tree node is a (type, value, context, nodes)
79
+ tuple, where type is the node type (a token or symbol number),
80
+ value is None for symbols and a string for tokens, context is
81
+ None or an opaque value used for error reporting (typically a
82
+ (lineno, offset) pair), and nodes is a list of children for
83
+ symbols, and None for tokens.
84
+
85
+ An abstract syntax tree node may be anything; this is entirely
86
+ up to the converter function.
87
+
88
+ """
89
+ self.grammar = grammar
90
+ self.convert = convert or (lambda grammar, node: node)
91
+
92
+ def setup(self, start=None):
93
+ """Prepare for parsing.
94
+
95
+ This *must* be called before starting to parse.
96
+
97
+ The optional argument is an alternative start symbol; it
98
+ defaults to the grammar's start symbol.
99
+
100
+ You can use a Parser instance to parse any number of programs;
101
+ each time you call setup() the parser is reset to an initial
102
+ state determined by the (implicit or explicit) start symbol.
103
+
104
+ """
105
+ if start is None:
106
+ start = self.grammar.start
107
+ # Each stack entry is a tuple: (dfa, state, node).
108
+ # A node is a tuple: (type, value, context, children),
109
+ # where children is a list of nodes or None, and context may be None.
110
+ newnode = (start, None, None, [])
111
+ stackentry = (self.grammar.dfas[start], 0, newnode)
112
+ self.stack = [stackentry]
113
+ self.rootnode = None
114
+ self.used_names = set() # Aliased to self.rootnode.used_names in pop()
115
+
116
+ def addtoken(self, type, value, context):
117
+ """Add a token; return True iff this is the end of the program."""
118
+ # Map from token to label
119
+ ilabel = self.classify(type, value, context)
120
+ # Loop until the token is shifted; may raise exceptions
121
+ while True:
122
+ dfa, state, node = self.stack[-1]
123
+ states, first = dfa
124
+ arcs = states[state]
125
+ # Look for a state with this label
126
+ for i, newstate in arcs:
127
+ t, v = self.grammar.labels[i]
128
+ if ilabel == i:
129
+ # Look it up in the list of labels
130
+ assert t < 256
131
+ # Shift a token; we're done with it
132
+ self.shift(type, value, newstate, context)
133
+ # Pop while we are in an accept-only state
134
+ state = newstate
135
+ while states[state] == [(0, state)]:
136
+ self.pop()
137
+ if not self.stack:
138
+ # Done parsing!
139
+ return True
140
+ dfa, state, node = self.stack[-1]
141
+ states, first = dfa
142
+ # Done with this token
143
+ return False
144
+ elif t >= 256:
145
+ # See if it's a symbol and if we're in its first set
146
+ itsdfa = self.grammar.dfas[t]
147
+ itsstates, itsfirst = itsdfa
148
+ if ilabel in itsfirst:
149
+ # Push a symbol
150
+ self.push(t, self.grammar.dfas[t], newstate, context)
151
+ break # To continue the outer while loop
152
+ else:
153
+ if (0, state) in arcs:
154
+ # An accepting state, pop it and try something else
155
+ self.pop()
156
+ if not self.stack:
157
+ # Done parsing, but another token is input
158
+ raise ParseError("too much input",
159
+ type, value, context)
160
+ else:
161
+ # No success finding a transition
162
+ raise ParseError("bad input", type, value, context)
163
+
164
+ def classify(self, type, value, context):
165
+ """Turn a token into a label. (Internal)"""
166
+ if type == token.NAME:
167
+ # Keep a listing of all used names
168
+ self.used_names.add(value)
169
+ # Check for reserved words
170
+ ilabel = self.grammar.keywords.get(value)
171
+ if ilabel is not None:
172
+ return ilabel
173
+ ilabel = self.grammar.tokens.get(type)
174
+ if ilabel is None:
175
+ raise ParseError("bad token", type, value, context)
176
+ return ilabel
177
+
178
+ def shift(self, type, value, newstate, context):
179
+ """Shift a token. (Internal)"""
180
+ dfa, state, node = self.stack[-1]
181
+ newnode = (type, value, context, None)
182
+ newnode = self.convert(self.grammar, newnode)
183
+ if newnode is not None:
184
+ node[-1].append(newnode)
185
+ self.stack[-1] = (dfa, newstate, node)
186
+
187
+ def push(self, type, newdfa, newstate, context):
188
+ """Push a nonterminal. (Internal)"""
189
+ dfa, state, node = self.stack[-1]
190
+ newnode = (type, None, context, [])
191
+ self.stack[-1] = (dfa, newstate, node)
192
+ self.stack.append((newdfa, 0, newnode))
193
+
194
+ def pop(self):
195
+ """Pop a nonterminal. (Internal)"""
196
+ popdfa, popstate, popnode = self.stack.pop()
197
+ newnode = self.convert(self.grammar, popnode)
198
+ if newnode is not None:
199
+ if self.stack:
200
+ dfa, state, node = self.stack[-1]
201
+ node[-1].append(newnode)
202
+ else:
203
+ self.rootnode = newnode
204
+ self.rootnode.used_names = self.used_names
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/pgen.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2
+ # Licensed to PSF under a Contributor Agreement.
3
+
4
+ # Pgen imports
5
+ from . import grammar, token, tokenize
6
+
7
+ class PgenGrammar(grammar.Grammar):
8
+ pass
9
+
10
+ class ParserGenerator(object):
11
+
12
+ def __init__(self, filename, stream=None):
13
+ close_stream = None
14
+ if stream is None:
15
+ stream = open(filename, encoding="utf-8")
16
+ close_stream = stream.close
17
+ self.filename = filename
18
+ self.stream = stream
19
+ self.generator = tokenize.generate_tokens(stream.readline)
20
+ self.gettoken() # Initialize lookahead
21
+ self.dfas, self.startsymbol = self.parse()
22
+ if close_stream is not None:
23
+ close_stream()
24
+ self.first = {} # map from symbol name to set of tokens
25
+ self.addfirstsets()
26
+
27
+ def make_grammar(self):
28
+ c = PgenGrammar()
29
+ names = list(self.dfas.keys())
30
+ names.sort()
31
+ names.remove(self.startsymbol)
32
+ names.insert(0, self.startsymbol)
33
+ for name in names:
34
+ i = 256 + len(c.symbol2number)
35
+ c.symbol2number[name] = i
36
+ c.number2symbol[i] = name
37
+ for name in names:
38
+ dfa = self.dfas[name]
39
+ states = []
40
+ for state in dfa:
41
+ arcs = []
42
+ for label, next in sorted(state.arcs.items()):
43
+ arcs.append((self.make_label(c, label), dfa.index(next)))
44
+ if state.isfinal:
45
+ arcs.append((0, dfa.index(state)))
46
+ states.append(arcs)
47
+ c.states.append(states)
48
+ c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name))
49
+ c.start = c.symbol2number[self.startsymbol]
50
+ return c
51
+
52
+ def make_first(self, c, name):
53
+ rawfirst = self.first[name]
54
+ first = {}
55
+ for label in sorted(rawfirst):
56
+ ilabel = self.make_label(c, label)
57
+ ##assert ilabel not in first # XXX failed on <> ... !=
58
+ first[ilabel] = 1
59
+ return first
60
+
61
+ def make_label(self, c, label):
62
+ # XXX Maybe this should be a method on a subclass of converter?
63
+ ilabel = len(c.labels)
64
+ if label[0].isalpha():
65
+ # Either a symbol name or a named token
66
+ if label in c.symbol2number:
67
+ # A symbol name (a non-terminal)
68
+ if label in c.symbol2label:
69
+ return c.symbol2label[label]
70
+ else:
71
+ c.labels.append((c.symbol2number[label], None))
72
+ c.symbol2label[label] = ilabel
73
+ return ilabel
74
+ else:
75
+ # A named token (NAME, NUMBER, STRING)
76
+ itoken = getattr(token, label, None)
77
+ assert isinstance(itoken, int), label
78
+ assert itoken in token.tok_name, label
79
+ if itoken in c.tokens:
80
+ return c.tokens[itoken]
81
+ else:
82
+ c.labels.append((itoken, None))
83
+ c.tokens[itoken] = ilabel
84
+ return ilabel
85
+ else:
86
+ # Either a keyword or an operator
87
+ assert label[0] in ('"', "'"), label
88
+ value = eval(label)
89
+ if value[0].isalpha():
90
+ # A keyword
91
+ if value in c.keywords:
92
+ return c.keywords[value]
93
+ else:
94
+ c.labels.append((token.NAME, value))
95
+ c.keywords[value] = ilabel
96
+ return ilabel
97
+ else:
98
+ # An operator (any non-numeric token)
99
+ itoken = grammar.opmap[value] # Fails if unknown token
100
+ if itoken in c.tokens:
101
+ return c.tokens[itoken]
102
+ else:
103
+ c.labels.append((itoken, None))
104
+ c.tokens[itoken] = ilabel
105
+ return ilabel
106
+
107
+ def addfirstsets(self):
108
+ names = list(self.dfas.keys())
109
+ names.sort()
110
+ for name in names:
111
+ if name not in self.first:
112
+ self.calcfirst(name)
113
+ #print name, self.first[name].keys()
114
+
115
+ def calcfirst(self, name):
116
+ dfa = self.dfas[name]
117
+ self.first[name] = None # dummy to detect left recursion
118
+ state = dfa[0]
119
+ totalset = {}
120
+ overlapcheck = {}
121
+ for label, next in state.arcs.items():
122
+ if label in self.dfas:
123
+ if label in self.first:
124
+ fset = self.first[label]
125
+ if fset is None:
126
+ raise ValueError("recursion for rule %r" % name)
127
+ else:
128
+ self.calcfirst(label)
129
+ fset = self.first[label]
130
+ totalset.update(fset)
131
+ overlapcheck[label] = fset
132
+ else:
133
+ totalset[label] = 1
134
+ overlapcheck[label] = {label: 1}
135
+ inverse = {}
136
+ for label, itsfirst in overlapcheck.items():
137
+ for symbol in itsfirst:
138
+ if symbol in inverse:
139
+ raise ValueError("rule %s is ambiguous; %s is in the"
140
+ " first sets of %s as well as %s" %
141
+ (name, symbol, label, inverse[symbol]))
142
+ inverse[symbol] = label
143
+ self.first[name] = totalset
144
+
145
+ def parse(self):
146
+ dfas = {}
147
+ startsymbol = None
148
+ # MSTART: (NEWLINE | RULE)* ENDMARKER
149
+ while self.type != token.ENDMARKER:
150
+ while self.type == token.NEWLINE:
151
+ self.gettoken()
152
+ # RULE: NAME ':' RHS NEWLINE
153
+ name = self.expect(token.NAME)
154
+ self.expect(token.OP, ":")
155
+ a, z = self.parse_rhs()
156
+ self.expect(token.NEWLINE)
157
+ #self.dump_nfa(name, a, z)
158
+ dfa = self.make_dfa(a, z)
159
+ #self.dump_dfa(name, dfa)
160
+ oldlen = len(dfa)
161
+ self.simplify_dfa(dfa)
162
+ newlen = len(dfa)
163
+ dfas[name] = dfa
164
+ #print name, oldlen, newlen
165
+ if startsymbol is None:
166
+ startsymbol = name
167
+ return dfas, startsymbol
168
+
169
+ def make_dfa(self, start, finish):
170
+ # To turn an NFA into a DFA, we define the states of the DFA
171
+ # to correspond to *sets* of states of the NFA. Then do some
172
+ # state reduction. Let's represent sets as dicts with 1 for
173
+ # values.
174
+ assert isinstance(start, NFAState)
175
+ assert isinstance(finish, NFAState)
176
+ def closure(state):
177
+ base = {}
178
+ addclosure(state, base)
179
+ return base
180
+ def addclosure(state, base):
181
+ assert isinstance(state, NFAState)
182
+ if state in base:
183
+ return
184
+ base[state] = 1
185
+ for label, next in state.arcs:
186
+ if label is None:
187
+ addclosure(next, base)
188
+ states = [DFAState(closure(start), finish)]
189
+ for state in states: # NB states grows while we're iterating
190
+ arcs = {}
191
+ for nfastate in state.nfaset:
192
+ for label, next in nfastate.arcs:
193
+ if label is not None:
194
+ addclosure(next, arcs.setdefault(label, {}))
195
+ for label, nfaset in sorted(arcs.items()):
196
+ for st in states:
197
+ if st.nfaset == nfaset:
198
+ break
199
+ else:
200
+ st = DFAState(nfaset, finish)
201
+ states.append(st)
202
+ state.addarc(st, label)
203
+ return states # List of DFAState instances; first one is start
204
+
205
+ def dump_nfa(self, name, start, finish):
206
+ print("Dump of NFA for", name)
207
+ todo = [start]
208
+ for i, state in enumerate(todo):
209
+ print(" State", i, state is finish and "(final)" or "")
210
+ for label, next in state.arcs:
211
+ if next in todo:
212
+ j = todo.index(next)
213
+ else:
214
+ j = len(todo)
215
+ todo.append(next)
216
+ if label is None:
217
+ print(" -> %d" % j)
218
+ else:
219
+ print(" %s -> %d" % (label, j))
220
+
221
+ def dump_dfa(self, name, dfa):
222
+ print("Dump of DFA for", name)
223
+ for i, state in enumerate(dfa):
224
+ print(" State", i, state.isfinal and "(final)" or "")
225
+ for label, next in sorted(state.arcs.items()):
226
+ print(" %s -> %d" % (label, dfa.index(next)))
227
+
228
+ def simplify_dfa(self, dfa):
229
+ # This is not theoretically optimal, but works well enough.
230
+ # Algorithm: repeatedly look for two states that have the same
231
+ # set of arcs (same labels pointing to the same nodes) and
232
+ # unify them, until things stop changing.
233
+
234
+ # dfa is a list of DFAState instances
235
+ changes = True
236
+ while changes:
237
+ changes = False
238
+ for i, state_i in enumerate(dfa):
239
+ for j in range(i+1, len(dfa)):
240
+ state_j = dfa[j]
241
+ if state_i == state_j:
242
+ #print " unify", i, j
243
+ del dfa[j]
244
+ for state in dfa:
245
+ state.unifystate(state_j, state_i)
246
+ changes = True
247
+ break
248
+
249
+ def parse_rhs(self):
250
+ # RHS: ALT ('|' ALT)*
251
+ a, z = self.parse_alt()
252
+ if self.value != "|":
253
+ return a, z
254
+ else:
255
+ aa = NFAState()
256
+ zz = NFAState()
257
+ aa.addarc(a)
258
+ z.addarc(zz)
259
+ while self.value == "|":
260
+ self.gettoken()
261
+ a, z = self.parse_alt()
262
+ aa.addarc(a)
263
+ z.addarc(zz)
264
+ return aa, zz
265
+
266
+ def parse_alt(self):
267
+ # ALT: ITEM+
268
+ a, b = self.parse_item()
269
+ while (self.value in ("(", "[") or
270
+ self.type in (token.NAME, token.STRING)):
271
+ c, d = self.parse_item()
272
+ b.addarc(c)
273
+ b = d
274
+ return a, b
275
+
276
+ def parse_item(self):
277
+ # ITEM: '[' RHS ']' | ATOM ['+' | '*']
278
+ if self.value == "[":
279
+ self.gettoken()
280
+ a, z = self.parse_rhs()
281
+ self.expect(token.OP, "]")
282
+ a.addarc(z)
283
+ return a, z
284
+ else:
285
+ a, z = self.parse_atom()
286
+ value = self.value
287
+ if value not in ("+", "*"):
288
+ return a, z
289
+ self.gettoken()
290
+ z.addarc(a)
291
+ if value == "+":
292
+ return a, z
293
+ else:
294
+ return a, a
295
+
296
+ def parse_atom(self):
297
+ # ATOM: '(' RHS ')' | NAME | STRING
298
+ if self.value == "(":
299
+ self.gettoken()
300
+ a, z = self.parse_rhs()
301
+ self.expect(token.OP, ")")
302
+ return a, z
303
+ elif self.type in (token.NAME, token.STRING):
304
+ a = NFAState()
305
+ z = NFAState()
306
+ a.addarc(z, self.value)
307
+ self.gettoken()
308
+ return a, z
309
+ else:
310
+ self.raise_error("expected (...) or NAME or STRING, got %s/%s",
311
+ self.type, self.value)
312
+
313
+ def expect(self, type, value=None):
314
+ if self.type != type or (value is not None and self.value != value):
315
+ self.raise_error("expected %s/%s, got %s/%s",
316
+ type, value, self.type, self.value)
317
+ value = self.value
318
+ self.gettoken()
319
+ return value
320
+
321
+ def gettoken(self):
322
+ tup = next(self.generator)
323
+ while tup[0] in (tokenize.COMMENT, tokenize.NL):
324
+ tup = next(self.generator)
325
+ self.type, self.value, self.begin, self.end, self.line = tup
326
+ #print token.tok_name[self.type], repr(self.value)
327
+
328
+ def raise_error(self, msg, *args):
329
+ if args:
330
+ try:
331
+ msg = msg % args
332
+ except:
333
+ msg = " ".join([msg] + list(map(str, args)))
334
+ raise SyntaxError(msg, (self.filename, self.end[0],
335
+ self.end[1], self.line))
336
+
337
+ class NFAState(object):
338
+
339
+ def __init__(self):
340
+ self.arcs = [] # list of (label, NFAState) pairs
341
+
342
+ def addarc(self, next, label=None):
343
+ assert label is None or isinstance(label, str)
344
+ assert isinstance(next, NFAState)
345
+ self.arcs.append((label, next))
346
+
347
+ class DFAState(object):
348
+
349
+ def __init__(self, nfaset, final):
350
+ assert isinstance(nfaset, dict)
351
+ assert isinstance(next(iter(nfaset)), NFAState)
352
+ assert isinstance(final, NFAState)
353
+ self.nfaset = nfaset
354
+ self.isfinal = final in nfaset
355
+ self.arcs = {} # map from label to DFAState
356
+
357
+ def addarc(self, next, label):
358
+ assert isinstance(label, str)
359
+ assert label not in self.arcs
360
+ assert isinstance(next, DFAState)
361
+ self.arcs[label] = next
362
+
363
+ def unifystate(self, old, new):
364
+ for label, next in self.arcs.items():
365
+ if next is old:
366
+ self.arcs[label] = new
367
+
368
+ def __eq__(self, other):
369
+ # Equality test -- ignore the nfaset instance variable
370
+ assert isinstance(other, DFAState)
371
+ if self.isfinal != other.isfinal:
372
+ return False
373
+ # Can't just return self.arcs == other.arcs, because that
374
+ # would invoke this method recursively, with cycles...
375
+ if len(self.arcs) != len(other.arcs):
376
+ return False
377
+ for label, next in self.arcs.items():
378
+ if next is not other.arcs.get(label):
379
+ return False
380
+ return True
381
+
382
+ __hash__ = None # For Py3 compatibility.
383
+
384
+ def generate_grammar(filename="Grammar.txt"):
385
+ p = ParserGenerator(filename)
386
+ return p.make_grammar()
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/token.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python3
2
+
3
+ """Token constants (from "token.h")."""
4
+
5
+ # Taken from Python (r53757) and modified to include some tokens
6
+ # originally monkeypatched in by pgen2.tokenize
7
+
8
+ #--start constants--
9
+ ENDMARKER = 0
10
+ NAME = 1
11
+ NUMBER = 2
12
+ STRING = 3
13
+ NEWLINE = 4
14
+ INDENT = 5
15
+ DEDENT = 6
16
+ LPAR = 7
17
+ RPAR = 8
18
+ LSQB = 9
19
+ RSQB = 10
20
+ COLON = 11
21
+ COMMA = 12
22
+ SEMI = 13
23
+ PLUS = 14
24
+ MINUS = 15
25
+ STAR = 16
26
+ SLASH = 17
27
+ VBAR = 18
28
+ AMPER = 19
29
+ LESS = 20
30
+ GREATER = 21
31
+ EQUAL = 22
32
+ DOT = 23
33
+ PERCENT = 24
34
+ BACKQUOTE = 25
35
+ LBRACE = 26
36
+ RBRACE = 27
37
+ EQEQUAL = 28
38
+ NOTEQUAL = 29
39
+ LESSEQUAL = 30
40
+ GREATEREQUAL = 31
41
+ TILDE = 32
42
+ CIRCUMFLEX = 33
43
+ LEFTSHIFT = 34
44
+ RIGHTSHIFT = 35
45
+ DOUBLESTAR = 36
46
+ PLUSEQUAL = 37
47
+ MINEQUAL = 38
48
+ STAREQUAL = 39
49
+ SLASHEQUAL = 40
50
+ PERCENTEQUAL = 41
51
+ AMPEREQUAL = 42
52
+ VBAREQUAL = 43
53
+ CIRCUMFLEXEQUAL = 44
54
+ LEFTSHIFTEQUAL = 45
55
+ RIGHTSHIFTEQUAL = 46
56
+ DOUBLESTAREQUAL = 47
57
+ DOUBLESLASH = 48
58
+ DOUBLESLASHEQUAL = 49
59
+ AT = 50
60
+ ATEQUAL = 51
61
+ OP = 52
62
+ COMMENT = 53
63
+ NL = 54
64
+ RARROW = 55
65
+ AWAIT = 56
66
+ ASYNC = 57
67
+ ERRORTOKEN = 58
68
+ COLONEQUAL = 59
69
+ N_TOKENS = 60
70
+ NT_OFFSET = 256
71
+ #--end constants--
72
+
73
+ tok_name = {}
74
+ for _name, _value in list(globals().items()):
75
+ if type(_value) is type(0):
76
+ tok_name[_value] = _name
77
+
78
+
79
+ def ISTERMINAL(x):
80
+ return x < NT_OFFSET
81
+
82
+ def ISNONTERMINAL(x):
83
+ return x >= NT_OFFSET
84
+
85
+ def ISEOF(x):
86
+ return x == ENDMARKER
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/pgen2/tokenize.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
2
+ # All rights reserved.
3
+
4
+ """Tokenization help for Python programs.
5
+
6
+ generate_tokens(readline) is a generator that breaks a stream of
7
+ text into Python tokens. It accepts a readline-like method which is called
8
+ repeatedly to get the next line of input (or "" for EOF). It generates
9
+ 5-tuples with these members:
10
+
11
+ the token type (see token.py)
12
+ the token (a string)
13
+ the starting (row, column) indices of the token (a 2-tuple of ints)
14
+ the ending (row, column) indices of the token (a 2-tuple of ints)
15
+ the original line (string)
16
+
17
+ It is designed to match the working of the Python tokenizer exactly, except
18
+ that it produces COMMENT tokens for comments and gives type OP for all
19
+ operators
20
+
21
+ Older entry points
22
+ tokenize_loop(readline, tokeneater)
23
+ tokenize(readline, tokeneater=printtoken)
24
+ are the same, except instead of generating tokens, tokeneater is a callback
25
+ function to which the 5 fields described above are passed as 5 arguments,
26
+ each time a new token is found."""
27
+
28
+ __author__ = 'Ka-Ping Yee <ping@lfw.org>'
29
+ __credits__ = \
30
+ 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
31
+
32
+ import string, re
33
+ from codecs import BOM_UTF8, lookup
34
+ from lib2to3.pgen2.token import *
35
+
36
+ from . import token
37
+ __all__ = [x for x in dir(token) if x[0] != '_'] + ["tokenize",
38
+ "generate_tokens", "untokenize"]
39
+ del token
40
+
41
+ try:
42
+ bytes
43
+ except NameError:
44
+ # Support bytes type in Python <= 2.5, so 2to3 turns itself into
45
+ # valid Python 3 code.
46
+ bytes = str
47
+
48
+ def group(*choices): return '(' + '|'.join(choices) + ')'
49
+ def any(*choices): return group(*choices) + '*'
50
+ def maybe(*choices): return group(*choices) + '?'
51
+ def _combinations(*l):
52
+ return set(
53
+ x + y for x in l for y in l + ("",) if x.casefold() != y.casefold()
54
+ )
55
+
56
+ Whitespace = r'[ \f\t]*'
57
+ Comment = r'#[^\r\n]*'
58
+ Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
59
+ Name = r'\w+'
60
+
61
+ Binnumber = r'0[bB]_?[01]+(?:_[01]+)*'
62
+ Hexnumber = r'0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?'
63
+ Octnumber = r'0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?'
64
+ Decnumber = group(r'[1-9]\d*(?:_\d+)*[lL]?', '0[lL]?')
65
+ Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber)
66
+ Exponent = r'[eE][-+]?\d+(?:_\d+)*'
67
+ Pointfloat = group(r'\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?', r'\.\d+(?:_\d+)*') + maybe(Exponent)
68
+ Expfloat = r'\d+(?:_\d+)*' + Exponent
69
+ Floatnumber = group(Pointfloat, Expfloat)
70
+ Imagnumber = group(r'\d+(?:_\d+)*[jJ]', Floatnumber + r'[jJ]')
71
+ Number = group(Imagnumber, Floatnumber, Intnumber)
72
+
73
+ # Tail end of ' string.
74
+ Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
75
+ # Tail end of " string.
76
+ Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
77
+ # Tail end of ''' string.
78
+ Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
79
+ # Tail end of """ string.
80
+ Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
81
+ _litprefix = r"(?:[uUrRbBfF]|[rR][fFbB]|[fFbBuU][rR])?"
82
+ Triple = group(_litprefix + "'''", _litprefix + '"""')
83
+ # Single-line ' or " string.
84
+ String = group(_litprefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
85
+ _litprefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
86
+
87
+ # Because of leftmost-then-longest match semantics, be sure to put the
88
+ # longest operators first (e.g., if = came before ==, == would get
89
+ # recognized as two instances of =).
90
+ Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
91
+ r"//=?", r"->",
92
+ r"[+\-*/%&@|^=<>]=?",
93
+ r"~")
94
+
95
+ Bracket = '[][(){}]'
96
+ Special = group(r'\r?\n', r':=', r'[:;.,`@]')
97
+ Funny = group(Operator, Bracket, Special)
98
+
99
+ PlainToken = group(Number, Funny, String, Name)
100
+ Token = Ignore + PlainToken
101
+
102
+ # First (or only) line of ' or " string.
103
+ ContStr = group(_litprefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
104
+ group("'", r'\\\r?\n'),
105
+ _litprefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
106
+ group('"', r'\\\r?\n'))
107
+ PseudoExtras = group(r'\\\r?\n', Comment, Triple)
108
+ PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
109
+
110
+ tokenprog, pseudoprog, single3prog, double3prog = map(
111
+ re.compile, (Token, PseudoToken, Single3, Double3))
112
+
113
+ _strprefixes = (
114
+ _combinations('r', 'R', 'f', 'F') |
115
+ _combinations('r', 'R', 'b', 'B') |
116
+ {'u', 'U', 'ur', 'uR', 'Ur', 'UR'}
117
+ )
118
+
119
+ endprogs = {"'": re.compile(Single), '"': re.compile(Double),
120
+ "'''": single3prog, '"""': double3prog,
121
+ **{f"{prefix}'''": single3prog for prefix in _strprefixes},
122
+ **{f'{prefix}"""': double3prog for prefix in _strprefixes},
123
+ **{prefix: None for prefix in _strprefixes}}
124
+
125
+ triple_quoted = (
126
+ {"'''", '"""'} |
127
+ {f"{prefix}'''" for prefix in _strprefixes} |
128
+ {f'{prefix}"""' for prefix in _strprefixes}
129
+ )
130
+ single_quoted = (
131
+ {"'", '"'} |
132
+ {f"{prefix}'" for prefix in _strprefixes} |
133
+ {f'{prefix}"' for prefix in _strprefixes}
134
+ )
135
+
136
+ tabsize = 8
137
+
138
+ class TokenError(Exception): pass
139
+
140
+ class StopTokenizing(Exception): pass
141
+
142
+ def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing
143
+ (srow, scol) = xxx_todo_changeme
144
+ (erow, ecol) = xxx_todo_changeme1
145
+ print("%d,%d-%d,%d:\t%s\t%s" % \
146
+ (srow, scol, erow, ecol, tok_name[type], repr(token)))
147
+
148
+ def tokenize(readline, tokeneater=printtoken):
149
+ """
150
+ The tokenize() function accepts two parameters: one representing the
151
+ input stream, and one providing an output mechanism for tokenize().
152
+
153
+ The first parameter, readline, must be a callable object which provides
154
+ the same interface as the readline() method of built-in file objects.
155
+ Each call to the function should return one line of input as a string.
156
+
157
+ The second parameter, tokeneater, must also be a callable object. It is
158
+ called once for each token, with five arguments, corresponding to the
159
+ tuples generated by generate_tokens().
160
+ """
161
+ try:
162
+ tokenize_loop(readline, tokeneater)
163
+ except StopTokenizing:
164
+ pass
165
+
166
+ # backwards compatible interface
167
+ def tokenize_loop(readline, tokeneater):
168
+ for token_info in generate_tokens(readline):
169
+ tokeneater(*token_info)
170
+
171
+ class Untokenizer:
172
+
173
+ def __init__(self):
174
+ self.tokens = []
175
+ self.prev_row = 1
176
+ self.prev_col = 0
177
+
178
+ def add_whitespace(self, start):
179
+ row, col = start
180
+ assert row <= self.prev_row
181
+ col_offset = col - self.prev_col
182
+ if col_offset:
183
+ self.tokens.append(" " * col_offset)
184
+
185
+ def untokenize(self, iterable):
186
+ for t in iterable:
187
+ if len(t) == 2:
188
+ self.compat(t, iterable)
189
+ break
190
+ tok_type, token, start, end, line = t
191
+ self.add_whitespace(start)
192
+ self.tokens.append(token)
193
+ self.prev_row, self.prev_col = end
194
+ if tok_type in (NEWLINE, NL):
195
+ self.prev_row += 1
196
+ self.prev_col = 0
197
+ return "".join(self.tokens)
198
+
199
+ def compat(self, token, iterable):
200
+ startline = False
201
+ indents = []
202
+ toks_append = self.tokens.append
203
+ toknum, tokval = token
204
+ if toknum in (NAME, NUMBER):
205
+ tokval += ' '
206
+ if toknum in (NEWLINE, NL):
207
+ startline = True
208
+ for tok in iterable:
209
+ toknum, tokval = tok[:2]
210
+
211
+ if toknum in (NAME, NUMBER, ASYNC, AWAIT):
212
+ tokval += ' '
213
+
214
+ if toknum == INDENT:
215
+ indents.append(tokval)
216
+ continue
217
+ elif toknum == DEDENT:
218
+ indents.pop()
219
+ continue
220
+ elif toknum in (NEWLINE, NL):
221
+ startline = True
222
+ elif startline and indents:
223
+ toks_append(indents[-1])
224
+ startline = False
225
+ toks_append(tokval)
226
+
227
+ cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
228
+ blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
229
+
230
+ def _get_normal_name(orig_enc):
231
+ """Imitates get_normal_name in tokenizer.c."""
232
+ # Only care about the first 12 characters.
233
+ enc = orig_enc[:12].lower().replace("_", "-")
234
+ if enc == "utf-8" or enc.startswith("utf-8-"):
235
+ return "utf-8"
236
+ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
237
+ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
238
+ return "iso-8859-1"
239
+ return orig_enc
240
+
241
+ def detect_encoding(readline):
242
+ """
243
+ The detect_encoding() function is used to detect the encoding that should
244
+ be used to decode a Python source file. It requires one argument, readline,
245
+ in the same way as the tokenize() generator.
246
+
247
+ It will call readline a maximum of twice, and return the encoding used
248
+ (as a string) and a list of any lines (left as bytes) it has read
249
+ in.
250
+
251
+ It detects the encoding from the presence of a utf-8 bom or an encoding
252
+ cookie as specified in pep-0263. If both a bom and a cookie are present, but
253
+ disagree, a SyntaxError will be raised. If the encoding cookie is an invalid
254
+ charset, raise a SyntaxError. Note that if a utf-8 bom is found,
255
+ 'utf-8-sig' is returned.
256
+
257
+ If no encoding is specified, then the default of 'utf-8' will be returned.
258
+ """
259
+ bom_found = False
260
+ encoding = None
261
+ default = 'utf-8'
262
+ def read_or_stop():
263
+ try:
264
+ return readline()
265
+ except StopIteration:
266
+ return bytes()
267
+
268
+ def find_cookie(line):
269
+ try:
270
+ line_string = line.decode('ascii')
271
+ except UnicodeDecodeError:
272
+ return None
273
+ match = cookie_re.match(line_string)
274
+ if not match:
275
+ return None
276
+ encoding = _get_normal_name(match.group(1))
277
+ try:
278
+ codec = lookup(encoding)
279
+ except LookupError:
280
+ # This behaviour mimics the Python interpreter
281
+ raise SyntaxError("unknown encoding: " + encoding)
282
+
283
+ if bom_found:
284
+ if codec.name != 'utf-8':
285
+ # This behaviour mimics the Python interpreter
286
+ raise SyntaxError('encoding problem: utf-8')
287
+ encoding += '-sig'
288
+ return encoding
289
+
290
+ first = read_or_stop()
291
+ if first.startswith(BOM_UTF8):
292
+ bom_found = True
293
+ first = first[3:]
294
+ default = 'utf-8-sig'
295
+ if not first:
296
+ return default, []
297
+
298
+ encoding = find_cookie(first)
299
+ if encoding:
300
+ return encoding, [first]
301
+ if not blank_re.match(first):
302
+ return default, [first]
303
+
304
+ second = read_or_stop()
305
+ if not second:
306
+ return default, [first]
307
+
308
+ encoding = find_cookie(second)
309
+ if encoding:
310
+ return encoding, [first, second]
311
+
312
+ return default, [first, second]
313
+
314
+ def untokenize(iterable):
315
+ """Transform tokens back into Python source code.
316
+
317
+ Each element returned by the iterable must be a token sequence
318
+ with at least two elements, a token number and token value. If
319
+ only two tokens are passed, the resulting output is poor.
320
+
321
+ Round-trip invariant for full input:
322
+ Untokenized source will match input source exactly
323
+
324
+ Round-trip invariant for limited input:
325
+ # Output text will tokenize the back to the input
326
+ t1 = [tok[:2] for tok in generate_tokens(f.readline)]
327
+ newcode = untokenize(t1)
328
+ readline = iter(newcode.splitlines(1)).next
329
+ t2 = [tok[:2] for tokin generate_tokens(readline)]
330
+ assert t1 == t2
331
+ """
332
+ ut = Untokenizer()
333
+ return ut.untokenize(iterable)
334
+
335
+ def generate_tokens(readline):
336
+ """
337
+ The generate_tokens() generator requires one argument, readline, which
338
+ must be a callable object which provides the same interface as the
339
+ readline() method of built-in file objects. Each call to the function
340
+ should return one line of input as a string. Alternately, readline
341
+ can be a callable function terminating with StopIteration:
342
+ readline = open(myfile).next # Example of alternate readline
343
+
344
+ The generator produces 5-tuples with these members: the token type; the
345
+ token string; a 2-tuple (srow, scol) of ints specifying the row and
346
+ column where the token begins in the source; a 2-tuple (erow, ecol) of
347
+ ints specifying the row and column where the token ends in the source;
348
+ and the line on which the token was found. The line passed is the
349
+ physical line.
350
+ """
351
+ lnum = parenlev = continued = 0
352
+ contstr, needcont = '', 0
353
+ contline = None
354
+ indents = [0]
355
+
356
+ # 'stashed' and 'async_*' are used for async/await parsing
357
+ stashed = None
358
+ async_def = False
359
+ async_def_indent = 0
360
+ async_def_nl = False
361
+
362
+ while 1: # loop over lines in stream
363
+ try:
364
+ line = readline()
365
+ except StopIteration:
366
+ line = ''
367
+ lnum = lnum + 1
368
+ pos, max = 0, len(line)
369
+
370
+ if contstr: # continued string
371
+ if not line:
372
+ raise TokenError("EOF in multi-line string", strstart)
373
+ endmatch = endprog.match(line)
374
+ if endmatch:
375
+ pos = end = endmatch.end(0)
376
+ yield (STRING, contstr + line[:end],
377
+ strstart, (lnum, end), contline + line)
378
+ contstr, needcont = '', 0
379
+ contline = None
380
+ elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
381
+ yield (ERRORTOKEN, contstr + line,
382
+ strstart, (lnum, len(line)), contline)
383
+ contstr = ''
384
+ contline = None
385
+ continue
386
+ else:
387
+ contstr = contstr + line
388
+ contline = contline + line
389
+ continue
390
+
391
+ elif parenlev == 0 and not continued: # new statement
392
+ if not line: break
393
+ column = 0
394
+ while pos < max: # measure leading whitespace
395
+ if line[pos] == ' ': column = column + 1
396
+ elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize
397
+ elif line[pos] == '\f': column = 0
398
+ else: break
399
+ pos = pos + 1
400
+ if pos == max: break
401
+
402
+ if stashed:
403
+ yield stashed
404
+ stashed = None
405
+
406
+ if line[pos] in '#\r\n': # skip comments or blank lines
407
+ if line[pos] == '#':
408
+ comment_token = line[pos:].rstrip('\r\n')
409
+ nl_pos = pos + len(comment_token)
410
+ yield (COMMENT, comment_token,
411
+ (lnum, pos), (lnum, pos + len(comment_token)), line)
412
+ yield (NL, line[nl_pos:],
413
+ (lnum, nl_pos), (lnum, len(line)), line)
414
+ else:
415
+ yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],
416
+ (lnum, pos), (lnum, len(line)), line)
417
+ continue
418
+
419
+ if column > indents[-1]: # count indents or dedents
420
+ indents.append(column)
421
+ yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
422
+ while column < indents[-1]:
423
+ if column not in indents:
424
+ raise IndentationError(
425
+ "unindent does not match any outer indentation level",
426
+ ("<tokenize>", lnum, pos, line))
427
+ indents = indents[:-1]
428
+
429
+ if async_def and async_def_indent >= indents[-1]:
430
+ async_def = False
431
+ async_def_nl = False
432
+ async_def_indent = 0
433
+
434
+ yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
435
+
436
+ if async_def and async_def_nl and async_def_indent >= indents[-1]:
437
+ async_def = False
438
+ async_def_nl = False
439
+ async_def_indent = 0
440
+
441
+ else: # continued statement
442
+ if not line:
443
+ raise TokenError("EOF in multi-line statement", (lnum, 0))
444
+ continued = 0
445
+
446
+ while pos < max:
447
+ pseudomatch = pseudoprog.match(line, pos)
448
+ if pseudomatch: # scan for tokens
449
+ start, end = pseudomatch.span(1)
450
+ spos, epos, pos = (lnum, start), (lnum, end), end
451
+ token, initial = line[start:end], line[start]
452
+
453
+ if initial in string.digits or \
454
+ (initial == '.' and token != '.'): # ordinary number
455
+ yield (NUMBER, token, spos, epos, line)
456
+ elif initial in '\r\n':
457
+ newline = NEWLINE
458
+ if parenlev > 0:
459
+ newline = NL
460
+ elif async_def:
461
+ async_def_nl = True
462
+ if stashed:
463
+ yield stashed
464
+ stashed = None
465
+ yield (newline, token, spos, epos, line)
466
+
467
+ elif initial == '#':
468
+ assert not token.endswith("\n")
469
+ if stashed:
470
+ yield stashed
471
+ stashed = None
472
+ yield (COMMENT, token, spos, epos, line)
473
+ elif token in triple_quoted:
474
+ endprog = endprogs[token]
475
+ endmatch = endprog.match(line, pos)
476
+ if endmatch: # all on one line
477
+ pos = endmatch.end(0)
478
+ token = line[start:pos]
479
+ if stashed:
480
+ yield stashed
481
+ stashed = None
482
+ yield (STRING, token, spos, (lnum, pos), line)
483
+ else:
484
+ strstart = (lnum, start) # multiple lines
485
+ contstr = line[start:]
486
+ contline = line
487
+ break
488
+ elif initial in single_quoted or \
489
+ token[:2] in single_quoted or \
490
+ token[:3] in single_quoted:
491
+ if token[-1] == '\n': # continued string
492
+ strstart = (lnum, start)
493
+ endprog = (endprogs[initial] or endprogs[token[1]] or
494
+ endprogs[token[2]])
495
+ contstr, needcont = line[start:], 1
496
+ contline = line
497
+ break
498
+ else: # ordinary string
499
+ if stashed:
500
+ yield stashed
501
+ stashed = None
502
+ yield (STRING, token, spos, epos, line)
503
+ elif initial.isidentifier(): # ordinary name
504
+ if token in ('async', 'await'):
505
+ if async_def:
506
+ yield (ASYNC if token == 'async' else AWAIT,
507
+ token, spos, epos, line)
508
+ continue
509
+
510
+ tok = (NAME, token, spos, epos, line)
511
+ if token == 'async' and not stashed:
512
+ stashed = tok
513
+ continue
514
+
515
+ if token in ('def', 'for'):
516
+ if (stashed
517
+ and stashed[0] == NAME
518
+ and stashed[1] == 'async'):
519
+
520
+ if token == 'def':
521
+ async_def = True
522
+ async_def_indent = indents[-1]
523
+
524
+ yield (ASYNC, stashed[1],
525
+ stashed[2], stashed[3],
526
+ stashed[4])
527
+ stashed = None
528
+
529
+ if stashed:
530
+ yield stashed
531
+ stashed = None
532
+
533
+ yield tok
534
+ elif initial == '\\': # continued stmt
535
+ # This yield is new; needed for better idempotency:
536
+ if stashed:
537
+ yield stashed
538
+ stashed = None
539
+ yield (NL, token, spos, (lnum, pos), line)
540
+ continued = 1
541
+ else:
542
+ if initial in '([{': parenlev = parenlev + 1
543
+ elif initial in ')]}': parenlev = parenlev - 1
544
+ if stashed:
545
+ yield stashed
546
+ stashed = None
547
+ yield (OP, token, spos, epos, line)
548
+ else:
549
+ yield (ERRORTOKEN, line[pos],
550
+ (lnum, pos), (lnum, pos+1), line)
551
+ pos = pos + 1
552
+
553
+ if stashed:
554
+ yield stashed
555
+ stashed = None
556
+
557
+ for indent in indents[1:]: # pop remaining indent levels
558
+ yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
559
+ yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
560
+
561
+ if __name__ == '__main__': # testing
562
+ import sys
563
+ if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline)
564
+ else: tokenize(sys.stdin.readline)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Author: Collin Winter
2
+
3
+ import os
4
+
5
+ from test.support import load_package_tests
6
+
7
+ def load_tests(*args):
8
+ return load_package_tests(os.path.dirname(__file__), *args)
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from . import load_tests
2
+ import unittest
3
+
4
+ unittest.main()
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/README ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ In this directory:
2
+ - py2_test_grammar.py -- test file that exercises most/all of Python 2.x's grammar.
3
+ - py3_test_grammar.py -- test file that exercises most/all of Python 3.x's grammar.
4
+ - infinite_recursion.py -- test file that causes lib2to3's faster recursive pattern matching
5
+ scheme to fail, but passes when lib2to3 falls back to iterative pattern matching.
6
+ - fixes/ -- for use by test_refactor.py
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/bom.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # coding: utf-8
2
+ print "BOM BOOM!"
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/crlf.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ print "hi"
2
+
3
+ print "Like bad Windows newlines?"
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/different_encoding.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ print u'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'
4
+
5
+ def f(x):
6
+ print '%s\t-> α(%2i):%s β(%s)'
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/false_encoding.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #!/usr/bin/env python
2
+ print '#coding=0'
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/fixers/bad_order.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from lib2to3.fixer_base import BaseFix
2
+
3
+ class FixBadOrder(BaseFix):
4
+
5
+ order = "crazy"
miniconda3/pkgs/python-3.10.20-h741d88c_0/lib/python3.10/lib2to3/tests/data/fixers/myfixes/__init__.py ADDED
File without changes