Bug 2584078
| Summary: | python-gast fails to build with Python 3.16: UnparserTestCase.test_ast_py: AssertionError | ||
|---|---|---|---|
| Product: | [Fedora] Fedora | Reporter: | Karolina Surma <ksurma> |
| Component: | python-gast | Assignee: | Miro HronĨok <mhroncok> |
| Status: | NEW --- | QA Contact: | Fedora Extras Quality Assurance <extras-qa> |
| Severity: | unspecified | Docs Contact: | |
| Priority: | unspecified | ||
| Version: | rawhide | CC: | ksurma, mhroncok, python-packagers-sig |
| Target Milestone: | --- | ||
| Target Release: | --- | ||
| Hardware: | Unspecified | ||
| OS: | Unspecified | ||
| Whiteboard: | |||
| Fixed In Version: | Doc Type: | --- | |
| Doc Text: | Story Points: | --- | |
| Clone Of: | Environment: | ||
| Last Closed: | Type: | Bug | |
| Regression: | --- | Mount Type: | --- |
| Documentation: | --- | CRM: | |
| Verified Versions: | Category: | --- | |
| oVirt Team: | --- | RHEL 7.3 requirements from Atomic Host: | |
| Cloudforms Team: | --- | Target Upstream Version: | |
| Embargoed: | |||
| Bug Depends On: | |||
| Bug Blocks: | 2567340 | ||
python-gast fails to build with Python 3.16.0a2. _________________________ UnparserTestCase.test_ast_py _________________________ self = <tests.test_unparser.UnparserTestCase testMethod=test_ast_py> def test_ast_py(self): with open(ast.__file__) as astfd: > self.assertUnparse(astfd.read(), parse_only=sys.version_info < (3, 12)) tests/test_unparser.py:30: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ tests/test_unparser.py:20: in assertUnparse self.assertEqual(normalized_code, unparsed) E AssertionError: '"""\[1054 chars]t *\nlazy import warnings\n\ndef parse(source,[24989 chars]in()' != '"""\[1054 chars]t *\nimport warnings\n\ndef parse(source, file[24984 chars]in()' E """ E The `ast` module helps Python applications to process trees of the Python E abstract syntax grammar. The abstract syntax itself might change with E each Python release; this module helps to find out programmatically what E the current grammar looks like and allows modifications of it. E E An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as E a flag to the `compile()` builtin function or by using the `parse()` E function from this module. The result will be a tree of objects whose E classes all inherit from `ast.AST`. E E A modified abstract syntax tree can be compiled into a Python code object E using the built-in `compile()` function. E E Additionally various helper functions are provided that make working with E the trees simpler. The main intention of the helper functions and this E module in general is to provide an easy to use interface for libraries E that work tightly with the python syntax (template engines for example). E E :copyright: Copyright 2008 by Armin Ronacher. E :license: Python License. E """ E from _ast import * E - lazy import warnings E ? ----- E + import warnings E E def parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1, module=None): E """ E Parse the source into an AST node. E Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). E Pass type_comments=True to get back type comments where the syntax allows. E """ E flags = PyCF_ONLY_AST E if optimize > 0: E flags |= PyCF_OPTIMIZED_AST E if type_comments: E flags |= PyCF_TYPE_COMMENTS E if feature_version is None: E feature_version = -1 E elif isinstance(feature_version, tuple): E major, minor = feature_version E if major != 3: E raise ValueError(f'Unsupported major version: {major}') E feature_version = minor E return compile(source, filename, mode, flags, _feature_version=feature_version, optimize=optimize, module=module) E E def literal_eval(node_or_string): E """ E Evaluate an expression node or a string containing only a Python E expression. The string or node provided may only consist of the following E Python literal structures: strings, bytes, numbers, tuples, lists, dicts, E sets, booleans, and None. E E Caution: A complex expression can overflow the C stack and cause a crash. E """ E if isinstance(node_or_string, str): E node_or_string = parse(node_or_string.lstrip(' \t'), mode='eval').body E elif isinstance(node_or_string, Expression): E node_or_string = node_or_string.body E return _convert_literal(node_or_string) E E def _convert_literal(node): E """ E Used by `literal_eval` to convert an AST node into a value. E """ E if isinstance(node, Constant): E return node.value E if isinstance(node, Dict) and len(node.keys) == len(node.values): E return dict(zip(map(_convert_literal, node.keys), map(_convert_literal, node.values))) E if isinstance(node, Tuple): E return tuple(map(_convert_literal, node.elts)) E if isinstance(node, List): E return list(map(_convert_literal, node.elts)) E if isinstance(node, Set): E return set(map(_convert_literal, node.elts)) E if isinstance(node, Call) and isinstance(node.func, Name) and (node.func.id == 'set') and (node.args == node.keywords == []): E return set() E if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)) and isinstance(node.operand, Constant) and (type((operand := node.operand.value)) in (int, float, complex)): E if isinstance(node.op, UAdd): E return +operand E else: E return -operand E if isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)) and isinstance(node.left, (Constant, UnaryOp)) and isinstance(node.right, Constant) and (type((left := _convert_literal(node.left))) in (int, float)) and (type((right := _convert_literal(node.right))) is complex): E if isinstance(node.op, Add): E return left + right E else: E return left - right E msg = 'malformed node or string' E if (lno := getattr(node, 'lineno', None)): E msg += f' on line {lno}' E raise ValueError(msg + f': {node!r}') E E def dump(node, annotate_fields=True, include_attributes=False, *, color=False, indent=None, show_empty=False): E """ E Return a formatted dump of the tree in node. This is mainly useful for E debugging purposes. E E If annotate_fields is true (by default), the returned string will show the E names and the values for fields. If annotate_fields is false, the result E string will be more compact by omitting unambiguous field names. E E Attributes such as line numbers and column offsets are not dumped by default. E If this is wanted, include_attributes can be set to true. E E If color is true, the returned string is syntax highlighted using ANSI E escape sequences. If color is false (the default), colored output is always E disabled. E E If indent is a non-negative integer or string, then the tree will be E pretty-printed with that indent level. If indent is None (the default), E the tree is dumped on a single line. E E If show_empty is False, then empty lists and fields that are None E will be omitted from the output for better readability. E """ E from _colorize import get_theme E t = get_theme(force_color=color, force_no_color=not color).ast E E def _format(node, level=0): E if indent is not None: E level += 1 E prefix = '\n' + indent * level E sep = ',\n' + indent * level E else: E prefix = '' E sep = ', ' E if isinstance(node, AST): E cls = type(node) E args = [] E args_buffer = [] E allsimple = True E keywords = annotate_fields E for name in node._fields: E try: E value = getattr(node, name) E except AttributeError: E keywords = True E continue E if value is None and getattr(cls, name, ...) is None: E keywords = True E continue E if not show_empty: E if value == []: E field_type = cls._field_types.get(name, object) E if getattr(field_type, '__origin__', ...) is list: E if not keywords: E args_buffer.append(repr(value)) E continue E elif isinstance(value, Load): E field_type = cls._field_types.get(name, object) E if field_type is expr_context: E if not keywords: E args_buffer.append(f'{t.node}{type(value).__name__}{t.reset}()') E continue E if not keywords: E args.extend(args_buffer) E args_buffer = [] E value, simple = _format(value, level) E allsimple = allsimple and simple E if keywords: E args.append(f'{t.field}{name}{t.reset}={value}') E else: E args.append(value) E if include_attributes and node._attributes: E for name in node._attributes: E try: E value = getattr(node, name) E except AttributeError: E continue E if value is None and getattr(cls, name, ...) is None: E continue E value, simple = _format(value, level) E allsimple = allsimple and simple E args.append(f'{t.attribute}{name}{t.reset}={value}') E cls_name = f'{t.node}{cls.__name__}{t.reset}' E if allsimple and len(args) <= 3: E return (f"{cls_name}({', '.join(args)})", not args) E return (f'{cls_name}({prefix}{sep.join(args)})', False) E elif isinstance(node, list): E if not node: E return ('[]', True) E return ('[%s%s]' % (prefix, sep.join((_format(x, level)[0] for x in node))), False) E if isinstance(node, bool) or node is None or node is Ellipsis: E return (f'{t.keyword}{node!r}{t.reset}', True) E if isinstance(node, (int, float, complex)): E return (f'{t.number}{node!r}{t.reset}', True) E if isinstance(node, (str, bytes)): E return (f'{t.string}{node!r}{t.reset}', True) E return (repr(node), True) E if not isinstance(node, AST): E raise TypeError('expected AST, got %r' % node.__class__.__name__) E if indent is not None and (not isinstance(indent, str)): E indent = ' ' * indent E return _format(node)[0] E E def copy_location(new_node, old_node): E """ E Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` E attributes) from *old_node* to *new_node* if possible, and return *new_node*. E """ E for attr in ('lineno', 'col_offset', 'end_lineno', 'end_col_offset'): E if attr in old_node._attributes and attr in new_node._attributes: E value = getattr(old_node, attr, None) E if value is not None or (hasattr(old_node, attr) and attr.startswith('end_')): E setattr(new_node, attr, value) E return new_node E E def fix_missing_locations(node): E """ E When you compile a node tree with compile(), the compiler expects lineno and E col_offset attributes for every node that supports them. This is rather E tedious to fill in for generated nodes, so this helper adds these attributes E recursively where not already set, by setting them to the values of the E parent node. It works recursively starting at *node*. E """ E E def _fix(node, lineno, col_offset, end_lineno, end_col_offset): E if 'lineno' in node._attributes: E if not hasattr(node, 'lineno'): E node.lineno = lineno E else: E lineno = node.lineno E if 'end_lineno' in node._attributes: E if getattr(node, 'end_lineno', None) is None: E node.end_lineno = end_lineno E else: E end_lineno = node.end_lineno E if 'col_offset' in node._attributes: E if not hasattr(node, 'col_offset'): E node.col_offset = col_offset E else: E col_offset = node.col_offset E if 'end_col_offset' in node._attributes: E if getattr(node, 'end_col_offset', None) is None: E node.end_col_offset = end_col_offset E else: E end_col_offset = node.end_col_offset E for child in iter_child_nodes(node): E _fix(child, lineno, col_offset, end_lineno, end_col_offset) E _fix(node, 1, 0, 1, 0) E return node E E def increment_lineno(node, n=1): E """ E Increment the line number and end line number of each node in the tree E starting at *node* by *n*. This is useful to "move code" to a different E location in a file. E """ E for child in walk(node): E if isinstance(child, TypeIgnore): E child.lineno = getattr(child, 'lineno', 0) + n E continue E if 'lineno' in child._attributes: E child.lineno = getattr(child, 'lineno', 0) + n E if 'end_lineno' in child._attributes and (end_lineno := getattr(child, 'end_lineno', 0)) is not None: E child.end_lineno = end_lineno + n E return node E E def iter_fields(node): E """ E Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` E that is present on *node*. E """ E for field in node._fields: E try: E yield (field, getattr(node, field)) E except AttributeError: E pass E E def iter_child_nodes(node): E """ E Yield all direct child nodes of *node*, that is, all fields that are nodes E and all items of fields that are lists of nodes. E """ E for name, field in iter_fields(node): E if isinstance(field, AST): E yield field E elif isinstance(field, list): E for item in field: E if isinstance(item, AST): E yield item E E def get_docstring(node, clean=True): E """ E Return the docstring for the given node or None if no docstring can E be found. If the node provided does not have docstrings a TypeError E will be raised. E E If *clean* is `True`, all tabs are expanded to spaces and any whitespace E that can be uniformly removed from the second line onwards is removed. E """ E if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)): E raise TypeError("%r can't have docstrings" % node.__class__.__name__) E if not (node.body and isinstance(node.body[0], Expr)): E return None E node = node.body[0].value E if isinstance(node, Constant) and isinstance(node.value, str): E text = node.value E else: E return None E if clean: E import inspect E text = inspect.cleandoc(text) E return text E _line_pattern = None E E def _splitlines_no_ff(source, maxlines=None): E """Split a string into lines ignoring form feed and other chars. E E This mimics how the Python parser splits source code. E """ E global _line_pattern E if _line_pattern is None: E import re E _line_pattern = re.compile('(.*?(?:\\r\\n|\\n|\\r|$))') E lines = [] E for lineno, match in enumerate(_line_pattern.finditer(source), 1): E if maxlines is not None and lineno > maxlines: E break E lines.append(match[0]) E return lines E E def _pad_whitespace(source): E """Replace all chars except '\\f\\t' in a line with spaces.""" E result = '' E for c in source: E if c in '\x0c\t': E result += c E else: E result += ' ' E return result E E def get_source_segment(source, node, *, padded=False): E """Get source code segment of the *source* that generated *node*. E E If some location information (`lineno`, `end_lineno`, `col_offset`, E or `end_col_offset`) is missing, return None. E E If *padded* is `True`, the first line of a multi-line statement will E be padded with spaces to match its original position. E """ E try: E if node.end_lineno is None or node.end_col_offset is None: E return None E lineno = node.lineno - 1 E end_lineno = node.end_lineno - 1 E col_offset = node.col_offset E end_col_offset = node.end_col_offset E except AttributeError: E return None E lines = _splitlines_no_ff(source, maxlines=end_lineno + 1) E if end_lineno == lineno: E return lines[lineno].encode()[col_offset:end_col_offset].decode() E if padded: E padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode()) E else: E padding = '' E first = padding + lines[lineno].encode()[col_offset:].decode() E last = lines[end_lineno].encode()[:end_col_offset].decode() E lines = lines[lineno + 1:end_lineno] E lines.insert(0, first) E lines.append(last) E return ''.join(lines) E E def walk(node): E """ E Recursively yield all descendant nodes in the tree starting at *node* E (including *node* itself), in no specified order. This is useful if you E only want to modify nodes in place and don't care about the context. E """ E from collections import deque E todo = deque([node]) E while todo: E node = todo.popleft() E todo.extend(iter_child_nodes(node)) E yield node E E def compare(a, b, /, *, compare_attributes=False): E """Recursively compares two ASTs. E E compare_attributes affects whether AST attributes are considered E in the comparison. If compare_attributes is False (default), then E attributes are ignored. Otherwise they must all be equal. This E option is useful to check whether the ASTs are structurally equal but E might differ in whitespace or similar details. E """ E sentinel = object() E E def _compare(a, b): E if isinstance(a, AST): E return compare(a, b, compare_attributes=compare_attributes) E elif isinstance(a, list): E if len(a) != len(b): E return False E for a_item, b_item in zip(a, b): E if not _compare(a_item, b_item): E return False E else: E return True E else: E return type(a) is type(b) and a == b E E def _compare_fields(a, b): E if a._fields != b._fields: E return False E for field in a._fields: E a_field = getattr(a, field, sentinel) E b_field = getattr(b, field, sentinel) E if a_field is sentinel and b_field is sentinel: E continue E if a_field is sentinel or b_field is sentinel: E return False E if not _compare(a_field, b_field): E return False E else: E return True E E def _compare_attributes(a, b): E if a._attributes != b._attributes: E return False E for attr in a._attributes: E a_attr = getattr(a, attr, sentinel) E b_attr = getattr(b, attr, sentinel) E if a_attr is sentinel and b_attr is sentinel: E continue E if a_attr != b_attr: E return False E else: E return True E if type(a) is not type(b): E return False E if not _compare_fields(a, b): E return False E if compare_attributes and (not _compare_attributes(a, b)): E return False E return True E E class NodeVisitor(object): E """ E A node visitor base class that walks the abstract syntax tree and calls a E visitor function for every node found. This function may return a value E which is forwarded by the `visit` method. E E This class is meant to be subclassed, with the subclass adding visitor E methods. E E Per default the visitor functions for the nodes are ``'visit_'`` + E class name of the node. So a `TryFinally` node visit function would E be `visit_TryFinally`. This behavior can be changed by overriding E the `visit` method. If no visitor function exists for a node E (return value `None`) the `generic_visit` visitor is used instead. E E Don't use the `NodeVisitor` if you want to apply changes to nodes during E traversing. For this a special visitor exists (`NodeTransformer`) that E allows modifications. E """ E E def visit(self, node): E """Visit a node.""" E method = 'visit_' + node.__class__.__name__ E visitor = getattr(self, method, self.generic_visit) E return visitor(node) E E def generic_visit(self, node): E """Called if no explicit visitor function exists for a node.""" E for field, value in iter_fields(node): E if isinstance(value, list): E for item in value: E if isinstance(item, AST): E self.visit(item) E elif isinstance(value, AST): E self.visit(value) E E class NodeTransformer(NodeVisitor): E """ E A :class:`NodeVisitor` subclass that walks the abstract syntax tree and E allows modification of nodes. E E The `NodeTransformer` will walk the AST and use the return value of the E visitor methods to replace or remove the old node. If the return value of E the visitor method is ``None``, the node will be removed from its location, E otherwise it is replaced with the return value. The return value may be the E original node in which case no replacement takes place. E E Here is an example transformer that rewrites all occurrences of name lookups E (``foo``) to ``data['foo']``:: E E class RewriteName(NodeTransformer): E E def visit_Name(self, node): E return Subscript( E value=Name(id='data', ctx=Load()), E slice=Constant(value=node.id), E ctx=node.ctx E ) E E Keep in mind that if the node you're operating on has child nodes you must E either transform the child nodes yourself or call the :meth:`generic_visit` E method for the node first. E E For nodes that were part of a collection of statements (that applies to all E statement nodes), the visitor may also return a list of nodes rather than E just a single node. E E Usually you use the transformer like this:: E E node = YourTransformer().visit(node) E """ E E def generic_visit(self, node): E for field, old_value in iter_fields(node): E if isinstance(old_value, list): E new_values = [] E for value in old_value: E if isinstance(value, AST): E value = self.visit(value) E if value is None: E continue E elif not isinstance(value, AST): E new_values.extend(value) E continue E new_values.append(value) E old_value[:] = new_values E elif isinstance(old_value, AST): E new_node = self.visit(old_value) E if new_node is None: E delattr(node, field) E else: E setattr(node, field, new_node) E return node E E class slice(AST): E """Deprecated AST node class.""" E E class Index(slice): E """Deprecated AST node class. Use the index value directly instead.""" E E def __new__(cls, value, **kwargs): E return value E E class ExtSlice(slice): E """Deprecated AST node class. Use ast.Tuple instead.""" E E def __new__(cls, dims=(), **kwargs): E return Tuple(list(dims), Load(), **kwargs) E if not hasattr(Tuple, 'dims'): E E def _dims_getter(self): E """Deprecated. Use elts instead.""" E warnings._deprecated(f'ast.Tuple.dims', remove=(3, 21)) E return self.elts E E def _dims_setter(self, value): E warnings._deprecated(f'ast.Tuple.dims', remove=(3, 21)) E self.elts = value E Tuple.dims = property(_dims_getter, _dims_setter) E E class Suite(mod): E """Deprecated AST node class. Unused in Python 3.""" E E class AugLoad(expr_context): E """Deprecated AST node class. Unused in Python 3.""" E E class AugStore(expr_context): E """Deprecated AST node class. Unused in Python 3.""" E E class Param(expr_context): E """Deprecated AST node class. Unused in Python 3.""" E E def unparse(ast_obj): E global _Unparser E try: E unparser = _Unparser() E except NameError: E from _ast_unparse import Unparser as _Unparser E unparser = _Unparser() E return unparser.visit(ast_obj) E E def main(args=None): E import argparse E import sys E parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) E parser.add_argument('infile', nargs='?', default='-', help='the file to parse; defaults to `stdin`') E parser.add_argument('-m', '--mode', default='exec', choices=('exec', 'single', 'eval', 'func_type'), help='specify what kind of code must be parsed') E parser.add_argument('--no-type-comments', default=True, action='store_false', help="don't add information about type comments") E parser.add_argument('-a', '--include-attributes', action='store_true', help='include attributes such as line numbers and column offsets') E parser.add_argument('-i', '--indent', type=int, default=3, help='indentation of nodes (number of spaces)') E parser.add_argument('--feature-version', type=str, default=None, metavar='VERSION', help='Python version in the format `3.x` (for example, `3.10`)') E parser.add_argument('-O', '--optimize', type=int, default=-1, metavar='LEVEL', help='optimization level for parser') E parser.add_argument('--show-empty', default=False, action='store_true', help='show empty lists and fields in dump output') E args = parser.parse_args(args) E if args.infile == '-': E name = '<stdin>' E source = sys.stdin.buffer.read() E else: E name = args.infile E with open(args.infile, 'rb') as infile: E source = infile.read() E feature_version = None E if args.feature_version: E try: E major, minor = map(int, args.feature_version.split('.', 1)) E except ValueError: E parser.error('Invalid format for --feature-version; expected format 3.x (for example, 3.10)') E feature_version = (major, minor) E tree = parse(source, name, args.mode, type_comments=args.no_type_comments, feature_version=feature_version, optimize=args.optimize) E from _colorize import can_colorize E print(dump(tree, include_attributes=args.include_attributes, color=can_colorize(file=sys.stdout), indent=args.indent, show_empty=args.show_empty)) E _deprecated = {'slice': globals().pop('slice'), 'Index': globals().pop('Index'), 'ExtSlice': globals().pop('ExtSlice'), 'Suite': globals().pop('Suite'), 'AugLoad': globals().pop('AugLoad'), 'AugStore': globals().pop('AugStore'), 'Param': globals().pop('Param')} E E def __getattr__(attr): E try: E val = _deprecated[attr] E except KeyError: E raise AttributeError(f"module 'ast' has no attribute {attr!r}") from None E warnings._deprecated(f'ast.{attr}', remove=(3, 21)) E return val E if __name__ == '__main__': E main() https://docs.python.org/3.16/whatsnew/3.16.html For the build logs, see: https://copr-be.cloud.fedoraproject.org/results/@python/python3.16/fedora-rawhide-x86_64/11359643-python-gast/ For all our attempts to build python-gast with Python 3.16, see: https://copr.fedorainfracloud.org/coprs/g/python/python3.16/package/python-gast/ Testing and mass rebuild of packages is happening in copr. You can follow these instructions to test locally in mock if your package builds with Python 3.16: https://copr.fedorainfracloud.org/coprs/g/python/python3.16/ Let us know here if you have any questions. Python 3.16 is planned to be included in Fedora 47. To make that update smoother, we're building Fedora packages with all pre-releases of Python 3.16. A build failure prevents us from testing all dependent packages (transitive [Build]Requires), so if this package is required a lot, it's important for us to get it fixed soon. We'd appreciate help from the people who know this package best, but if you don't want to work on this now, let us know so we can try to work around it on our side.