Skip to content
Snippets Groups Projects
Commit 8fa43645 authored by Apertis package maintainers's avatar Apertis package maintainers
Browse files

Import Upstream version 0.8.1

parents
Branches upstream/bookworm upstream/bullseye upstream/trixie
Tags upstream/0.8.1
No related merge requests found
Pipeline #873697 skipped
Showing with 1458 additions and 0 deletions
AUTHORS 0 → 100644
Original author of astor/codegen.py:
* Armin Ronacher <armin.ronacher@active-4.com>
And with some modifications based on Armin's code:
* Paul Dubs <paul.dubs@gmail.com>
* Berker Peksag <berker.peksag@gmail.com>
* Patrick Maupin <pmaupin@gmail.com>
* Abhishek L <abhishek.lekshmanan@gmail.com>
* Bob Tolbert <bob@eyesopen.com>
* Whyzgeek <whyzgeek@gmail.com>
* Zack M. Davis <code@zackmdavis.net>
* Ryan Gonzalez <rymg19@gmail.com>
* Lenny Truong <leonardtruong@protonmail.com>
* Radomír Bosák <radomir.bosak@gmail.com>
* Kodi Arfer <git@arfer.net>
* Felix Yan <felixonmars@archlinux.org>
* Chris Rink <chrisrink10@gmail.com>
* Batuhan Taskaya <batuhanosmantaskaya@gmail.com>
LICENSE 0 → 100644
Copyright (c) 2012, Patrick Maupin
Copyright (c) 2013, Berker Peksag
Copyright (c) 2008, Armin Ronacher
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include README.rst AUTHORS LICENSE CHANGES
include setuputils.py
include astor/VERSION
recursive-include tests *.py
PKG-INFO 0 → 100644
Metadata-Version: 1.2
Name: astor
Version: 0.8.1
Summary: Read/rewrite/write Python ASTs
Home-page: https://github.com/berkerpeksag/astor
Author: Patrick Maupin
Author-email: pmaupin@gmail.com
License: BSD-3-Clause
Description: =============================
astor -- AST observe/rewrite
=============================
:PyPI: https://pypi.org/project/astor/
:Documentation: https://astor.readthedocs.io
:Source: https://github.com/berkerpeksag/astor
:License: 3-clause BSD
:Build status:
.. image:: https://secure.travis-ci.org/berkerpeksag/astor.svg
:alt: Travis CI
:target: https://travis-ci.org/berkerpeksag/astor/
astor is designed to allow easy manipulation of Python source via the AST.
There are some other similar libraries, but astor focuses on the following areas:
- Round-trip an AST back to Python [1]_:
- Modified AST doesn't need linenumbers, ctx, etc. or otherwise
be directly compileable for the round-trip to work.
- Easy to read generated code as, well, code
- Can round-trip two different source trees to compare for functional
differences, using the astor.rtrip tool (for example, after PEP8 edits).
- Dump pretty-printing of AST
- Harder to read than round-tripped code, but more accurate to figure out what
is going on.
- Easier to read than dump from built-in AST module
- Non-recursive treewalk
- Sometimes you want a recursive treewalk (and astor supports that, starting
at any node on the tree), but sometimes you don't need to do that. astor
doesn't require you to explicitly visit sub-nodes unless you want to:
- You can add code that executes before a node's children are visited, and/or
- You can add code that executes after a node's children are visited, and/or
- You can add code that executes and keeps the node's children from being
visited (and optionally visit them yourself via a recursive call)
- Write functions to access the tree based on object names and/or attribute names
- Enjoy easy access to parent node(s) for tree rewriting
.. [1]
The decompilation back to Python is based on code originally written
by Armin Ronacher. Armin's code was well-structured, but failed on
some obscure corner cases of the Python language (and even more corner
cases when the AST changed on different versions of Python), and its
output arguably had cosmetic issues -- for example, it produced
parentheses even in some cases where they were not needed, to
avoid having to reason about precedence.
Other derivatives of Armin's code are floating around, and typically
have fixes for a few corner cases that happened to be noticed by the
maintainers, but most of them have not been tested as thoroughly as
astor. One exception may be the version of codegen
`maintained at github by CensoredUsername`__. This has been tested
to work properly on Python 2.7 using astor's test suite, and, as it
is a single source file, it may be easier to drop into some applications
that do not require astor's other features or Python 3.x compatibility.
__ https://github.com/CensoredUsername/codegen
Keywords: ast,codegen,PEP 8
Platform: Independent
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: Implementation
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Compilers
Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7
=============================
astor -- AST observe/rewrite
=============================
:PyPI: https://pypi.org/project/astor/
:Documentation: https://astor.readthedocs.io
:Source: https://github.com/berkerpeksag/astor
:License: 3-clause BSD
:Build status:
.. image:: https://secure.travis-ci.org/berkerpeksag/astor.svg
:alt: Travis CI
:target: https://travis-ci.org/berkerpeksag/astor/
astor is designed to allow easy manipulation of Python source via the AST.
There are some other similar libraries, but astor focuses on the following areas:
- Round-trip an AST back to Python [1]_:
- Modified AST doesn't need linenumbers, ctx, etc. or otherwise
be directly compileable for the round-trip to work.
- Easy to read generated code as, well, code
- Can round-trip two different source trees to compare for functional
differences, using the astor.rtrip tool (for example, after PEP8 edits).
- Dump pretty-printing of AST
- Harder to read than round-tripped code, but more accurate to figure out what
is going on.
- Easier to read than dump from built-in AST module
- Non-recursive treewalk
- Sometimes you want a recursive treewalk (and astor supports that, starting
at any node on the tree), but sometimes you don't need to do that. astor
doesn't require you to explicitly visit sub-nodes unless you want to:
- You can add code that executes before a node's children are visited, and/or
- You can add code that executes after a node's children are visited, and/or
- You can add code that executes and keeps the node's children from being
visited (and optionally visit them yourself via a recursive call)
- Write functions to access the tree based on object names and/or attribute names
- Enjoy easy access to parent node(s) for tree rewriting
.. [1]
The decompilation back to Python is based on code originally written
by Armin Ronacher. Armin's code was well-structured, but failed on
some obscure corner cases of the Python language (and even more corner
cases when the AST changed on different versions of Python), and its
output arguably had cosmetic issues -- for example, it produced
parentheses even in some cases where they were not needed, to
avoid having to reason about precedence.
Other derivatives of Armin's code are floating around, and typically
have fixes for a few corner cases that happened to be noticed by the
maintainers, but most of them have not been tested as thoroughly as
astor. One exception may be the version of codegen
`maintained at github by CensoredUsername`__. This has been tested
to work properly on Python 2.7 using astor's test suite, and, as it
is a single source file, it may be easier to drop into some applications
that do not require astor's other features or Python 3.x compatibility.
__ https://github.com/CensoredUsername/codegen
Metadata-Version: 1.2
Name: astor
Version: 0.8.1
Summary: Read/rewrite/write Python ASTs
Home-page: https://github.com/berkerpeksag/astor
Author: Patrick Maupin
Author-email: pmaupin@gmail.com
License: BSD-3-Clause
Description: =============================
astor -- AST observe/rewrite
=============================
:PyPI: https://pypi.org/project/astor/
:Documentation: https://astor.readthedocs.io
:Source: https://github.com/berkerpeksag/astor
:License: 3-clause BSD
:Build status:
.. image:: https://secure.travis-ci.org/berkerpeksag/astor.svg
:alt: Travis CI
:target: https://travis-ci.org/berkerpeksag/astor/
astor is designed to allow easy manipulation of Python source via the AST.
There are some other similar libraries, but astor focuses on the following areas:
- Round-trip an AST back to Python [1]_:
- Modified AST doesn't need linenumbers, ctx, etc. or otherwise
be directly compileable for the round-trip to work.
- Easy to read generated code as, well, code
- Can round-trip two different source trees to compare for functional
differences, using the astor.rtrip tool (for example, after PEP8 edits).
- Dump pretty-printing of AST
- Harder to read than round-tripped code, but more accurate to figure out what
is going on.
- Easier to read than dump from built-in AST module
- Non-recursive treewalk
- Sometimes you want a recursive treewalk (and astor supports that, starting
at any node on the tree), but sometimes you don't need to do that. astor
doesn't require you to explicitly visit sub-nodes unless you want to:
- You can add code that executes before a node's children are visited, and/or
- You can add code that executes after a node's children are visited, and/or
- You can add code that executes and keeps the node's children from being
visited (and optionally visit them yourself via a recursive call)
- Write functions to access the tree based on object names and/or attribute names
- Enjoy easy access to parent node(s) for tree rewriting
.. [1]
The decompilation back to Python is based on code originally written
by Armin Ronacher. Armin's code was well-structured, but failed on
some obscure corner cases of the Python language (and even more corner
cases when the AST changed on different versions of Python), and its
output arguably had cosmetic issues -- for example, it produced
parentheses even in some cases where they were not needed, to
avoid having to reason about precedence.
Other derivatives of Armin's code are floating around, and typically
have fixes for a few corner cases that happened to be noticed by the
maintainers, but most of them have not been tested as thoroughly as
astor. One exception may be the version of codegen
`maintained at github by CensoredUsername`__. This has been tested
to work properly on Python 2.7 using astor's test suite, and, as it
is a single source file, it may be easier to drop into some applications
that do not require astor's other features or Python 3.x compatibility.
__ https://github.com/CensoredUsername/codegen
Keywords: ast,codegen,PEP 8
Platform: Independent
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: Implementation
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Compilers
Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7
AUTHORS
LICENSE
MANIFEST.in
README.rst
setup.cfg
setup.py
setuputils.py
astor/VERSION
astor/__init__.py
astor/code_gen.py
astor/codegen.py
astor/file_util.py
astor/node_util.py
astor/op_util.py
astor/rtrip.py
astor/source_repr.py
astor/string_repr.py
astor/tree_walk.py
astor.egg-info/PKG-INFO
astor.egg-info/SOURCES.txt
astor.egg-info/dependency_links.txt
astor.egg-info/top_level.txt
astor.egg-info/zip-safe
tests/__init__.py
tests/build_expressions.py
tests/check_astunparse.py
tests/check_expressions.py
tests/support.py
tests/test_code_gen.py
tests/test_misc.py
tests/test_optional.py
tests/test_rtrip.py
\ No newline at end of file
astor
0.8.1
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright 2012 (c) Patrick Maupin
Copyright 2013 (c) Berker Peksag
"""
import os
import warnings
from .code_gen import SourceGenerator, to_source # NOQA
from .node_util import iter_node, strip_tree, dump_tree # NOQA
from .node_util import ExplicitNodeVisitor # NOQA
from .file_util import CodeToAst, code_to_ast # NOQA
from .op_util import get_op_symbol, get_op_precedence # NOQA
from .op_util import symbol_data # NOQA
from .tree_walk import TreeWalk # NOQA
ROOT = os.path.dirname(__file__)
with open(os.path.join(ROOT, 'VERSION')) as version_file:
__version__ = version_file.read().strip()
parse_file = code_to_ast.parse_file
# DEPRECATED!!!
# These aliases support old programs. Please do not use in future.
deprecated = """
get_boolop = get_binop = get_cmpop = get_unaryop = get_op_symbol
get_anyop = get_op_symbol
parsefile = code_to_ast.parse_file
codetoast = code_to_ast
dump = dump_tree
all_symbols = symbol_data
treewalk = tree_walk
codegen = code_gen
"""
exec(deprecated)
def deprecate():
def wrap(deprecated_name, target_name):
if '.' in target_name:
target_mod, target_fname = target_name.split('.')
target_func = getattr(globals()[target_mod], target_fname)
else:
target_func = globals()[target_name]
msg = "astor.%s is deprecated. Please use astor.%s." % (
deprecated_name, target_name)
if callable(target_func):
def newfunc(*args, **kwarg):
warnings.warn(msg, DeprecationWarning, stacklevel=2)
return target_func(*args, **kwarg)
else:
class ModProxy:
def __getattr__(self, name):
warnings.warn(msg, DeprecationWarning, stacklevel=2)
return getattr(target_func, name)
newfunc = ModProxy()
globals()[deprecated_name] = newfunc
for line in deprecated.splitlines(): # NOQA
line = line.split('#')[0].replace('=', '').split()
if line:
target_name = line.pop()
for deprecated_name in line:
wrap(deprecated_name, target_name)
deprecate()
del deprecate, deprecated
This diff is collapsed.
import warnings
from .code_gen import * # NOQA
warnings.warn(
'astor.codegen module is deprecated. Please import '
'astor.code_gen module instead.',
DeprecationWarning,
stacklevel=2
)
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright (c) 2012-2015 Patrick Maupin
Copyright (c) 2013-2015 Berker Peksag
Functions that interact with the filesystem go here.
"""
import ast
import sys
import os
try:
from tokenize import open as fopen
except ImportError:
fopen = open
class CodeToAst(object):
"""Given a module, or a function that was compiled as part
of a module, re-compile the module into an AST and extract
the sub-AST for the function. Allow caching to reduce
number of compiles.
Also contains static helper utility functions to
look for python files, to parse python files, and to extract
the file/line information from a code object.
"""
@staticmethod
def find_py_files(srctree, ignore=None):
"""Return all the python files in a source tree
Ignores any path that contains the ignore string
This is not used by other class methods, but is
designed to be used in code that uses this class.
"""
if not os.path.isdir(srctree):
yield os.path.split(srctree)
for srcpath, _, fnames in os.walk(srctree):
# Avoid infinite recursion for silly users
if ignore is not None and ignore in srcpath:
continue
for fname in (x for x in fnames if x.endswith('.py')):
yield srcpath, fname
@staticmethod
def parse_file(fname):
"""Parse a python file into an AST.
This is a very thin wrapper around ast.parse
TODO: Handle encodings other than the default for Python 2
(issue #26)
"""
try:
with fopen(fname) as f:
fstr = f.read()
except IOError:
if fname != 'stdin':
raise
sys.stdout.write('\nReading from stdin:\n\n')
fstr = sys.stdin.read()
fstr = fstr.replace('\r\n', '\n').replace('\r', '\n')
if not fstr.endswith('\n'):
fstr += '\n'
return ast.parse(fstr, filename=fname)
@staticmethod
def get_file_info(codeobj):
"""Returns the file and line number of a code object.
If the code object has a __file__ attribute (e.g. if
it is a module), then the returned line number will
be 0
"""
fname = getattr(codeobj, '__file__', None)
linenum = 0
if fname is None:
func_code = codeobj.__code__
fname = func_code.co_filename
linenum = func_code.co_firstlineno
fname = fname.replace('.pyc', '.py')
return fname, linenum
def __init__(self, cache=None):
self.cache = cache or {}
def __call__(self, codeobj):
cache = self.cache
key = self.get_file_info(codeobj)
result = cache.get(key)
if result is not None:
return result
fname = key[0]
cache[(fname, 0)] = mod_ast = self.parse_file(fname)
for obj in mod_ast.body:
if not isinstance(obj, ast.FunctionDef):
continue
cache[(fname, obj.lineno)] = obj
return cache[key]
code_to_ast = CodeToAst()
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright 2012-2015 (c) Patrick Maupin
Copyright 2013-2015 (c) Berker Peksag
Utilities for node (and, by extension, tree) manipulation.
For a whole-tree approach, see the treewalk submodule.
"""
import ast
import itertools
try:
zip_longest = itertools.zip_longest
except AttributeError:
zip_longest = itertools.izip_longest
class NonExistent(object):
"""This is not the class you are looking for.
"""
pass
def iter_node(node, name='', unknown=None,
# Runtime optimization
list=list, getattr=getattr, isinstance=isinstance,
enumerate=enumerate, missing=NonExistent):
"""Iterates over an object:
- If the object has a _fields attribute,
it gets attributes in the order of this
and returns name, value pairs.
- Otherwise, if the object is a list instance,
it returns name, value pairs for each item
in the list, where the name is passed into
this function (defaults to blank).
- Can update an unknown set with information about
attributes that do not exist in fields.
"""
fields = getattr(node, '_fields', None)
if fields is not None:
for name in fields:
value = getattr(node, name, missing)
if value is not missing:
yield value, name
if unknown is not None:
unknown.update(set(vars(node)) - set(fields))
elif isinstance(node, list):
for value in node:
yield value, name
def dump_tree(node, name=None, initial_indent='', indentation=' ',
maxline=120, maxmerged=80,
# Runtime optimization
iter_node=iter_node, special=ast.AST,
list=list, isinstance=isinstance, type=type, len=len):
"""Dumps an AST or similar structure:
- Pretty-prints with indentation
- Doesn't print line/column/ctx info
"""
def dump(node, name=None, indent=''):
level = indent + indentation
name = name and name + '=' or ''
values = list(iter_node(node))
if isinstance(node, list):
prefix, suffix = '%s[' % name, ']'
elif values:
prefix, suffix = '%s%s(' % (name, type(node).__name__), ')'
elif isinstance(node, special):
prefix, suffix = name + type(node).__name__, ''
else:
return '%s%s' % (name, repr(node))
node = [dump(a, b, level) for a, b in values if b != 'ctx']
oneline = '%s%s%s' % (prefix, ', '.join(node), suffix)
if len(oneline) + len(indent) < maxline:
return '%s' % oneline
if node and len(prefix) + len(node[0]) < maxmerged:
prefix = '%s%s,' % (prefix, node.pop(0))
node = (',\n%s' % level).join(node).lstrip()
return '%s\n%s%s%s' % (prefix, level, node, suffix)
return dump(node, name, initial_indent)
def strip_tree(node,
# Runtime optimization
iter_node=iter_node, special=ast.AST,
list=list, isinstance=isinstance, type=type, len=len):
"""Strips an AST by removing all attributes not in _fields.
Returns a set of the names of all attributes stripped.
This canonicalizes two trees for comparison purposes.
"""
stripped = set()
def strip(node, indent):
unknown = set()
leaf = True
for subnode, _ in iter_node(node, unknown=unknown):
leaf = False
strip(subnode, indent + ' ')
if leaf:
if isinstance(node, special):
unknown = set(vars(node))
stripped.update(unknown)
for name in unknown:
delattr(node, name)
if hasattr(node, 'ctx'):
delattr(node, 'ctx')
if 'ctx' in node._fields:
mylist = list(node._fields)
mylist.remove('ctx')
node._fields = mylist
strip(node, '')
return stripped
class ExplicitNodeVisitor(ast.NodeVisitor):
"""This expands on the ast module's NodeVisitor class
to remove any implicit visits.
"""
def abort_visit(node): # XXX: self?
msg = 'No defined handler for node of type %s'
raise AttributeError(msg % node.__class__.__name__)
def visit(self, node, abort=abort_visit):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, abort)
return visitor(node)
def allow_ast_comparison():
"""This ugly little monkey-patcher adds in a helper class
to all the AST node types. This helper class allows
eq/ne comparisons to work, so that entire trees can
be easily compared by Python's comparison machinery.
Used by the anti8 functions to compare old and new ASTs.
Could also be used by the test library.
"""
class CompareHelper(object):
def __eq__(self, other):
return type(self) == type(other) and vars(self) == vars(other)
def __ne__(self, other):
return type(self) != type(other) or vars(self) != vars(other)
for item in vars(ast).values():
if type(item) != type:
continue
if issubclass(item, ast.AST):
try:
item.__bases__ = tuple(list(item.__bases__) + [CompareHelper])
except TypeError:
pass
def fast_compare(tree1, tree2):
""" This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes.
"""
geta = ast.AST.__getattribute__
work = [(tree1, tree2)]
pop = work.pop
extend = work.extend
# TypeError in cPython, AttributeError in PyPy
exception = TypeError, AttributeError
zipl = zip_longest
type_ = type
list_ = list
while work:
n1, n2 = pop()
try:
f1 = geta(n1, '_fields')
f2 = geta(n2, '_fields')
except exception:
if type_(n1) is list_:
extend(zipl(n1, n2))
continue
if n1 == n2:
continue
return False
else:
f1 = [x for x in f1 if x != 'ctx']
if f1 != [x for x in f2 if x != 'ctx']:
return False
extend((geta(n1, fname), geta(n2, fname)) for fname in f1)
return True
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright (c) 2015 Patrick Maupin
This module provides data and functions for mapping
AST nodes to symbols and precedences.
"""
import ast
op_data = """
GeneratorExp 1
Assign 1
AnnAssign 1
AugAssign 0
Expr 0
Yield 1
YieldFrom 0
If 1
For 0
AsyncFor 0
While 0
Return 1
Slice 1
Subscript 0
Index 1
ExtSlice 1
comprehension_target 1
Tuple 0
FormattedValue 0
Comma 1
NamedExpr 1
Assert 0
Raise 0
call_one_arg 1
Lambda 1
IfExp 0
comprehension 1
Or or 1
And and 1
Not not 1
Eq == 1
Gt > 0
GtE >= 0
In in 0
Is is 0
NotEq != 0
Lt < 0
LtE <= 0
NotIn not in 0
IsNot is not 0
BitOr | 1
BitXor ^ 1
BitAnd & 1
LShift << 1
RShift >> 0
Add + 1
Sub - 0
Mult * 1
Div / 0
Mod % 0
FloorDiv // 0
MatMult @ 0
PowRHS 1
Invert ~ 1
UAdd + 0
USub - 0
Pow ** 1
Await 1
Num 1
Constant 1
"""
op_data = [x.split() for x in op_data.splitlines()]
op_data = [[x[0], ' '.join(x[1:-1]), int(x[-1])] for x in op_data if x]
for index in range(1, len(op_data)):
op_data[index][2] *= 2
op_data[index][2] += op_data[index - 1][2]
precedence_data = dict((getattr(ast, x, None), z) for x, y, z in op_data)
symbol_data = dict((getattr(ast, x, None), y) for x, y, z in op_data)
def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type):
"""Given an AST node object, returns a string containing the symbol.
"""
return fmt % symbol_data[type(obj)]
def get_op_precedence(obj, precedence_data=precedence_data, type=type):
"""Given an AST node object, returns the precedence.
"""
return precedence_data[type(obj)]
class Precedence(object):
vars().update((x, z) for x, y, z in op_data)
highest = max(z for x, y, z in op_data) + 2
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright (c) 2015 Patrick Maupin
"""
import sys
import os
import ast
import shutil
import logging
from astor.code_gen import to_source
from astor.file_util import code_to_ast
from astor.node_util import (allow_ast_comparison, dump_tree,
strip_tree, fast_compare)
dsttree = 'tmp_rtrip'
# TODO: Remove this workaround once we remove version 2 support
def out_prep(s, pre_encoded=(sys.version_info[0] == 2)):
return s if pre_encoded else s.encode('utf-8')
def convert(srctree, dsttree=dsttree, readonly=False, dumpall=False,
ignore_exceptions=False, fullcomp=False):
"""Walk the srctree, and convert/copy all python files
into the dsttree
"""
if fullcomp:
allow_ast_comparison()
parse_file = code_to_ast.parse_file
find_py_files = code_to_ast.find_py_files
srctree = os.path.normpath(srctree)
if not readonly:
dsttree = os.path.normpath(dsttree)
logging.info('')
logging.info('Trashing ' + dsttree)
shutil.rmtree(dsttree, True)
unknown_src_nodes = set()
unknown_dst_nodes = set()
badfiles = set()
broken = []
oldpath = None
allfiles = find_py_files(srctree, None if readonly else dsttree)
for srcpath, fname in allfiles:
# Create destination directory
if not readonly and srcpath != oldpath:
oldpath = srcpath
if srcpath >= srctree:
dstpath = srcpath.replace(srctree, dsttree, 1)
if not dstpath.startswith(dsttree):
raise ValueError("%s not a subdirectory of %s" %
(dstpath, dsttree))
else:
assert srctree.startswith(srcpath)
dstpath = dsttree
os.makedirs(dstpath)
srcfname = os.path.join(srcpath, fname)
logging.info('Converting %s' % srcfname)
try:
srcast = parse_file(srcfname)
except SyntaxError:
badfiles.add(srcfname)
continue
try:
dsttxt = to_source(srcast)
except Exception:
if not ignore_exceptions:
raise
dsttxt = ''
if not readonly:
dstfname = os.path.join(dstpath, fname)
try:
with open(dstfname, 'wb') as f:
f.write(out_prep(dsttxt))
except UnicodeEncodeError:
badfiles.add(dstfname)
# As a sanity check, make sure that ASTs themselves
# round-trip OK
try:
dstast = ast.parse(dsttxt) if readonly else parse_file(dstfname)
except SyntaxError:
dstast = []
if fullcomp:
unknown_src_nodes.update(strip_tree(srcast))
unknown_dst_nodes.update(strip_tree(dstast))
bad = srcast != dstast
else:
bad = not fast_compare(srcast, dstast)
if dumpall or bad:
srcdump = dump_tree(srcast)
dstdump = dump_tree(dstast)
logging.warning(' calculating dump -- %s' %
('bad' if bad else 'OK'))
if bad:
broken.append(srcfname)
if dumpall or bad:
if not readonly:
try:
with open(dstfname[:-3] + '.srcdmp', 'wb') as f:
f.write(out_prep(srcdump))
except UnicodeEncodeError:
badfiles.add(dstfname[:-3] + '.srcdmp')
try:
with open(dstfname[:-3] + '.dstdmp', 'wb') as f:
f.write(out_prep(dstdump))
except UnicodeEncodeError:
badfiles.add(dstfname[:-3] + '.dstdmp')
elif dumpall:
sys.stdout.write('\n\nAST:\n\n ')
sys.stdout.write(srcdump.replace('\n', '\n '))
sys.stdout.write('\n\nDecompile:\n\n ')
sys.stdout.write(dsttxt.replace('\n', '\n '))
sys.stdout.write('\n\nNew AST:\n\n ')
sys.stdout.write('(same as old)' if dstdump == srcdump
else dstdump.replace('\n', '\n '))
sys.stdout.write('\n')
if badfiles:
logging.warning('\nFiles not processed due to syntax errors:')
for fname in sorted(badfiles):
logging.warning(' %s' % fname)
if broken:
logging.warning('\nFiles failed to round-trip to AST:')
for srcfname in broken:
logging.warning(' %s' % srcfname)
ok_to_strip = 'col_offset _precedence _use_parens lineno _p_op _pp'
ok_to_strip = set(ok_to_strip.split())
bad_nodes = (unknown_dst_nodes | unknown_src_nodes) - ok_to_strip
if bad_nodes:
logging.error('\nERROR -- UNKNOWN NODES STRIPPED: %s' % bad_nodes)
logging.info('\n')
return broken
def usage(msg):
raise SystemExit(textwrap.dedent("""
Error: %s
Usage:
python -m astor.rtrip [readonly] [<source>]
This utility tests round-tripping of Python source to AST
and back to source.
If readonly is specified, then the source will be tested,
but no files will be written.
if the source is specified to be "stdin" (without quotes)
then any source entered at the command line will be compiled
into an AST, converted back to text, and then compiled to
an AST again, and the results will be displayed to stdout.
If neither readonly nor stdin is specified, then rtrip
will create a mirror directory named tmp_rtrip and will
recursively round-trip all the Python source from the source
into the tmp_rtrip dir, after compiling it and then reconstituting
it through code_gen.to_source.
If the source is not specified, the entire Python library will be used.
""") % msg)
if __name__ == '__main__':
import textwrap
args = sys.argv[1:]
readonly = 'readonly' in args
if readonly:
args.remove('readonly')
if not args:
args = [os.path.dirname(textwrap.__file__)]
if len(args) > 1:
usage("Too many arguments")
fname, = args
dumpall = False
if not os.path.exists(fname):
dumpall = fname == 'stdin' or usage("Cannot find directory %s" % fname)
logging.basicConfig(format='%(msg)s', level=logging.INFO)
convert(fname, readonly=readonly or dumpall, dumpall=dumpall)
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright (c) 2015 Patrick Maupin
Pretty-print source -- post-process for the decompiler
The goals of the initial cut of this engine are:
1) Do a passable, if not PEP8, job of line-wrapping.
2) Serve as an example of an interface to the decompiler
for anybody who wants to do a better job. :)
"""
def pretty_source(source):
""" Prettify the source.
"""
return ''.join(split_lines(source))
def split_lines(source, maxline=79):
"""Split inputs according to lines.
If a line is short enough, just yield it.
Otherwise, fix it.
"""
result = []
extend = result.extend
append = result.append
line = []
multiline = False
count = 0
for item in source:
newline = type(item)('\n')
index = item.find(newline)
if index:
line.append(item)
multiline = index > 0
count += len(item)
else:
if line:
if count <= maxline or multiline:
extend(line)
else:
wrap_line(line, maxline, result)
count = 0
multiline = False
line = []
append(item)
return result
def count(group, slen=str.__len__):
return sum([slen(x) for x in group])
def wrap_line(line, maxline=79, result=[], count=count):
""" We have a line that is too long,
so we're going to try to wrap it.
"""
# Extract the indentation
append = result.append
extend = result.extend
indentation = line[0]
lenfirst = len(indentation)
indent = lenfirst - len(indentation.lstrip())
assert indent in (0, lenfirst)
indentation = line.pop(0) if indent else ''
# Get splittable/non-splittable groups
dgroups = list(delimiter_groups(line))
unsplittable = dgroups[::2]
splittable = dgroups[1::2]
# If the largest non-splittable group won't fit
# on a line, try to add parentheses to the line.
if max(count(x) for x in unsplittable) > maxline - indent:
line = add_parens(line, maxline, indent)
dgroups = list(delimiter_groups(line))
unsplittable = dgroups[::2]
splittable = dgroups[1::2]
# Deal with the first (always unsplittable) group, and
# then set up to deal with the remainder in pairs.
first = unsplittable[0]
append(indentation)
extend(first)
if not splittable:
return result
pos = indent + count(first)
indentation += ' '
indent += 4
if indent >= maxline / 2:
maxline = maxline / 2 + indent
for sg, nsg in zip(splittable, unsplittable[1:]):
if sg:
# If we already have stuff on the line and even
# the very first item won't fit, start a new line
if pos > indent and pos + len(sg[0]) > maxline:
append('\n')
append(indentation)
pos = indent
# Dump lines out of the splittable group
# until the entire thing fits
csg = count(sg)
while pos + csg > maxline:
ready, sg = split_group(sg, pos, maxline)
if ready[-1].endswith(' '):
ready[-1] = ready[-1][:-1]
extend(ready)
append('\n')
append(indentation)
pos = indent
csg = count(sg)
# Dump the remainder of the splittable group
if sg:
extend(sg)
pos += csg
# Dump the unsplittable group, optionally
# preceded by a linefeed.
cnsg = count(nsg)
if pos > indent and pos + cnsg > maxline:
append('\n')
append(indentation)
pos = indent
extend(nsg)
pos += cnsg
def split_group(source, pos, maxline):
""" Split a group into two subgroups. The
first will be appended to the current
line, the second will start the new line.
Note that the first group must always
contain at least one item.
The original group may be destroyed.
"""
first = []
source.reverse()
while source:
tok = source.pop()
first.append(tok)
pos += len(tok)
if source:
tok = source[-1]
allowed = (maxline + 1) if tok.endswith(' ') else (maxline - 4)
if pos + len(tok) > allowed:
break
source.reverse()
return first, source
begin_delim = set('([{')
end_delim = set(')]}')
end_delim.add('):')
def delimiter_groups(line, begin_delim=begin_delim,
end_delim=end_delim):
"""Split a line into alternating groups.
The first group cannot have a line feed inserted,
the next one can, etc.
"""
text = []
line = iter(line)
while True:
# First build and yield an unsplittable group
for item in line:
text.append(item)
if item in begin_delim:
break
if not text:
break
yield text
# Now build and yield a splittable group
level = 0
text = []
for item in line:
if item in begin_delim:
level += 1
elif item in end_delim:
level -= 1
if level < 0:
yield text
text = [item]
break
text.append(item)
else:
assert not text, text
break
statements = set(['del ', 'return', 'yield ', 'if ', 'while '])
def add_parens(line, maxline, indent, statements=statements, count=count):
"""Attempt to add parentheses around the line
in order to make it splittable.
"""
if line[0] in statements:
index = 1
if not line[0].endswith(' '):
index = 2
assert line[1] == ' '
line.insert(index, '(')
if line[-1] == ':':
line.insert(-1, ')')
else:
line.append(')')
# That was the easy stuff. Now for assignments.
groups = list(get_assign_groups(line))
if len(groups) == 1:
# So sad, too bad
return line
counts = list(count(x) for x in groups)
didwrap = False
# If the LHS is large, wrap it first
if sum(counts[:-1]) >= maxline - indent - 4:
for group in groups[:-1]:
didwrap = False # Only want to know about last group
if len(group) > 1:
group.insert(0, '(')
group.insert(-1, ')')
didwrap = True
# Might not need to wrap the RHS if wrapped the LHS
if not didwrap or counts[-1] > maxline - indent - 10:
groups[-1].insert(0, '(')
groups[-1].append(')')
return [item for group in groups for item in group]
# Assignment operators
ops = list('|^&+-*/%@~') + '<< >> // **'.split() + ['']
ops = set(' %s= ' % x for x in ops)
def get_assign_groups(line, ops=ops):
""" Split a line into groups by assignment (including
augmented assignment)
"""
group = []
for item in line:
group.append(item)
if item in ops:
yield group
group = []
yield group
# -*- coding: utf-8 -*-
"""
Part of the astor library for Python AST manipulation.
License: 3-clause BSD
Copyright (c) 2015 Patrick Maupin
Pretty-print strings for the decompiler
We either return the repr() of the string,
or try to format it as a triple-quoted string.
This is a lot harder than you would think.
This has lots of Python 2 / Python 3 ugliness.
"""
import re
try:
special_unicode = unicode
except NameError:
class special_unicode(object):
pass
try:
basestring = basestring
except NameError:
basestring = str
def _properly_indented(s, line_indent):
mylist = s.split('\n')[1:]
mylist = [x.rstrip() for x in mylist]
mylist = [x for x in mylist if x]
if not s:
return False
counts = [(len(x) - len(x.lstrip())) for x in mylist]
return counts and min(counts) >= line_indent
mysplit = re.compile(r'(\\|\"\"\"|\"$)').split
replacements = {'\\': '\\\\', '"""': '""\\"', '"': '\\"'}
def _prep_triple_quotes(s, mysplit=mysplit, replacements=replacements):
""" Split the string up and force-feed some replacements
to make sure it will round-trip OK
"""
s = mysplit(s)
s[1::2] = (replacements[x] for x in s[1::2])
return ''.join(s)
def string_triplequote_repr(s):
"""Return string's python representation in triple quotes.
"""
return '"""%s"""' % _prep_triple_quotes(s)
def pretty_string(s, embedded, current_line, uni_lit=False,
min_trip_str=20, max_line=100):
"""There are a lot of reasons why we might not want to or
be able to return a triple-quoted string. We can always
punt back to the default normal string.
"""
default = repr(s)
# Punt on abnormal strings
if (isinstance(s, special_unicode) or not isinstance(s, basestring)):
return default
if uni_lit and isinstance(s, bytes):
return 'b' + default
len_s = len(default)
if current_line.strip():
len_current = len(current_line)
second_line_start = s.find('\n') + 1
if embedded > 1 and not second_line_start:
return default
if len_s < min_trip_str:
return default
line_indent = len_current - len(current_line.lstrip())
# Could be on a line by itself...
if embedded and not second_line_start:
return default
total_len = len_current + len_s
if total_len < max_line and not _properly_indented(s, line_indent):
return default
fancy = string_triplequote_repr(s)
# Sometimes this doesn't work. One reason is that
# the AST has no understanding of whether \r\n was
# entered that way in the string or was a cr/lf in the
# file. So we punt just so we can round-trip properly.
try:
if eval(fancy) == s and '\r' not in fancy:
return fancy
except Exception:
pass
return default
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment