Compare commits

..

135 Commits

Author SHA1 Message Date
rocky
c91b5e1164 Need additional try vs try/else checks 2018-03-07 07:37:13 -05:00
rocky
f8fd474b55 Merge branch 'master' into python-2.4 2018-03-07 07:36:41 -05:00
rocky
30756c52b2 Add another batch test 2018-03-07 07:24:07 -05:00
rocky
74e280171b Get ready for release 3.0.1 2018-03-07 07:16:40 -05:00
rocky
df0207eb90 For batch testing 2018-03-07 06:12:24 -05:00
rocky
07a8ae9541 Go over 2.6.9 runtests.sh 2018-03-06 23:55:06 -05:00
rocky
5d6872bcd1 test_pyenvlib.py return number of failed now 2018-03-06 19:13:03 -05:00
rocky
c03cdf1a49 Last 2.6 while1 bug...
before all of 2.6.9 stdlib parses without error.
2018-03-06 18:52:27 -05:00
rocky
01ad91b519 Another 2.6 try parse bug 2018-03-06 18:19:01 -05:00
rocky
ccd42077c1 Better 2.6 tryifelse detection 2018-03-06 17:23:08 -05:00
rocky
ca3f822c81 More 2.6 while-loop control flow parsing 2018-03-06 13:16:22 -05:00
rocky
bc5f43ab05 Merge branch 'master' into python-2.4 2018-03-06 09:55:15 -05:00
rocky
1896c40202 Type comp_ifnot -> comp_if_not...
By the way, the sense of comp_if and list_if is reversed.
Will fix later...
2018-03-06 09:53:55 -05:00
rocky
8278c72a6f Python 2.6 while1 if/and handling 2018-03-06 09:39:13 -05:00
rocky
3b0a5aab16 2.6- CONTINUE/JUMP_BACK confusion workaroud 2018-03-06 00:29:34 -05:00
rocky
a74890d388 Administrivia...
- Add script to run test_pyenvlib.py on everything
- Bump 3.6 version 3.6.4
2018-03-05 23:27:11 -05:00
rocky
5d24367ef6 Small changes...
pysource.py: Bug fix for relative imports.

scanner2.py: Remove a debug expression
2018-03-05 21:53:49 -05:00
rocky
1da2118e13 Merge branch 'master' into python-2.4 2018-03-05 12:26:45 -05:00
rocky
cad1325a90 Python 2.2 code anomoly?
Python 2.2 may generate PRINT_ITEM_CONT in some places for PRINT_ITEM
2018-03-05 12:25:31 -05:00
rocky
61534ceed5 Need to back off set_comp change a little...
There was set_comp already. So what had been setcomp_func is now
merely set_comp_func rather than set_comp. Small improvement but
in the right direction, still
2018-03-05 11:41:21 -05:00
rocky
9f66694056 dictcomp_func -> dict_comp_func...
to match AST better. Also adds a correction in last commit,
including set_comp -> set_comp_expr where apprpriate

Note: can't use dict_comp as that was already used.
But dict_comp_func is matches AST better than dictcomp_func
2018-03-05 11:12:15 -05:00
rocky
2bdfd76635 setcomp_func -> set_comp ...
to match AST name more closely
2018-03-05 10:20:14 -05:00
rocky
01f2f6578b Dictcomp with if for 2.7...
extend grammar in last commit to 2.7 which also has dictionary comprehensions
2018-03-05 08:37:09 -05:00
rocky
67e8f5d1a7 Merge branch 'master' into python-2.4 2018-03-05 07:55:17 -05:00
rocky
02b1554da3 grammar and semantics for dict comp with "if"
Fixes #162
2018-03-05 07:52:02 -05:00
rocky
fac5d31f34 Adjust that 2.2-2.6 "while" may not have COME_FROM 2018-03-05 00:21:54 -05:00
rocky
d42858cae4 additional while1 grammar rules for 2.3-2.6 2018-03-05 00:03:33 -05:00
rocky
2a76013ed5 Merge branch 'master' into python-2.4 2018-03-04 21:46:46 -05:00
rocky
9e815d8d79 2.6 and before COME_FROM handling...
also, add in some of the test bytecode from the python-2.4 branch
2018-03-04 21:42:59 -05:00
rocky
def9e1676b look for "closure" node from the end...
Fix previous commit. Looking from the beginning fails because there are
a variable number of default values. From the end though seems fixed.
2018-03-04 19:28:51 -05:00
rocky
35fcb1edf1 Picking out 3.3 function default values 2018-03-04 18:40:08 -05:00
rocky
ffbce9cb77 3.6 class signature problems...
This time getting the class name in when a "load_closure" is added.
2018-03-04 17:25:42 -05:00
rocky
dc1971f559 Prevent 3.6 call_kw deriving itself..
Was causing some calls to be parsed incorrectly
2018-03-04 16:30:22 -05:00
rocky
cef61904c7 Tweak HOW-TO-REPORT... 2018-03-04 09:49:22 -05:00
rocky
778f92b6f4 Fix a 3.6 CALL_FUNCTION_EX_KW problem..
and remove 3.6 customization from pysource.
2018-03-04 09:18:57 -05:00
rocky
a8260edded 3.6 function/class prototype fixes..
Had got the order backwards in: class Foo(a=B.c)
String defaults in default parameter tuples need to be quoted
2018-03-03 09:12:02 -05:00
rocky
c662cb1df2 Bump python versions 2018-03-03 07:36:56 -05:00
rocky
681bbd616b Merge branch 'master' into python-2.4 2018-03-02 11:14:01 -05:00
rocky
e809ade6e1 Licence is GPL3 2018-03-02 11:13:00 -05:00
rocky
d080b4402d Get ready for release 3.0.0 2018-03-02 10:30:11 -05:00
rocky
46390a161e Merge branch 'master' into python-2.4 2018-03-02 10:07:20 -05:00
rocky
7200d298a5 Back off unconditional_true test for now - Sigh 2018-03-02 10:06:38 -05:00
rocky
28d0ec7a2a Merge branch 'master' into python-2.4 2018-03-02 08:06:53 -05:00
rocky
bb13988126 Instruction fixup broken 3.x make_func...
for handling default values
2018-03-02 08:03:51 -05:00
rocky
8d503682b3 Use get_inst and self.insts more..
needed more in 3.6 to handle EXTENDED_ARGS before JUMP_xxx
2018-03-02 07:15:23 -05:00
rocky
26e1df835c Better "continue" detection for 2.7 2018-03-01 23:34:26 -05:00
rocky
6807015526 Better CONTINUE detection on 3.x
Helps when line numbers have been stripped say in optimization
2018-03-01 22:47:36 -05:00
rocky
99d9beac76 Code generation changes between 3.4.2 and 3.4.4 2018-03-01 21:23:44 -05:00
rocky
452d17a6c3 3.4 while1 bug fix 2018-03-01 18:56:08 -05:00
rocky
8a842c57d3 Omit empty parens in 2.4 2018-03-01 18:17:11 -05:00
rocky
8d1c454376 small test tweak..
Allow it to run not under pytest
2018-03-01 17:23:58 -05:00
rocky
fb333f1505 Merge branch 'master' into python-2.4 2018-03-01 17:22:45 -05:00
rocky
2edc757b6f more deparse_code -> code_deparse API additions 2018-03-01 16:55:45 -05:00
rocky
ef076c065b Imports yet again 2018-03-01 08:45:31 -05:00
rocky
a0e3759f76 Towards better 3.6 parameter handling
3.6 is still a mess though.
2018-03-01 08:09:53 -05:00
rocky
f7439f506a Fix 3.6 MAKE_FUNCTION for kw params...
and remove duplicated attributies in pattr of MAKE_FUNCITON token.
2018-03-01 07:14:46 -05:00
rocky
257c3ca454 Exclude early versions of Python in last change 2018-03-01 00:00:23 -05:00
rocky
e23315b2e6 Fallout from more precise token attributes 2018-02-28 23:35:52 -05:00
rocky
413df51dfa Token.format(), shows CONST values better...
We were not showing the proper value for None, or False.

Start a unit test for Token().

I think this cleans the Token class up a little more.

More work is needed for MAKE_FUNCTION...

Note: Some debug stuff is commented out in make_funciton.py for upcoming work.
2018-02-28 22:05:12 -05:00
rocky
1fe432585e Keep pre-3.6 listcomp code patterns in 3.6 2018-02-28 16:22:33 -05:00
rocky
b128e4fde6 Fix 3.6+ nested list comprehensions
Modified "load_closure" rule and
changed semantic actions since LOAD_CLOSUREs are stored
inside a MAKE_TUPLE.

FIXME: Not sure if we have additional "if" clauses correct. Test and correct
2018-02-28 11:13:52 -05:00
rocky
7eb19a8617 revise API for aligner 2018-02-27 22:02:51 -05:00
rocky
ab257dc7ce Merge branch 'master' into python-2.4 2018-02-27 17:49:22 -05:00
rocky
b6d96929cb Start simplifying higher-level API 2018-02-27 17:48:26 -05:00
rocky
68692abaf6 Start changing API to make version optional...
and use debug option dictionary
2018-02-27 11:42:29 -05:00
rocky
55a10d9e20 Remove trepan debug 2018-02-27 11:16:27 -05:00
rocky
e9d1b86a5b Revise comprehension walking in 3.x...
less rigidly and with less magic and more verbiage as to what's going on
2018-02-27 11:13:55 -05:00
rocky
e3d8751338 Sync with master + lint 2018-02-27 10:41:46 -05:00
rocky
a1532bbfea Merge branch 'master' into python-2.4 2018-02-27 10:40:40 -05:00
rocky
afb90dd12e 3.6+ try/finally bugs
Another day another 3.6 bug fix attempted
2018-02-27 10:37:18 -05:00
rocky
c43c9a19aa Move to GPL3 license 2018-02-27 06:40:36 -05:00
rocky
d3f5ec6f30 Fix Bug in recalculating prev_op ...
in removing EXTENDED_ARG
2018-02-27 06:15:37 -05:00
rocky
5c2d0484e5 3.6 MAKE_FUNCTION workarounds
Still wrong, but points to diretions for improvements
2018-02-26 09:10:00 -05:00
rocky
31de0d2af5 3.6 keyword args bugs in CALL_FUNCTION_KW 2018-02-26 07:44:37 -05:00
rocky
195075ac01 3.6 while-if-while bug 2018-02-26 01:27:00 -05:00
rocky
d09e820d89 Use get_inst() to paper around EXTENDED_ARG 2018-02-25 23:02:23 -05:00
rocky
b584a0f6b0 More EXTENDED_ARGS woes on 3.6+ 2018-02-25 22:42:18 -05:00
rocky
df7cfa2d20 Add another 3.6 test for EXTENDED_ARGS 2018-02-25 21:46:42 -05:00
R. Bernstein
7f3956c996 Merge pull request #161 from rocky/extended_args
Extended args handling to address 3.6+ problems
2018-02-25 21:40:20 -05:00
rocky
98394d18bb pytest adjust: 2.7 should have be unchanged 2018-02-25 21:31:30 -05:00
rocky
493835b8cd bild_lines API changed. Adjust test for change 2018-02-25 21:27:09 -05:00
rocky
f6aa775d58 EXTENDED_ARG in 3.6 fixes
3.6 uses EXTENDED_ARG more often appearing as the targets of jump
instructions at the beginning of line statements. All of this wreaks
havoc in the current way that our instruction processing works
2018-02-25 21:06:57 -05:00
rocky
2f6a85d538 Merge branch 'master' into extended_args 2018-02-25 19:19:32 -05:00
rocky
8c0f256b78 Sync python2 and python3 scanner/injest code more 2018-02-25 09:42:04 -05:00
rocky
6e2ca8f53d Add another guard on a test 2018-02-25 08:59:12 -05:00
rocky
c1ed6dea62 Merge branch 'master' into extended_args 2018-02-25 08:57:11 -05:00
rocky
ab1c2ec5bb Merge branch 'master' of github.com:rocky/python-uncompyle6 2018-02-25 08:53:15 -05:00
rocky
e3d0b1b9ce move more toward instruction-based ingest...
rather than bytecode-based. This cleans up code
up a little bit better by using more general instructions
2018-02-25 08:51:50 -05:00
rocky
aaf83ea35d WIP: Handle EXTENDED_ARGS better 2018-02-25 08:22:07 -05:00
R. Bernstein
cb24973147 Merge pull request #160 from wangym5106/master
Keep global statements in fixed order
2018-02-24 10:34:50 -05:00
Yiming Wang
3545c7dc6f Keep global statements in fixed order 2018-02-24 22:22:50 +08:00
rocky
8463221527 yield before 2.4 may need "None" 2018-02-22 22:26:56 -05:00
rocky
128963d2e9 yield before 2.4 may need "None" 2018-02-22 22:23:57 -05:00
rocky
1cb9fc8b43 I hate conflicted merges 2018-02-22 21:46:05 -05:00
rocky
6b6a085b08 Go over runtest.sh exceptions 2018-02-22 20:27:56 -05:00
rocky
b9147b7872 Distingish 2.4-2.6 try from try/else 2018-02-22 20:24:21 -05:00
rocky
5496271000 Merge branch 'master' into python-2.4 2018-02-22 20:15:45 -05:00
rocky
30fbdff29c More 2.4-2.6 try vs try/else determination 2018-02-22 20:14:52 -05:00
rocky
26e65e0d90 2.4 test_typespy was fixed by commit from a while ago 2018-02-22 19:30:51 -05:00
rocky
16b5df4ba4 2.4 test_types was fixed by prior commit 2018-02-22 19:16:41 -05:00
rocky
fee6114d74 Merge branch 'master' into python-2.4 2018-02-22 19:15:24 -05:00
rocky
a2b6ebc669 grammar tree -> parse tree 2018-02-22 14:34:42 -05:00
rocky
09efb24a3e Start distinguishing AST from grammar tree 2018-02-22 11:17:09 -05:00
rocky
a1b2a91d88 == -> is 2018-02-21 18:09:24 -05:00
rocky
b14655dd43 == -> is 2018-02-21 18:08:27 -05:00
rocky
3de2890050 Merge branch 'master' into python-2.4 2018-02-21 17:43:37 -05:00
rocky
859ce2206d version=None in deparse_code() uses sys.version...
(the current interpreter version) as the version to decompile.

Fixes #159.
2018-02-21 17:40:43 -05:00
rocky
90ae3e42f6 Merge branch 'python-2.4' of github.com:rocky/python-uncompyle6 into python-2.4 2018-02-21 07:54:17 -05:00
rocky
ee89b5decd Fix 2.4/2.5 try/else detection...
in a hacky way
2018-02-21 04:17:08 -05:00
rocky
158a1886fe Fix 2.4/2.5 try/else detection bug...
in a hacky way
2018-02-21 04:13:57 -05:00
rocky
d2285f0d61 remove a 2.7 runtest.sh exception 2018-02-21 02:54:40 -05:00
rocky
2e44ac25a1 Merge branch 'master' into python-2.4 2018-02-19 17:07:11 -05:00
rocky
8864034966 Narrow the 2.7 unconditional_true reduction 2018-02-19 17:06:18 -05:00
rocky
deb9903a97 DRY and limit STORE_LOCALS 2018-02-19 08:03:09 -05:00
rocky
f4b7e54313 Refine 2.7 dead code test ..
in a hacky way. Will probalby have to expand this in the future or
better do dead code analysis
2018-02-19 07:06:04 -05:00
rocky
08c7966ef9 2.7 for .. try-else bug 2018-02-18 09:13:22 -05:00
rocky
9d425039a2 Merge branch 'master' into python-2.4 2018-02-17 11:28:45 -05:00
rocky
a5c388c13b Another 2.7 "if" with return fix
This works is in conjunction with the commit before the previous release commit.
2018-02-17 11:11:32 -05:00
rocky
c82095e6ac Get ready for release 2.16.0 2018-02-17 07:30:22 -05:00
rocky
67ad08fd4a Beter 2.7 end_if and COME_FROM determination
Fixes #149

... Add more tests too
2018-02-17 07:16:14 -05:00
rocky
fa4f614295 Wierd comprehension bug seen via new loctraceback 2018-02-15 12:15:49 -05:00
rocky
832f04a486 Merge branch 'master' into python-2.4 2018-02-15 10:47:14 -05:00
rocky
f7f0aa5ea9 Merge branch 'master' of github.com:rocky/python-uncompyle6 2018-02-15 10:42:29 -05:00
rocky
083ae5f3fd Add deparsed_find() used by the trepan debuggers 2018-02-15 10:42:00 -05:00
rocky
657d5ef024 pydisasm fixes 2018-02-15 07:33:51 -05:00
rocky
e92c2503d1 Merge branch 'master' into python-2.4 2018-02-15 07:31:11 -05:00
rocky
a01091a46e Misc pydisasm fixes 2018-02-15 07:30:01 -05:00
rocky
b5a825f4d8 Fix up 3.6+ CALL_FUNCTION_EX 2018-02-12 07:45:20 -05:00
rocky
730b0549d5 Handle 3.6+ FUNCTION_EX a little more generally 2018-02-12 04:26:52 -05:00
rocky
e431e49d77 Isolate Python 3.5 custom parse rules...
are isolated into parse35.py now and removed from parse3.py

This causes some code duplicated from parse3.py into parse3{5,6}.py

We will deal with that later.
2018-02-12 03:59:44 -05:00
rocky
230a38d537 Fix Python 3.5 CALL_FUNCTION_VAR handling 2018-02-12 03:07:03 -05:00
rocky
6d29ed9077 Python 3.5 CALL_FUNCTION_VAR bugs 2018-02-09 16:48:11 -05:00
rocky
bb45be2dc7 Start to handle 3.5+ BUILD_LIST_UNPACK in call ..
to implement multple star arguments
2018-02-09 03:41:13 -05:00
rocky
f7999d2754 Add custom 3.5 handling for f(*a, *b, *c) 2018-02-08 08:42:38 -05:00
rocky
5aeb0424fc Administrivia 2018-02-05 06:37:50 -05:00
120 changed files with 2778 additions and 862 deletions

11
.gitignore vendored
View File

@@ -1,11 +1,15 @@
*.pyo
*.pyc
*.pyo
*_dis
*~
/.cache
/.eggs
/.hypothesis
/.idea
/.pytest_cache
/.python-version
/.tox
/.venv*
/README
/__pkginfo__.pyc
/dist
@@ -14,9 +18,6 @@
/tmp
/uncompyle6.egg-info
/unpyc
ChangeLog
__pycache__
build
/.venv*
/.idea
/.hypothesis
ChangeLog

674
COPYING Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1,4 +1,4 @@
This project has history of over 17 years spanning back to Python 1.5
This project has history of over 18 years spanning back to Python 1.5
There have been a number of people who have worked on this. I am awed
by the amount of work, number of people who have contributed to this,

View File

@@ -57,6 +57,19 @@ disassembler called `pydisasm`.
### Semantic equivalence vs. exact source code
Consider how Python compiles something like "(x*y) + 5". Early on
Python creates an "abstract syntax tree" (AST) for this. And this is
"abstract" in the sense that unimportant, redundant or unnecceary
items have been removed. Here, this means that any notion that you
wrote "x+y" in parenthesis is lost, since in this context they are
unneeded. Also lost is the fact that the multiplication didn't have
spaces around it while the addition did. It should not come as a
surprise then that the bytecode which is derived from the AST also has
no notion of such possible variation. Generally this kind of thing
isn't noticed since the Python community has laid out a very rigid set
of formatting guidelines; and it has largely beaten the community into
compliance.
Almost all versions of Python can perform some sort of code
improvement that can't be undone. In earlier versions of Python it is
rare; in later Python versions, it is more common.
@@ -66,7 +79,7 @@ If the code emitted is semantically equivalent, then this isn't a bug.
For example the code might be
```
```python
if a:
if b:
x = 1
@@ -74,7 +87,7 @@ if a:
and we might produce:
```
```python
if a and b:
x = 1
```
@@ -87,24 +100,35 @@ else:
```
may come out as `elif`.
may come out as `elif` or vice versa.
As mentioned in the README, It is possible that Python changes what
you write to be more efficient. For example, for:
```
```python
if True:
x = 5
```
Python will generate code like:
```
```python
x = 5
```
Even more extreme, if your code is:
```python
if False:
x = 1
y = 2
# ...
```
Python will eliminate the entire "if" statement.
So just because the text isn't the same, does not
necessarily mean there's a bug.

22
LICENSE
View File

@@ -1,22 +0,0 @@
Copyright (c) 2015 by Rocky Bernstein
Copyright (c) 2000 by hartmut Goebel <h.goebel@crazy-compilers.com>
Copyright (c) 1998-2002 John Aycock
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -2,7 +2,7 @@ include README.rst
include ChangeLog
include HISTORY.md
include HOW-TO-REPORT-A-BUG.md
include LICENSE
include COPYING
include Makefile
include requirements.txt
include requirements-dev.txt

64
NEWS
View File

@@ -1,3 +1,51 @@
uncompyle6 3.0.1 2018-02-17
- All Python 2.6.9 standard library files weakly verify
- Many 3.6 fixes. 84% of the first 200 standard library files weakly compile.
One more big push is needed to get the remaining to compile
- Many decompilation fixes for other Python versions
- Add more to the test framework
- And more add tests target previous existing bugs more completely
- sync recent license changes in metadata
uncompyle6 3.0.0 2018-02-17
- deparse_code() and lookalikes from the various semantic actions are
now deprecated. Instead use new API code_deparse() which makes the
version optional and bundles debug options into a dictionary.
- License changed to GPL3.
- Many Python 3.6 fixes, especially around handling EXTENDED_ARGS
Due to the reduction in operand size for JUMP's there are many
more EXTENDED_ARGS instructions which can be the targets
of jumps, and messes up the peephole-like analysis that is
done for control flow since we don't have something better in place.
- Code has been reorganized to be more instruction nametuple based where it
has been more bytecode array based. There was and still is code that had
had magic numbers to advance instructions or to pick out operands.
- Bug fixes in numerous other Python versions
- Instruction display improved
- Keep global statements in fixed order (from wangym5106)
A bit more work is still needed for 3.6 especially in the area of
function calls and definitions.
uncompyle6 2.16.0 2018-02-17
- API additions:
- add fragments.op_at_code_loc() and
- fragments.deparsed_find()_
- Better 2.7 end_if and COME_FROM determination
- Fix up 3.6+ CALL_FUNCTION_EX
- Misc pydisasm fixes
- Weird comprehension bug seen via new loctraceback
- Fix Python 3.5+ CALL_FUNCTION_VAR and BUILD_LIST_UNPACK in call; with this
we can can handle 3.5+ f(a, b, *c, *d, *e) now
uncompyle6 2.15.1 2018-02-05
- More bug fixes and revert an improper bug fix in 2.15.0
uncompyle6 2.15.0 2018-02-05 pycon2018.co
- Bug fixes
@@ -43,7 +91,7 @@ Decompilation bug fixes, mostly 3.6 and pre 2.7
- limit pypy customization to pypy
- Add addr fields in COME_FROMS
- Allow use of full instructions in parser reduction routines
- Reduce grammar in Pythion 3 by specialization more to specific
- Reduce grammar in Python 3 by specialization more to specific
Python versions
- Match Python AST names more closely when possible
@@ -61,7 +109,7 @@ uncompyle6 2.14.0 2017-11-26 johnnybamazing
and remove used grammar rules
- Fix a number of bytecode decompile problems
(many more remain)
- Add stdlib/runtests.sh for even more rigourous testing
- Add stdlib/runtests.sh for even more rigorous testing
uncompyle6 2.13.3 2017-11-13
@@ -85,7 +133,7 @@ Overall: better 3.6 decompiling and some much needed code refactoring and cleanu
added to assist here. Ignoring errors may be okay because the fragment parser often just needs,
well, *fragments*.
- Distinguish RETURN_VALUE from RETURN_END_IF in exception bodies better in 3.6
- bug in 3.x language changes: import queue va import Queue
- bug in 3.x language changes: import queue via import Queue
- reinstate some bytecode tests since decompiling has gotten better
- Revise how to report a bug
@@ -120,8 +168,8 @@ uncompyle6 2.11.4 2017-08-15
* scanner and parser now allow 3-part version string lookups,
e.g. 2.7.1 We allow a float here, but if passed a string like '2.7'. or
* unpin 3.5.1. xdis 3.5.4 has been releasd and fixes the problems we had. Use that.
* some routnes here moved to xdis. Use the xdis version
* unpin 3.5.1. xdis 3.5.4 has been release and fixes the problems we had. Use that.
* some routines here moved to xdis. Use the xdis version
* README.rst: Link typo Name is trepan2 now not trepan
* xdis-forced change adjust for COMPARE_OP "is-not" in
semanatic routines. We need "is not".
@@ -217,9 +265,9 @@ uncompyle6 2.9.8 2016-12-16
- fix bug in --verify option
- DRY (a little) control-flow detection
- fix syntax in tuples with one element
- if AST rule inheritence in Python 2.5
- if AST rule inheritance in Python 2.5
- NAME_MODULE removal for Python <= 2.4
- verifycall fixes for Python <= 2.4
- verify call fixes for Python <= 2.4
- more Python lint
uncompyle6 2.9.7 2016-12-16
@@ -255,7 +303,7 @@ uncompyle6 2.9.6 2016-11-20
in the results.
- better control flow debugging output
- Python 2 and 3 detect structure code is more similar
- Handle Docstrings with embedded tiple quotes (""")
- Handle Docstrings with embedded triple quotes (""")
uncompyle6 2.9.5 2016-11-13

View File

@@ -1,3 +1,17 @@
# Copyright (C) 2018 Rocky Bernstein <rocky@gnu.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""uncompyle6 packaging information"""
# To the extent possible we make this file look more like a
@@ -14,6 +28,7 @@ Copyright (C) 2015-2018 Rocky Bernstein <rb@dustyfeet.com>.
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
@@ -41,8 +56,8 @@ entry_points = {
]}
ftp_url = None
install_requires = ['spark-parser >= 1.8.5, < 1.9.0',
'xdis >= 3.6.9, < 3.7.0']
license = 'MIT'
'xdis >= 3.7.0, < 3.8.0']
license = 'GPL3'
mailing_list = 'python-debugger@googlegroups.com'
modname = 'uncompyle6'
py_modules = None

View File

@@ -45,6 +45,8 @@
$ source admin-tools/setup-python-2.4.sh
$ git merge master
# Add and fix merge conflicts
$ git commit
# Check against older versions

View File

@@ -5,4 +5,4 @@ if [[ $0 == ${BASH_SOURCE[0]} ]] ; then
echo "This script should be *sourced* rather than run directly through bash"
exit 1
fi
export PYVERSIONS='3.5.3 3.6.3 2.6.9 3.3.6 2.7.14 3.4.2'
export PYVERSIONS='3.5.5 3.6.4 2.6.9 3.3.7 2.7.14 3.4.8'

View File

@@ -0,0 +1,28 @@
#!/bin/bash
# Runs test_pyenvlib.test on all versions of Python master.
function finish {
cd $owd
}
# FIXME put some of the below in a common routine
owd=$(pwd)
trap finish EXIT
cd $(dirname ${BASH_SOURCE[0]})
if ! source ./pyenv-newer-versions ; then
exit $?
fi
if ! source ./setup-master.sh ; then
exit $?
fi
cd ../test
for version in $PYVERSIONS; do
if ! pyenv local $version ; then
exit $?
fi
echo "====== Running test_pyenvlib.py on $version ====="
if ! python ./test_pyenvlib.py --weak-verify --max 800 --${version} ; then
exit $?
fi
echo "------ Done test_pyenvlib.py on $version -----"
done

View File

@@ -1,5 +1,5 @@
#!/bin/bash
PYTHON_VERSION=3.6.3
PYTHON_VERSION=3.6.4
# FIXME put some of the below in a common routine
function finish {

View File

@@ -1,5 +1,5 @@
import pytest
from uncompyle6.semantics.fragments import deparse_code as deparse
from uncompyle6.semantics.fragments import code_deparse as deparse, deparsed_find
from uncompyle6 import PYTHON_VERSION, PYTHON3
def map_stmts(x, y):
@@ -31,17 +31,19 @@ def list_comp():
def get_parsed_for_fn(fn):
code = fn.func_code
return deparse(PYTHON_VERSION, code)
return deparse(code, version=PYTHON_VERSION)
def check_expect(expect, parsed, fn_name):
debug = False
i = 2
max_expect = len(expect)
code = get_parsed_for_fn(fn_name)
for name, offset in sorted(parsed.offsets.keys()):
assert i+1 <= max_expect, (
"%s: ran out if items in testing node" % fn_name)
nodeInfo = parsed.offsets[name, offset]
node = nodeInfo.node
nodeInfo2 = deparsed_find((name, offset), parsed, code)
extractInfo = parsed.extract_node_info(node)
assert expect[i] == extractInfo.selectedLine, \

View File

@@ -70,7 +70,7 @@ def test_if_in_for():
elif 3.2 < PYTHON_VERSION <= 3.4:
bytecode = Bytecode(code, scan.opc)
scan.code = array('B', code.co_code)
scan.build_lines_data(code)
scan.lines = scan.build_lines_data(code)
scan.build_prev_op()
scan.insts = list(bytecode)
scan.offset2inst_index = {}

View File

@@ -66,9 +66,9 @@ def test_grammar():
expect_dup_rhs = frozenset([('COME_FROM',), ('CONTINUE',), ('JUMP_ABSOLUTE',),
('LOAD_CONST',),
('JUMP_BACK',), ('JUMP_FORWARD',)])
# reduced_dup_rhs = {k: dup_rhs[k] for k in dup_rhs if k not in expect_dup_rhs}
# for k in reduced_dup_rhs:
# print(k, reduced_dup_rhs[k])
reduced_dup_rhs = dict((k, dup_rhs[k]) for k in dup_rhs if k not in expect_dup_rhs)
for k in reduced_dup_rhs:
print(k, reduced_dup_rhs[k])
# assert not reduced_dup_rhs, reduced_dup_rhs
s = get_scanner(PYTHON_VERSION, IS_PYPY)

23
pytest/test_token.py Normal file
View File

@@ -0,0 +1,23 @@
from uncompyle6.scanners.tok import Token
def test_token():
# Test token formatting of: LOAD_CONST None
t = Token('LOAD_CONST', offset=0, attr=None, pattr=None, has_arg=True)
expect = ' 0 LOAD_CONST None'
# print(t.format())
assert t
assert t.format() == expect
# Make sure equality testing of tokens ignores offset
t2 = Token('LOAD_CONST', offset=2, attr=None, pattr=None, has_arg=True)
assert t2 == t
# Make sure formatting of: LOAD_CONST False. We assume False is the 0th index
# of co_consts.
t = Token('LOAD_CONST', offset=1, attr=False, pattr=False, has_arg=True)
expect = ' 1 LOAD_CONST 0 False'
assert t.format() == expect
if __name__ == '__main__':
test_token()

View File

@@ -8,5 +8,5 @@
9 STORE_NAME 2 'b'
12 JUMP_FORWARD 0 'to 15'
15_0 COME_FROM 12 '12'
15 LOAD_CONST 0 ''
15 LOAD_CONST 0 None
18 RETURN_VALUE

View File

@@ -11,5 +11,5 @@
6 15 LOAD_CONST 1 2
18 STORE_NAME 2 'd'
21_0 COME_FROM 12 '12'
21 LOAD_CONST 2 ''
21 LOAD_CONST 2 None
24 RETURN_VALUE

View File

@@ -53,6 +53,7 @@ check-3.4: check-bytecode check-3.4-ok check-2.7-ok
#: Run working tests from Python 3.5
check-3.5: check-bytecode
$(PYTHON) test_pythonlib.py --bytecode-3.5 --weak-verify $(COMPILE)
$(PYTHON) test_pythonlib.py --bytecode-3.5-run --verify-run
#: Run working tests from Python 3.6
check-3.6: check-bytecode

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

0
test/bytecode_3.6_run/.gitignore vendored Normal file
View File

13
test/run-and-email.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/bash
EMAIL=${EMAIL:-rb@dustyfeet.com}
for VERSION in 2.7.14 2.6.9 ; do
LOGFILE=/tmp/pyenlib-$VERSION-$$.log
python ./test_pyenvlib.py --max 800 --weak-verify --$VERSION >$LOGFILE 2>&1
rc=$?
if ((rc == 0)); then
tail -v $LOGFILE | mail -s \""$VERSION ok"\" rocky@localhost
else
tail -v $LOGFILE | mail -s \""$VERSION not ok"\" rocky@localhost
tail -v $LOGFILE | mail -s \""$VERSION not ok"\" rb@dustyfeet.com
fi
done

View File

@@ -0,0 +1,7 @@
# From 2.4 test_array.py
# In Python 2.4 and earlier "yield" is not valid and instead
# we must use "yield None". Bug was not adding "None"
def yield_bug():
yield None
return

View File

@@ -1,18 +1,17 @@
# From Python 2.4. test_cgi.py
# Bug was in putting try block inside the ifelse statement.
# Note: this is a self testing program - will assert on failure.
def do_test(method):
if method == "GET":
rc = 0
elif method == "POST":
rc = 1
else:
raise ValueError, "unknown method: %s" % method
# Bug found in 2.4 test_math.py
# Bug was turning last try/except/else into try/else
import math
def test_exceptions():
try:
rc = 2
except ZeroDivisionError:
rc = 3
return rc
x = math.exp(-1000000000)
except:
raise RuntimeError
assert 2 == do_test("GET")
try:
x = math.sqrt(-1.0)
except ValueError:
return x
else:
raise RuntimeError
test_exceptions()

View File

@@ -0,0 +1,19 @@
# From 2.4 test_sax.py
# Bug was distinguishing try from try/else
def verify_empty_attrs():
gvqk = 3
try:
gvk = 1/0
except ZeroDivisionError:
gvk = 1
try:
gvqk = 0
except KeyError:
gvqk = 1
# If try/else was used above the return will be 4
return gvk + gvqk
assert 1 == verify_empty_attrs()

View File

@@ -0,0 +1,13 @@
# From 2.3 Queue.py
# Bug was adding COME_FROM from while
# confusing the else
def put(item, block=True, timeout=None):
if block:
if timeout:
while True:
if item:
block = 1
else:
block = 5
elif item:
block = False

View File

@@ -0,0 +1,19 @@
# From 2.6.9 ftplib.py
# Bug was handling if with "and' inside while1
def getmultiline(line):
if line[3]:
while 1:
if line[2] and line[5]:
break
return
# From 2.6.9 refactor.py
def _detect_future_features(tp):
while True:
if tp == 6:
while tp == 7:
if tp != 11:
break
else:
break
return

View File

@@ -21,5 +21,33 @@ def call(*args):
except KeyError:
return 2
except TypeError:
# Unhashable argument
return 3
# From 2.6.9 pdb.py
# Here we have a "try/except" inside a "try/except/else and we can't
# distinguish which COME_FROM comes from which "try".
def do_jump(self, arg):
try:
arg(1)
except ValueError:
arg(2)
else:
try:
arg(3)
except ValueError:
arg(4)
# From 2.6.9 smtpd.py
# Bug was that the for can cause multiple COME_FROMs at the
# of the try block
def _deliver(self, s, mailfrom, rcpttos):
try:
mailfrom(1)
except RuntimeError:
mailfrom(2)
except IndexError:
for r in s:
mailfrom()
return

View File

@@ -0,0 +1,13 @@
# From 2.3.7 dis.py. Bug ranged from 2.2 to 2.6.
# bug was in "while". uncompyle6 doesn't
# add in a COME_FROM after the while. Maybe it should?
def distb(tb=None):
"""Disassemble a traceback (default: last traceback)."""
if tb is None:
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError, "no last traceback to disassemble"
while tb.tb_next: tb = tb.tb_next
disassemble(tb.tb_frame.f_code, tb.tb_lasti)

View File

@@ -0,0 +1,9 @@
# Bug found in 2.7 test_itertools.py
# Bug was erroneously using reduction to unconditional_true
# A proper fix would be to use unconditional_true only when we
# can determine there is or was dead code.
from itertools import izip_longest
for args in [['abc', range(6)]]:
target = [tuple([arg[i] if i < len(arg) else None for arg in args])
for i in range(max(map(len, args)))]
assert list(izip_longest(*args)) == target

View File

@@ -0,0 +1,20 @@
# Bug found in 2.7 test_itertools.py
def test_iziplongest(self):
# Having a for loop seems important
for args in ['abc']:
self.assertEqual(1, 2)
pass # Having this seems important
# The bug was the except jumping back
# to the beginning of this for loop
for stmt in [
"izip_longest('abc', fv=1)",
]:
try:
eval(stmt)
except TypeError:
pass
else:
self.fail()

View File

@@ -0,0 +1,12 @@
# From 2.7 test_itertools.py
# Bug was in 2.7 decompiling like the commented out
# code below
from itertools import izip_longest
for args in [
['abc', range(6)],
]:
# target = [tuple([ arg[i] if 1 else None for arg in args if i < len(arg) ])
# for i in range(max(map(len, args)))]
target = [tuple([arg[i] if i < len(arg) else None for arg in args])
for i in range(max(map(len, args)))]
assert list(izip_longest(*args)) == target

View File

@@ -4,3 +4,14 @@ def __new__(cls, encode, decode, streamreader=None, streamwriter=None,
incrementalencoder=None, incrementaldecoder=None, name=None,
*, _is_text_encoding=None):
return
# From 3.3 _pyio.py. A closure is created here.
# This changes how the default params are found
class StringIO(object):
def __init__(self, initial_value="", newline="\n"):
super(StringIO, self).__init__()
# No closure created here
class StringIO2(object):
def __init__(self, initial_value="", newline="\n"):
return 5

View File

@@ -0,0 +1,17 @@
# From 3.4.4 mailcap.py
# Bug was needing a grammar rule to add POP_BLOCK before the end of the while1.
# 3.3 apparently doesn't add this.
def readmailcapfile(line):
while 1:
if not line: break
if line[0] == '#' or line.strip() == '':
continue
if not line:
continue
for j in range(3):
line[j] = line[j].strip()
if '/' in line:
line['/'].append('a')
else:
line['/'] = 'a'
return

View File

@@ -1,9 +1,16 @@
# Bug in Python 3.5 is getting the two star'd arguments right.
def sum(a,b,c,d):
# Bug in 3.5 is detecting when there is more than
# one * in a call. There is a "BUILD_UNPACK_LIST" instruction used
# to unpack star arguments
def sum(a, b, c, d):
return a + b + c + d
args=(1,2)
args, a, b, c = (1, 2), 1, 2, 3
sum(*args, *args)
sum(*args, *args, *args)
sum(a, *args, *args)
sum(a, b, *args)
sum(a, b, *args, *args)
# FIXME: this is handled incorrectly
# (*c,) = (3,4)

View File

@@ -1,5 +1,30 @@
# Python 3.6's changes for calling functions.
# See https://github.com/rocky/python-uncompyle6/issues/58
# CALL_FUNCTION_EX takes 2 to 3 arguments on the stack: the function, the tuple of positional arguments,
# and optionally the dict of keyword arguments if bit 0 of oparg is 1.
a(*[])
# CALL_FUNCTION_EX takes 2 to 3 arguments on the stack:
# * the function,
# * the tuple of positional arguments, and optionally
# * the dict of keyword arguments if bit 0 of oparg is 1.
from foo import f, dialect, args, kwds, reader
f(*[])
# From Python 3.6 csv.py
# (f, dialect) are positional arg tuples, *args, is by itself, i.e.
# no tuple.
x = reader(f, dialect, *args, **kwds)
# From 3.6 functools.py
# Below there is a load_closure instruction added
def cmp_to_key(mycmp):
class K(object):
def __ge__():
return mycmp()
return
# In this situation though, there is no load_closure
def cmp2_to_key(mycmp):
class K2(object):
def __ge__():
return 5
return

View File

@@ -7,3 +7,9 @@ def foo3(bar, baz=1, qux=2):
return 3
def foo4(bar, baz, qux=1, quux=2):
return 4
# From 3.6 compileall.
# Bug was in omitting default which when used in an "if"
# are treated as False would be
def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0):
return

View File

@@ -0,0 +1,20 @@
# From 3.6 _pyio.py
# Bug was in "return" not having "COME_FROM"
# and in 1st try/finally no END_FINALLY (which really
# hooks into the control-flow analysis).
# The 2nd try/finally has an END_FINALLY although still
# no "COME_FROM".
def getvalue(self):
try:
return 3
finally:
return 1
def getvalue1(self):
try:
return 4
finally:
pass
return 2

View File

@@ -0,0 +1,4 @@
# From 3.6 _pydecimal. Bug was handling
# keyword args in the return (CALL_FUNCTION_KW_2)
def to_eng_string(self, context=None):
return self.__str__(eng=True, context=context)

View File

@@ -0,0 +1,17 @@
# From 3.6 base64.py. Bug was handling *, and keyword args
def a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v'):
return
# From 3.6 configparser.py. Same problem as above.
_UNSET = object()
def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
return
# From 3.6 compileall.py Bug is making default values are in quotes
def compile_command(source, filename="<input>", symbol="single"):
return
# From 3.6 _pyio.py. Bug was in getting order of metaclass=abc.ABCMeta right
import abc
class IOBase(metaclass=abc.ABCMeta):
pass

View File

@@ -0,0 +1,24 @@
# From 3.6 _sitebuiltins.py
# Bug was in handling double nested kinds of things like:
# for a in b for c in d
# This required grammar modification and
# and semantic action changes. LOAD_CLOSUREs are stored
# inside a MAKE_TUPLE.
# FIXME: test and try additional "if" clauses.
def __init__(self, path, name, files=(), dirs=(), volumes=()):
f = [path.join(dir, filename)
for dir in dirs
for filename in files]
f2 = [path.join(drive, dir, filename)
for dir in dirs
for filename in files
for drive in volumes]
return f, f2
# From 3.6 codeop. The below listcomp is generated still
# like it was in 3.5
import __future__
_features = [getattr(__future__, fname)
for fname in __future__.all_feature_names]

View File

@@ -0,0 +1,37 @@
# From 3.6 argparse. Bug was in handling EXTENDED_ARGS in a JUMP_FORWARD
# messing up control flow detection
def _format_usage(self, usage, actions, groups, prefix):
if usage:
usage = usage % dict(prog=self._prog)
elif usage is None:
prog = 5
for action in actions:
if action.option_strings:
actions.append(action)
else:
actions.append(action)
action_usage = format(optionals + positionals, groups)
text_width = self._width - self._current_indent
if len(prefix) + len(usage) > text_width:
if len(prefix) + len(prog) <= 0.75 * text_width:
indent = ' ' * (len(prefix) + len(prog) + 1)
if opt_parts:
lines.extend(get_lines(pos_parts, indent))
elif pos_parts:
lines = get_lines([prog] + pos_parts, indent, prefix)
else:
lines = [prog]
else:
if len(lines) > 1:
lines.extend(get_lines(pos_parts, indent))
lines = [prog] + lines
usage = '\n'.positionals(lines)
return

View File

@@ -0,0 +1,9 @@
# From 3.6 _markupbase.py
# Bug was parsing the inner while
def _parse_doctype_subset(c, j, rawdata, n):
while n:
if c:
j += 1
while j < n and rawdata[j]:
j += 1
return -1

View File

@@ -0,0 +1,8 @@
# Issue #162
def x(s):
return {k: v
for (k, v) in s
if not k.startswith('_')
}
assert x((('_foo', None),)) == {}

View File

@@ -0,0 +1,2 @@
# Tests relative imports
from . import bogus

View File

@@ -6,3 +6,16 @@ def PipeClient(address):
else:
raise
return
# From 2.6.9 sre.py
# Bug was parsing inner while1. Our massaging adds a COME_FROM
# possibly in the wrong place. When control flow is
# redone possibly all of this mess will disappear.
def _parse(source, state, this, group, char):
while 1:
if this:
while 1:
raise RuntimeError
else:
raise IndexError
return

13
test/stdlib/run-and-email.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/bash
EMAIL=${EMAIL:-rb@dustyfeet.com}
for VERSION in 2.7.14 2.6.9 ; do
LOGFILE=/tmp/runtests-$VERSION-$$.log
./runtests.sh >$LOGFILE 2>&1
rc=$?
if ((rc == 0)); then
tail -v $LOGFILE | mail -s \""$VERSION ok"\" rocky@localhost
else
tail -v $LOGFILE | mail -s \""$VERSION not ok"\" rocky@localhost
tail -v $LOGFILE | mail -s \""$VERSION not ok"\" rb@dustyfeet.com
fi
done

View File

@@ -27,24 +27,18 @@ case $PYVERSION in
SKIP_TESTS=(
[test_dis.py]=1 # We change line numbers - duh!
[test_grp.py]=1 # Long test - might work Control flow?
[test_math.py]=1 # Control flow?
[test_pwd.py]=1 # Long test - might work? Control flow?
[test_queue.py]=1 # Control flow?
[test_sax.py]=1 # Control flow?
# [test_threading.py]=1 # Long test - works
[test_types.py]=1 # Control flow?
)
;;
2.5)
SKIP_TESTS=(
[test_contextlib.py]=1
[test_dis.py]=1 # We change line numbers - duh!
[test_exceptions.py]=1
[test_functools.py]=1
[test_grammar.py]=1 # Too many stmts. Handle large stmts
[test_grp.py]=1 # Long test - might work Control flow?
[test_math.py]=1 # Control flow?
[test_pdb.py]=1
[test_contextlib.py]=1 # Syntax error - look at
[test_dis.py]=1 # We change line numbers - duh!
[test_grammar.py]=1 # Too many stmts. Handle large stmts
[test_grp.py]=1 # Long test - might work Control flow?
[test_pdb.py]=1 # Line-number specific
[test_pwd.py]=1 # Long test - might work? Control flow?
[test_queue.py]=1 # Control flow?
[test_re.py]=1 # Probably Control flow?
@@ -58,7 +52,11 @@ case $PYVERSION in
[test_opcodes.py]=1
[test_pwd.py]=1 # Long test - might work? Control flow?
[test_re.py]=1 # Probably Control flow?
[test_queue.py]=1 # Control flow?
[test_strftime.py]=1
[test_trace.py]=1 # Line numbers are expected to be different
[test_zipfile64.py]=1 # Skip Long test
[test_zlib.py]=1 # Look at
# .pyenv/versions/2.6.9/lib/python2.6/lib2to3/refactor.pyc
# .pyenv/versions/2.6.9/lib/python2.6/pyclbr.pyc
# .pyenv/versions/2.6.9/lib/python2.6/quopri.pyc -- look at ishex, is short
@@ -71,13 +69,19 @@ case $PYVERSION in
;;
2.7)
SKIP_TESTS=(
# These are ok, but our test machine POWER has problems
# so we skip..
[test_httplib.py]=1 # Ok, but POWER has problems with this
[test_pdb.py]=1 # Ok, but POWER has problems with this
[test_curses.py]=1 # Possibly fails on its own but not detected
[test_dis.py]=1 # We change line numbers - duh!
[test_doctest.py]=1 # Fails on its own
[test_grammar.py]=1 # Too many stmts. Handle large stmts
[test_io.py]=1 # Test takes too long to run
[test_ioctl.py]=1 # Test takes too long to run
[test_itertools.py]=1 # Syntax error - look at!
[test_itertools.py]=1 # Fix erroneous reduction to "conditional_true".
# See test/simple_source/bug27+/05_not_unconditional.py
[test_memoryio.py]=1 # FIX
[test_multiprocessing.py]=1 # On uncompyle2, taks 24 secs
[test_pep352.py]=1 # ?

View File

@@ -9,6 +9,7 @@ Usage-Examples:
test_pyenvlib.py --all --verify # decomyile all tests and verify results
test_pyenvlib.py --test # decompile only the testsuite
test_pyenvlib.py --2.7.12 --verify # decompile and verify python lib 2.7.11
test_pyenvlib.py --3.6.4 --max 10 # decompile first 10 of 3.6.4
Adding own test-trees:
@@ -115,8 +116,10 @@ def do_tests(src_dir, patterns, target_dir, start_with=None,
files = files[:max_files]
print(time.ctime())
main.main(src_dir, target_dir, files, [], do_verify=do_verify)
(tot_files, okay_files, failed_files,
verify_failed_files) = main.main(src_dir, target_dir, files, [], do_verify=do_verify)
print(time.ctime())
return verify_failed_files + failed_files
if __name__ == '__main__':
import getopt, sys
@@ -160,15 +163,19 @@ if __name__ == '__main__':
'/tmp/spark-grammar-%s.cover' % vers
)
failed = 0
for src_dir, pattern, target_dir in test_dirs:
if os.path.exists(src_dir):
target_dir = os.path.join(target_base, target_dir)
if os.path.exists(target_dir):
shutil.rmtree(target_dir, ignore_errors=1)
do_tests(src_dir, pattern, target_dir, start_with,
do_verify, test_options['max='])
failed += do_tests(src_dir, pattern, target_dir, start_with,
do_verify, test_options['max='])
else:
print("### Path %s doesn't exist; skipping" % src_dir)
pass
pass
sys.exit(failed)
# python 1.5:

View File

@@ -1,7 +1,7 @@
"""
Copyright (c) 1999 John Aycock
Copyright (c) 2015, 2018 by Rocky Bernstein
Copyright (c) 2000 by hartmut Goebel <h.goebel@crazy-compilers.com>
Copyright (c) 2015 by Rocky Bernstein
Copyright (c) 1999 John Aycock
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -55,6 +55,10 @@ from uncompyle6.main import decompile_file
uncompyle_file = decompile_file
# Conventience functions so you can say:
# from uncompyle6 import deparse_code
# from uncompyle6 import (code_deparse, deparse_code2str)
code_deparse = uncompyle6.semantics.pysource.code_deparse
deparse_code2str = uncompyle6.semantics.pysource.deparse_code2str
# This is deprecated:
deparse_code = uncompyle6.semantics.pysource.deparse_code

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python
# Mode: -*- python -*-
#
# Copyright (c) 2015-2016 by Rocky Bernstein <rb@dustyfeet.com>
# Copyright (c) 2015-2016, 2018 by Rocky Bernstein <rb@dustyfeet.com>
#
import sys, os, getopt
@@ -15,17 +15,24 @@ Usage:
%s [OPTIONS]... FILE
%s [--help | -h | -V | --version]
Disassemble FILE with the instruction mangling that is done to
assist uncompyle6 in parsing the instruction stream. For example
instructions with variable-length arguments like CALL_FUNCTION and
BUILD_LIST have arguement counts appended to the instruction name, and
COME_FROM instructions are inserted into the instruction stream.
Examples:
{0} foo.pyc
{0} foo.py # same thing as above but find the file
{0} foo.pyc bar.pyc # disassemble foo.pyc and bar.pyc
%s foo.pyc
%s foo.py # same thing as above but find the file
%s foo.pyc bar.pyc # disassemble foo.pyc and bar.pyc
See also `pydisasm' from the `xdis' package.
Options:
-U | --uncompyle6 show instructions with uncompyle6 mangling
-V | --version show version and stop
-h | --help show this message
""" % (program, program)
""" % ((program,) * 5)
PATTERNS = ('*.pyc', '*.pyo')
@@ -33,8 +40,6 @@ def main():
Usage_short = """usage: %s FILE...
Type -h for for full help.""" % program
native = True
if len(sys.argv) == 1:
sys.stderr.write("No file(s) given\n")
sys.stderr.write(Usage_short)
@@ -54,8 +59,6 @@ Type -h for for full help.""" % program
elif opt in ('-V', '--version'):
print("%s %s" % (program, VERSION))
sys.exit(0)
elif opt in ('-U', '--uncompyle6'):
native = False
else:
print(opt)
sys.stderr.write(Usage_short)
@@ -63,7 +66,7 @@ Type -h for for full help.""" % program
for file in files:
if os.path.exists(files[0]):
disassemble_file(file, sys.stdout, native)
disassemble_file(file, sys.stdout)
else:
sys.stderr.write("Can't read %s - skipping\n" % files[0])
pass

View File

@@ -1,7 +1,20 @@
# Copyright (c) 2015-2016, 2818 by Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright (c) 1999 John Aycock
# Copyright (c) 2015-2016, 2818 by Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright (c) 1999 John Aycock
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
CPython magic- and version- independent disassembly routines

View File

@@ -1,3 +1,18 @@
# Copyright (c) 2015-2016, 2818 by Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from collections import deque
from xdis.code import iscode

View File

@@ -1,6 +1,21 @@
import datetime, os, subprocess, sys, tempfile
# Copyright (C) 2018 Rocky Bernstein <rocky@gnu.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from uncompyle6 import verify, IS_PYPY, PYTHON_VERSION
import datetime, os, subprocess, sys
from uncompyle6 import verify, IS_PYPY
from xdis.code import iscode
from uncompyle6.disas import check_object_path
from uncompyle6.semantics import pysource
@@ -8,8 +23,8 @@ from uncompyle6.parser import ParserError
from uncompyle6.version import VERSION
# from uncompyle6.linenumbers import line_number_mapping
from uncompyle6.semantics.pysource import deparse_code
from uncompyle6.semantics.fragments import deparse_code as deparse_code_fragments
from uncompyle6.semantics.pysource import code_deparse
from uncompyle6.semantics.fragments import code_deparse as code_deparse_fragments
from uncompyle6.semantics.linemap import deparse_code_with_map
from xdis.load import load_module
@@ -28,7 +43,7 @@ def _get_outstream(outfile):
def decompile(
bytecode_version, co, out=None, showasm=None, showast=False,
timestamp=None, showgrammar=False, code_objects={},
source_size=None, is_pypy=False, magic_int=None,
source_size=None, is_pypy=None, magic_int=None,
mapstream=None, do_fragments=False):
"""
ingests and deparses a given code block 'co'
@@ -74,6 +89,12 @@ def decompile(
real_out.write('# Size of source mod 2**32: %d bytes\n' %
source_size)
debug_opts = {
'asm': showasm,
'ast': showast,
'grammar': showgrammar
}
try:
if mapstream:
if isinstance(mapstream, str):
@@ -91,12 +112,12 @@ def decompile(
mapstream.write("\n\n# %s\n" % linemap)
else:
if do_fragments:
deparse_fn = deparse_code_fragments
deparse_fn = code_deparse_fragments
else:
deparse_fn = deparse_code
deparsed = deparse_fn(bytecode_version, co, out, showasm, showast,
showgrammar, code_objects=code_objects,
is_pypy=is_pypy)
deparse_fn = code_deparse
deparsed = deparse_fn(co, out, bytecode_version,
debug_opts = debug_opts,
is_pypy=is_pypy)
pass
return deparsed
except pysource.SourceWalkerError, e:
@@ -224,6 +245,7 @@ def main(in_base, out_base, files, codes, outfile=None,
sys.stdout.write("\n")
sys.stderr.write("# file %s\n" % (infile))
failed_files += 1
tot_files += 1
except KeyboardInterrupt:
if outfile:
outstream.close()
@@ -250,7 +272,7 @@ def main(in_base, out_base, files, codes, outfile=None,
do_verify)
if not current_outfile:
if not msg:
print '\n# okay decompiling %s' % infile
print('\n# okay decompiling %s' % infile)
okay_files += 1
else:
verify_failed_files += 1

View File

@@ -1,7 +1,20 @@
# Copyright (c) 2015-2017 Rocky Bernstein
# Copyright (c) 2015-2018 Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright (c) 1999 John Aycock
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Common uncompyle6 parser routines.
"""

View File

@@ -306,9 +306,9 @@ class Python2Parser(PythonParser):
], customize)
if self.version >= 2.7:
self.add_unique_rule(
'dictcomp_func ::= BUILD_MAP_n LOAD_FAST FOR_ITER store '
'dict_comp_func ::= BUILD_MAP_n LOAD_FAST FOR_ITER store '
'comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST',
'dictcomp_func', 0, customize)
'dict_comp_func', 0, customize)
else:
kvlist_n = "kvlist_%s" % token.attr

View File

@@ -18,6 +18,10 @@ class Python22Parser(Python23Parser):
COME_FROM POP_TOP COME_FROM
list_for ::= expr for_iter store list_iter CONTINUE JUMP_FORWARD
COME_FROM POP_TOP COME_FROM
# Some versions of Python 2.2 have been found to generate
# PRINT_ITEM_CONT for PRINT_ITEM
print_items_stmt ::= expr PRINT_ITEM_CONT print_items_opt
'''
def customize_grammar_rules(self, tokens, customize):

View File

@@ -32,6 +32,9 @@ class Python23Parser(Python24Parser):
while1stmt ::= _while1test l_stmts_opt JUMP_BACK
POP_TOP POP_BLOCK COME_FROM
while1stmt ::= _while1test l_stmts_opt JUMP_BACK
POP_TOP POP_BLOCK
while1stmt ::= _while1test l_stmts_opt JUMP_BACK
COME_FROM POP_TOP POP_BLOCK COME_FROM

View File

@@ -33,8 +33,8 @@ class Python24Parser(Python25Parser):
import_cont ::= filler LOAD_CONST alias
# Python 2.5+ omits POP_TOP POP_BLOCK
while1stmt ::= SETUP_LOOP l_stmts JUMP_BACK POP_TOP POP_BLOCK COME_FROM
while1stmt ::= SETUP_LOOP l_stmts_opt JUMP_BACK POP_TOP POP_BLOCK COME_FROM
while1stmt ::= SETUP_LOOP l_stmts_opt JUMP_BACK POP_TOP POP_BLOCK
# Python 2.5+:
# call_stmt ::= expr POP_TOP
@@ -69,7 +69,6 @@ class Python24Parser(Python25Parser):
super(Python24Parser, self).customize_grammar_rules(tokens, customize)
if self.version == 2.4:
self.check_reduce['nop_stmt'] = 'tokens'
self.check_reduce['try_except'] = 'tokens'
def reduce_is_invalid(self, rule, ast, tokens, first, last):
invalid = super(Python24Parser,
@@ -83,15 +82,6 @@ class Python24Parser(Python25Parser):
l = len(tokens)
if 0 <= l < len(tokens):
return not int(tokens[first].pattr) == tokens[last].offset
elif lhs == 'try_except':
if last == len(tokens):
last -= 1
if tokens[last] != 'COME_FROM' and tokens[last-1] == 'COME_FROM':
last -= 1
return (tokens[last] == 'COME_FROM'
and tokens[last-1] == 'END_FINALLY'
and tokens[last-2] == 'POP_TOP'
and tokens[last-3].kind != 'JUMP_FORWARD')
return False

View File

@@ -89,15 +89,16 @@ class Python25Parser(Python26Parser):
""")
super(Python25Parser, self).customize_grammar_rules(tokens, customize)
if self.version == 2.5:
self.check_reduce['tryelsestmt'] = 'tokens'
self.check_reduce['try_except'] = 'tokens'
def reduce_is_invalid(self, rule, ast, tokens, first, last):
invalid = super(Python25Parser,
self).reduce_is_invalid(rule, ast,
tokens, first, last)
if invalid:
return invalid
return False
## Don't need this for 2.5 yet..
# def reduce_is_invalid(self, rule, ast, tokens, first, last):
# invalid = super(Python25Parser,
# self).reduce_is_invalid(rule, ast,
# tokens, first, last)
# if invalid or tokens is None:
# return invalid
# return False
class Python25ParserSingle(Python26Parser, PythonParserSingle):

View File

@@ -22,7 +22,7 @@ class Python26Parser(Python2Parser):
JUMP_IF_FALSE POP_TOP POP_TOP store POP_TOP
except_handler ::= JUMP_FORWARD COME_FROM except_stmts
come_from_pop END_FINALLY come_froms
come_froms_pop END_FINALLY come_froms
except_handler ::= JUMP_FORWARD COME_FROM except_stmts END_FINALLY
come_froms
@@ -77,8 +77,7 @@ class Python26Parser(Python2Parser):
jb_cont ::= JUMP_BACK
jb_cont ::= CONTINUE
jb_cf_pop ::= JUMP_BACK come_froms POP_TOP
jb_cf_pop ::= JUMP_BACK POP_TOP
jb_cf_pop ::= come_from_opt JUMP_BACK _come_froms POP_TOP
ja_cf_pop ::= JUMP_ABSOLUTE come_froms POP_TOP
jf_cf_pop ::= JUMP_FORWARD come_froms POP_TOP
@@ -115,8 +114,7 @@ class Python26Parser(Python2Parser):
# Semantic actions want else_suitel to be at index 3
ifelsestmtl ::= testexpr c_stmts_opt cf_jb_cf_pop else_suitel
ifelsestmtc ::= testexpr c_stmts_opt ja_cf_pop else_suitec
ifelsestmtc ::= testexpr c_stmts_opt ja_cf_pop else_suitec
# Semantic actions want suite_stmts_opt to be at index 3
withstmt ::= expr setupwith SETUP_FINALLY suite_stmts_opt
@@ -135,10 +133,15 @@ class Python26Parser(Python2Parser):
setup_finally ::= STORE_FAST SETUP_FINALLY LOAD_FAST DELETE_FAST
setup_finally ::= STORE_NAME SETUP_FINALLY LOAD_NAME DELETE_NAME
while1stmt ::= SETUP_LOOP l_stmts JUMP_BACK COME_FROM
while1stmt ::= SETUP_LOOP l_stmts_opt come_from_opt JUMP_BACK _come_froms
# Sometimes JUMP_BACK is misclassified as CONTINUE.
# workaround until we have better control flow in place
while1stmt ::= SETUP_LOOP l_stmts_opt CONTINUE _come_froms
whilestmt ::= SETUP_LOOP testexpr l_stmts_opt jb_pop POP_BLOCK _come_froms
whilestmt ::= SETUP_LOOP testexpr l_stmts_opt jb_cf_pop bp_come_from
whilestmt ::= SETUP_LOOP testexpr l_stmts_opt jb_cf_pop POP_BLOCK
whilestmt ::= SETUP_LOOP testexpr returns POP_BLOCK COME_FROM
whileelsestmt ::= SETUP_LOOP testexpr l_stmts_opt jb_pop POP_BLOCK
@@ -149,13 +152,11 @@ class Python26Parser(Python2Parser):
return ::= ret_expr RETURN_VALUE POP_TOP
return_if_stmt ::= ret_expr RETURN_END_IF POP_TOP
iflaststmtl ::= testexpr c_stmts_opt JUMP_BACK come_from_pop
iflaststmtl ::= testexpr c_stmts_opt jb_cf_pop
iflaststmt ::= testexpr c_stmts_opt JUMP_ABSOLUTE come_from_pop
lastc_stmt ::= iflaststmt COME_FROM
while1stmt ::= SETUP_LOOP l_stmts_opt JUMP_BACK COME_FROM
ifstmt ::= testexpr_then _ifstmts_jump
# Semantic actions want the else to be at position 3
@@ -314,6 +315,7 @@ class Python26Parser(Python2Parser):
self.check_reduce['and'] = 'AST'
self.check_reduce['list_for'] = 'AST'
self.check_reduce['try_except'] = 'tokens'
self.check_reduce['tryelsestmt'] = 'AST'
def reduce_is_invalid(self, rule, ast, tokens, first, last):
invalid = super(Python26Parser,
@@ -341,7 +343,7 @@ class Python26Parser(Python2Parser):
ja_attr = ast[4].attr
return tokens[last].offset != ja_attr
elif rule[0] == 'try_except':
# We need to distingush try_except from try_except_else and we do that
# We need to distingush try_except from tryelsestmt and we do that
# by checking the jump before the END_FINALLY
# If we have:
# insn
@@ -349,14 +351,65 @@ class Python26Parser(Python2Parser):
# END_FINALLY
# COME_FROM
# then insn has to be either a JUMP_FORWARD or a RETURN_VALUE
# and if it is JUMP_FORWARD, then it has to be a JUMP_FORWARD to right after
# COME_FROM
if last == len(tokens):
last -= 1
if tokens[last] != 'COME_FROM' and tokens[last-1] == 'COME_FROM':
last -= 1
return (tokens[last] == 'COME_FROM'
and tokens[last-1] == 'END_FINALLY'
and tokens[last-2] == 'POP_TOP'
and tokens[last-3].kind not in frozenset(('JUMP_FORWARD', 'RETURN_VALUE')))
if (tokens[last] == 'COME_FROM'
and tokens[last-1] == 'END_FINALLY'
and tokens[last-2] == 'POP_TOP'):
# A jump of 2 is a jump around POP_TOP, END_FINALLY which
# would indicate try/else rather than try
return (tokens[last-3].kind not in frozenset(('JUMP_FORWARD', 'RETURN_VALUE'))
or (tokens[last-3] == 'JUMP_FORWARD' and tokens[last-3].attr != 2))
elif rule[0] == 'tryelsestmt':
# We need to distingush try_except from tryelsestmt and we do that
# by making sure that the jump before the except handler jumps to
# code somewhere before the end of the construct.
# This AST method is slower, but the token-only based approach
# didn't work as it failed with a "try" embedded inside a "try/else"
# since we can't detect COME_FROM boundaries.
if ast[3] == 'except_handler':
except_handler = ast[3]
if except_handler[0] == 'JUMP_FORWARD':
else_start = int(except_handler[0].pattr)
if last == len(tokens):
last -= 1
if tokens[last] == 'COME_FROM' and isinstance:
last_offset = int(tokens[last].offset.split('_')[0])
return else_start >= last_offset
# The above test apparently isn't good enough, so we have additional
# checks distinguish try_except from tryelsestmt and we do that
# by checking the jump before the END_FINALLY
# If we have:
# insn
# POP_TOP
# END_FINALLY
# COME_FROM
# then insn is neither a JUMP_FORWARD nor RETURN_VALUE,
# or if it is JUMP_FORWARD, then it can't be a JUMP_FORWARD to right after
# COME_FROM
if last == len(tokens):
last -= 1
while tokens[last-1] == 'COME_FROM' and tokens[last-2] == 'COME_FROM':
last -= 1
if tokens[last] == 'COME_FROM' and tokens[last-1] == 'COME_FROM':
last -= 1
if (tokens[last] == 'COME_FROM'
and tokens[last-1] == 'END_FINALLY'
and tokens[last-2] == 'POP_TOP'):
# A jump of 2 is a jump around POP_TOP, END_FINALLY which
# would indicate try/else rather than try
return (tokens[last-3].kind in frozenset(('JUMP_FORWARD', 'RETURN_VALUE'))
and (tokens[last-3] != 'JUMP_FORWARD' or tokens[last-3].attr == 2))
return False
class Python26ParserSingle(Python2Parser, PythonParserSingle):
pass

View File

@@ -1,4 +1,4 @@
# Copyright (c) 2016-2017 Rocky Bernstein
# Copyright (c) 2016-2018 Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <hartmut@goebel.noris.de>
@@ -17,24 +17,31 @@ class Python27Parser(Python2Parser):
list_for ::= expr for_iter store list_iter JUMP_BACK
list_comp ::= BUILD_LIST_0 list_iter
lc_body ::= expr LIST_APPEND
for_iter ::= GET_ITER COME_FROM FOR_ITER
stmt ::= set_comp_func
stmt ::= setcomp_func
# Dictionary and set comprehensions were added in Python 2.7
expr ::= dict_comp
dict_comp ::= LOAD_DICTCOMP MAKE_FUNCTION_0 expr GET_ITER CALL_FUNCTION_1
stmt ::= dictcomp_func
dictcomp_func ::= BUILD_MAP_0 LOAD_FAST FOR_ITER store
comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST
stmt ::= dict_comp_func
dict_comp_func ::= BUILD_MAP_0 LOAD_FAST FOR_ITER store
comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST
setcomp_func ::= BUILD_SET_0 LOAD_FAST FOR_ITER store comp_iter
JUMP_BACK RETURN_VALUE RETURN_LAST
set_comp_func ::= BUILD_SET_0 LOAD_FAST FOR_ITER store comp_iter
JUMP_BACK RETURN_VALUE RETURN_LAST
comp_body ::= dict_comp_body
comp_body ::= set_comp_body
comp_for ::= expr for_iter store comp_iter JUMP_BACK
comp_iter ::= comp_if
comp_iter ::= comp_if_not
comp_if_not ::= expr jmp_true comp_iter
comp_iter ::= comp_body
dict_comp_body ::= expr expr MAP_ADD
set_comp_body ::= expr SET_ADD
@@ -53,6 +60,9 @@ class Python27Parser(Python2Parser):
tryelsestmtl ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
except_handler else_suitel JUMP_BACK COME_FROM
tryelsestmtl ::= SETUP_EXCEPT suite_stmts_opt POP_BLOCK
except_handler else_suitel
except_stmt ::= except_cond2 except_suite
except_cond1 ::= DUP_TOP expr COMPARE_OP
@@ -60,6 +70,9 @@ class Python27Parser(Python2Parser):
except_cond2 ::= DUP_TOP expr COMPARE_OP
jmp_false POP_TOP store POP_TOP
for_block ::= l_stmts_opt JUMP_BACK
"""
def p_jump27(self, args):
@@ -94,7 +107,10 @@ class Python27Parser(Python2Parser):
# conditional_true are for conditions which always evaluate true
# There is dead or non-optional remnants of the condition code though,
# and we use that to match on to reconstruct the source more accurately
# and we use that to match on to reconstruct the source more accurately.
# FIXME: we should do analysis and reduce *only* if there is dead code?
# right now we check that expr is "or". Any other nodes types?
expr ::= conditional_true
conditional_true ::= expr JUMP_FORWARD expr COME_FROM
@@ -130,6 +146,11 @@ class Python27Parser(Python2Parser):
whileelsestmt ::= SETUP_LOOP testexpr l_stmts_opt JUMP_BACK POP_BLOCK
else_suitel COME_FROM
return_stmts ::= _stmts return_stmt
return_stmts ::= return_stmt
return_stmt ::= return
ifstmt ::= testexpr return_stmts COME_FROM
ifstmt ::= testexpr return_if_stmts COME_FROM
ifelsestmt ::= testexpr c_stmts_opt JUMP_FORWARD else_suite COME_FROM
ifelsestmtc ::= testexpr c_stmts_opt JUMP_ABSOLUTE else_suitec
@@ -154,6 +175,7 @@ class Python27Parser(Python2Parser):
""")
super(Python27Parser, self).customize_grammar_rules(tokens, customize)
self.check_reduce['and'] = 'AST'
# self.check_reduce['conditional_true'] = 'AST'
return
def reduce_is_invalid(self, rule, ast, tokens, first, last):
@@ -169,6 +191,12 @@ class Python27Parser(Python2Parser):
jmp_target = jmp_false.offset + jmp_false.attr + 3
return not (jmp_target == tokens[last].offset or
tokens[last].pattr == jmp_false.pattr)
# elif rule[0] == ('conditional_true'):
# # FIXME: the below is a hack: we check expr for
# # nodes that could have possibly been a been a Boolean.
# # We should also look for the presence of dead code.
# return ast[0] == 'expr' and ast[0] == 'or'
return False

View File

@@ -3,7 +3,18 @@
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright (c) 1999 John Aycock
#
# See LICENSE for license
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
A spark grammar for Python 3.x.
@@ -51,13 +62,13 @@ class Python3Parser(PythonParser):
jb_or_c ::= JUMP_BACK
jb_or_c ::= CONTINUE
stmt ::= setcomp_func
stmt ::= set_comp_func
setcomp_func ::= BUILD_SET_0 LOAD_FAST FOR_ITER store comp_iter
JUMP_BACK RETURN_VALUE RETURN_LAST
set_comp_func ::= BUILD_SET_0 LOAD_FAST FOR_ITER store comp_iter
JUMP_BACK RETURN_VALUE RETURN_LAST
setcomp_func ::= BUILD_SET_0 LOAD_FAST FOR_ITER store comp_iter
COME_FROM JUMP_BACK RETURN_VALUE RETURN_LAST
set_comp_func ::= BUILD_SET_0 LOAD_FAST FOR_ITER store comp_iter
COME_FROM JUMP_BACK RETURN_VALUE RETURN_LAST
comp_body ::= dict_comp_body
comp_body ::= set_comp_body
@@ -67,14 +78,19 @@ class Python3Parser(PythonParser):
# See also common Python p_list_comprehension
"""
def p_dictcomp3(self, args):
def p_dict_comp3(self, args):
""""
expr ::= dict_comp
stmt ::= dictcomp_func
dictcomp_func ::= BUILD_MAP_0 LOAD_FAST FOR_ITER store
comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST
dict_comp ::= LOAD_DICTCOMP LOAD_CONST MAKE_FUNCTION_0 expr
GET_ITER CALL_FUNCTION_1
stmt ::= dict_comp_func
dict_comp_func ::= BUILD_MAP_0 LOAD_FAST FOR_ITER store
comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST
dict_comp ::= LOAD_DICTCOMP LOAD_CONST MAKE_FUNCTION_0 expr
GET_ITER CALL_FUNCTION_1
comp_iter ::= comp_if
comp_iter ::= comp_if_not
comp_if_not ::= expr jmp_true comp_iter
comp_iter ::= comp_body
"""
def p_grammar(self, args):
@@ -136,7 +152,7 @@ class Python3Parser(PythonParser):
iflaststmtl ::= testexpr c_stmts_opt JUMP_BACK COME_FROM_LOOP
iflaststmtl ::= testexpr c_stmts_opt JUMP_BACK POP_BLOCK
# These are used to keep AST indices the same
# These are used to keep parse tree indices the same
jump_forward_else ::= JUMP_FORWARD ELSE
jump_absolute_else ::= JUMP_ABSOLUTE ELSE
@@ -484,33 +500,15 @@ class Python3Parser(PythonParser):
token.kind = self.call_fn_name(token)
uniq_param = args_kw + args_pos
if self.version == 3.5 and opname.startswith('CALL_FUNCTION_VAR'):
# Python 3.5 changes the stack position of *args. KW args come
# after *args.
# Python 3.6+ replaces CALL_FUNCTION_VAR_KW with CALL_FUNCTION_EX
if opname.endswith('KW'):
kw = 'expr '
else:
kw = ''
rule = ('call ::= expr expr ' +
('pos_arg ' * args_pos) +
('kwarg ' * args_kw) + kw + token.kind)
self.add_unique_rule(rule, token.kind, uniq_param, customize)
# Note: 3.5+ have subclassed this method; so we don't handle
# 'CALL_FUNCTION_VAR' or 'CALL_FUNCTION_EX' here.
rule = ('call ::= expr ' +
('pos_arg ' * args_pos) +
('kwarg ' * args_kw) +
'expr ' * nak + token.kind)
self.add_unique_rule(rule, token.kind, uniq_param, customize)
if self.version >= 3.5 and seen_GET_AWAITABLE_YIELD_FROM:
rule = ('async_call ::= expr ' +
('pos_arg ' * args_pos) +
('kwarg ' * args_kw) +
'expr ' * nak + token.kind +
' GET_AWAITABLE LOAD_CONST YIELD_FROM')
self.add_unique_rule(rule, token.kind, uniq_param, customize)
self.add_unique_rule('expr ::= async_call', token.kind, uniq_param, customize)
'expr ' * nak + token.kind)
self.add_unique_rule(rule, token.kind, uniq_param, customize)
if possible_class_decorator:
if next_token == 'CALL_FUNCTION' and next_token.attr == 1:
@@ -635,9 +633,9 @@ class Python3Parser(PythonParser):
kvlist_n = "kvlist_%s" % token.attr
if opname == 'BUILD_MAP_n':
# PyPy sometimes has no count. Sigh.
rule = ('dictcomp_func ::= BUILD_MAP_n LOAD_FAST FOR_ITER store '
rule = ('dict_comp_func ::= BUILD_MAP_n LOAD_FAST FOR_ITER store '
'comp_iter JUMP_BACK RETURN_VALUE RETURN_LAST')
self.add_unique_rule(rule, 'dictomp_func', 1, customize)
self.add_unique_rule(rule, 'dict_comp_func', 1, customize)
kvlist_n = 'kvlist_n'
rule = 'kvlist_n ::= kvlist_n kv3'
@@ -671,6 +669,11 @@ class Python3Parser(PythonParser):
rule = ('build_map_unpack_with_call ::= ' + 'expr1024 ' * int(v//1024) +
'expr32 ' * int((v//32) % 32) +
'expr ' * (v % 32) + opname)
self.addRule(rule, nop_func)
elif opname.startswith('BUILD_TUPLE_UNPACK_WITH_CALL'):
v = token.attr
rule = ('starred ::= %s %s' % ('expr ' * v, opname))
self.addRule(rule, nop_func)
elif opname_base in ('BUILD_LIST', 'BUILD_SET', 'BUILD_TUPLE'):
v = token.attr
@@ -899,8 +902,15 @@ class Python3Parser(PythonParser):
"GET_ITER CALL_FUNCTION_1" % ('pos_arg '* args_pos, opname))
self.add_make_function_rule(rule_pat, opname, token.attr, customize)
if is_pypy or (i >= 2 and tokens[i-2] == 'LOAD_LISTCOMP'):
if self.version >= 3.6:
# 3.6+ sometimes bundles all of the
# 'exprs' in the rule above into a
# tuple.
rule_pat = ("listcomp ::= load_closure LOAD_LISTCOMP %%s%s "
"expr GET_ITER CALL_FUNCTION_1" % (opname,))
self.add_make_function_rule(rule_pat, opname, token.attr, customize)
rule_pat = ("listcomp ::= %sLOAD_LISTCOMP %%s%s expr "
"GET_ITER CALL_FUNCTION_1" % ('expr ' * args_pos, opname))
"GET_ITER CALL_FUNCTION_1" % ('expr ' * args_pos, opname))
self.add_make_function_rule(rule_pat, opname, token.attr, customize)
if is_pypy or (i >= 2 and tokens[i-2] == 'LOAD_LAMBDA'):
@@ -1117,10 +1127,6 @@ class Python30Parser(Python3Parser):
def p_30(self, args):
"""
# Store locals is only in Python 3.0 to 3.3
stmt ::= store_locals
store_locals ::= LOAD_FAST STORE_LOCALS
jmp_true ::= JUMP_IF_TRUE_OR_POP POP_TOP
_ifstmts_jump ::= c_stmts_opt JUMP_FORWARD POP_TOP COME_FROM
"""

View File

@@ -10,9 +10,6 @@ class Python30Parser(Python31Parser):
def p_30(self, args):
"""
# Store locals is only in Python 3.0 to 3.3
stmt ::= store_locals
store_locals ::= LOAD_FAST STORE_LOCALS
# FIXME: combine with parse3.2
whileTruestmt ::= SETUP_LOOP l_stmts_opt JUMP_BACK

View File

@@ -25,6 +25,13 @@ class Python33Parser(Python32Parser):
jump_excepts come_from_except_clauses
"""
def p_30to33(self, args):
"""
# Store locals is only in Python 3.0 to 3.3
stmt ::= store_locals
store_locals ::= LOAD_FAST STORE_LOCALS
"""
def customize_grammar_rules(self, tokens, customize):
self.remove_rules("""
# 3.3+ adds POP_BLOCKS

View File

@@ -1,4 +1,17 @@
# Copyright (c) 2017 Rocky Bernstein
# Copyright (c) 2017-2018 Rocky Bernstein
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
spark grammar differences over Python 3.3 for Python 3.4
"""
@@ -18,6 +31,10 @@ class Python34Parser(Python33Parser):
expr ::= LOAD_ASSERT
# Seems to be needed starting 3.4.4 or so
while1stmt ::= SETUP_LOOP l_stmts
COME_FROM JUMP_BACK POP_BLOCK COME_FROM_LOOP
# FIXME the below masks a bug in not detecting COME_FROM_LOOP
# grammar rules with COME_FROM -> COME_FROM_LOOP already exist
whileelsestmt ::= SETUP_LOOP testexpr l_stmts_opt JUMP_BACK POP_BLOCK
@@ -30,8 +47,10 @@ class Python34Parser(Python33Parser):
"""
def customize_grammar_rules(self, tokens, customize):
# self.remove_rules("""
# """)
self.remove_rules("""
# 3.4.2 has this. 3.4.4 may now
# while1stmt ::= SETUP_LOOP l_stmts COME_FROM JUMP_BACK COME_FROM_LOOP
""")
super(Python34Parser, self).customize_grammar_rules(tokens, customize)
return

View File

@@ -186,6 +186,52 @@ class Python35Parser(Python34Parser):
pass
return
def custom_classfunc_rule(self, opname, token, customize,
seen_LOAD_BUILD_CLASS,
seen_GET_AWAITABLE_YIELD_FROM,
*args):
args_pos, args_kw = self.get_pos_kw(token)
# Additional exprs for * and ** args:
# 0 if neither
# 1 for CALL_FUNCTION_VAR or CALL_FUNCTION_KW
# 2 for * and ** args (CALL_FUNCTION_VAR_KW).
# Yes, this computation based on instruction name is a little bit hoaky.
nak = ( len(opname)-len('CALL_FUNCTION') ) // 3
uniq_param = args_kw + args_pos
if seen_GET_AWAITABLE_YIELD_FROM:
rule = ('async_call ::= expr ' +
('pos_arg ' * args_pos) +
('kwarg ' * args_kw) +
'expr ' * nak + token.kind +
' GET_AWAITABLE LOAD_CONST YIELD_FROM')
self.add_unique_rule(rule, token.kind, uniq_param, customize)
self.add_unique_rule('expr ::= async_call', token.kind, uniq_param, customize)
uniq_param = args_kw + args_pos
if opname.startswith('CALL_FUNCTION_VAR'):
# Python 3.5 changes the stack position of *args. KW args come
# after *args.
# Note: Python 3.6+ replaces CALL_FUNCTION_VAR and
# CALL_FUNCTION_VAR_KW with CALL_FUNCTION_EX
token.kind = self.call_fn_name(token)
if opname.endswith('KW'):
kw = 'expr '
else:
kw = ''
rule = ('call ::= expr expr ' +
('pos_arg ' * args_pos) +
('kwarg ' * args_kw) + kw + token.kind)
self.add_unique_rule(rule, token.kind, uniq_param, customize)
else:
super(Python35Parser, self).custom_classfunc_rule(opname, token, customize,
seen_LOAD_BUILD_CLASS,
seen_GET_AWAITABLE_YIELD_FROM,
*args)
class Python35ParserSingle(Python35Parser, PythonParserSingle):
pass

View File

@@ -1,4 +1,17 @@
# Copyright (c) 2016-2017 Rocky Bernstein
# Copyright (c) 2016-2018 Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
spark grammar differences over Python 3.5 for Python 3.6.
"""
@@ -6,6 +19,7 @@ spark grammar differences over Python 3.5 for Python 3.6.
from uncompyle6.parser import PythonParserSingle, nop_func
from spark_parser import DEFAULT_DEBUG as PARSER_DEFAULT_DEBUG
from uncompyle6.parsers.parse35 import Python35Parser
from uncompyle6.scanners.tok import Token
class Python36Parser(Python35Parser):
@@ -16,6 +30,8 @@ class Python36Parser(Python35Parser):
def p_36misc(self, args):
"""
sstmt ::= sstmt RETURN_LAST
# 3.6 redoes how return_closure works
return_closure ::= LOAD_CLOSURE DUP_TOP STORE_NAME RETURN_VALUE RETURN_LAST
@@ -29,6 +45,8 @@ class Python36Parser(Python35Parser):
for_block ::= l_stmts_opt come_from_loops JUMP_BACK
come_from_loops ::= COME_FROM_LOOP*
whilestmt ::= SETUP_LOOP testexpr l_stmts_opt
JUMP_BACK COME_FROM POP_BLOCK COME_FROM_LOOP
# This might be valid in < 3.6
and ::= expr jmp_false expr
@@ -48,11 +66,20 @@ class Python36Parser(Python35Parser):
except_handler36 ::= COME_FROM_EXCEPT except_stmts END_FINALLY
stmt ::= try_except36
try_except36 ::= SETUP_EXCEPT returns except_handler36 opt_come_from_except
try_except36 ::= SETUP_EXCEPT returns except_handler36
opt_come_from_except
stmt ::= tryfinally36
tryfinally36 ::= SETUP_FINALLY returns
COME_FROM_FINALLY suite_stmts
tryfinally36 ::= SETUP_FINALLY returns
COME_FROM_FINALLY suite_stmts_opt END_FINALLY
"""
def customize_grammar_rules(self, tokens, customize):
super(Python36Parser, self).customize_grammar_rules(tokens, customize)
self.check_reduce['call_kw'] = 'AST'
for i, token in enumerate(tokens):
opname = token.kind
@@ -131,6 +158,26 @@ class Python36Parser(Python35Parser):
def custom_classfunc_rule(self, opname, token, customize,
possible_class_decorator,
seen_GET_AWAITABLE_YIELD_FROM, next_token):
args_pos, args_kw = self.get_pos_kw(token)
# Additional exprs for * and ** args:
# 0 if neither
# 1 for CALL_FUNCTION_VAR or CALL_FUNCTION_KW
# 2 for * and ** args (CALL_FUNCTION_VAR_KW).
# Yes, this computation based on instruction name is a little bit hoaky.
nak = ( len(opname)-len('CALL_FUNCTION') ) // 3
uniq_param = args_kw + args_pos
if seen_GET_AWAITABLE_YIELD_FROM:
rule = ('async_call ::= expr ' +
('pos_arg ' * args_pos) +
('kwarg ' * args_kw) +
'expr ' * nak + token.kind +
' GET_AWAITABLE LOAD_CONST YIELD_FROM')
self.add_unique_rule(rule, token.kind, uniq_param, customize)
self.add_unique_rule('expr ::= async_call', token.kind, uniq_param, customize)
if opname.startswith('CALL_FUNCTION_KW'):
self.addRule("expr ::= call_kw", nop_func)
values = 'expr ' * token.attr
@@ -142,6 +189,8 @@ class Python36Parser(Python35Parser):
self.addRule("""expr ::= call_ex_kw
expr ::= call_ex_kw2
expr ::= call_ex_kw3
expr ::= call_ex_kw4
call_ex_kw ::= expr expr build_map_unpack_with_call
CALL_FUNCTION_EX_KW
call_ex_kw2 ::= expr
@@ -149,6 +198,10 @@ class Python36Parser(Python35Parser):
build_map_unpack_with_call
CALL_FUNCTION_EX_KW
call_ex_kw3 ::= expr
build_tuple_unpack_with_call
expr
CALL_FUNCTION_EX_KW
call_ex_kw4 ::= expr
expr
expr
CALL_FUNCTION_EX_KW
@@ -168,6 +221,21 @@ class Python36Parser(Python35Parser):
seen_GET_AWAITABLE_YIELD_FROM,
next_token)
def reduce_is_invalid(self, rule, ast, tokens, first, last):
invalid = super(Python36Parser,
self).reduce_is_invalid(rule, ast,
tokens, first, last)
if invalid:
return invalid
if rule[0] == 'call_kw':
# Make sure we don't derive call_kw
nt = ast[0]
while not isinstance(nt, Token):
if nt[0] == 'call_kw':
return True
nt = nt[0]
return False
class Python36ParserSingle(Python36Parser, PythonParserSingle):
pass

View File

@@ -1,4 +1,17 @@
# Copyright (c) 2017 Rocky Bernstein
# Copyright (c) 2017-2018 Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
spark grammar differences over Python 3.6 for Python 3.7
"""

View File

@@ -3,7 +3,18 @@
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright (c) 1999 John Aycock
#
# See LICENSE
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
scanner/ingestion module. From here we call various version-specific
@@ -15,8 +26,8 @@ import sys
from uncompyle6 import PYTHON3, IS_PYPY
from uncompyle6.scanners.tok import Token
import xdis
from xdis.bytecode import op_size, extended_arg_val
from xdis.magics import py_str2float, canonic_python_version
from xdis.bytecode import instruction_size, extended_arg_val, next_offset
from xdis.magics import canonic_python_version
from xdis.util import code2num
# The byte code versions we support.
@@ -89,19 +100,38 @@ class Scanner(object):
That is, it is ether "JUMP_FORWARD" or an absolute jump that
goes forward.
"""
if self.code[offset] == self.opc.JUMP_FORWARD:
opname = self.get_inst(offset).opname
if opname == 'JUMP_FORWARD':
return True
if self.code[offset] != self.opc.JUMP_ABSOLUTE:
if opname != 'JUMP_ABSOLUTE':
return False
# FIXME 0 isn't always correct
return offset < self.get_target(offset, 0)
return offset < self.get_target(offset)
def get_target(self, pos, op=None):
if op is None:
op = self.code[pos]
target = self.get_argument(pos)
if op in self.opc.JREL_OPS:
target += pos + 3
def prev_offset(self, offset):
return self.insts[self.offset2inst_index[offset]-1].offset
def get_inst(self, offset):
# Instructions can get moved as a result of EXTENDED_ARGS removal.
# So if "offset" is not in self.offset2inst_index, then
# we assume that it was an instruction moved back.
# We check that assumption though by looking at
# self.code's opcode.
if offset not in self.offset2inst_index:
offset -= instruction_size(self.opc.EXTENDED_ARG, self.opc)
assert self.code[offset] == self.opc.EXTENDED_ARG
return self.insts[self.offset2inst_index[offset]]
def get_target(self, offset, extended_arg=0):
"""
Get next instruction offset for op located at given <offset>.
NOTE: extended_arg is no longer used
"""
inst = self.get_inst(offset)
if inst.opcode in self.opc.JREL_OPS | self.opc.JABS_OPS:
target = inst.argval
else:
# No jump offset, so use fall-through offset
target = next_offset(inst.opcode, self.opc, inst.offset)
return target
def get_argument(self, pos):
@@ -267,7 +297,7 @@ class Scanner(object):
"""
while start < end:
yield start
start += op_size(self.code[start], self.opc)
start += instruction_size(self.code[start], self.opc)
def remove_mid_line_ifs(self, ifs):
"""

View File

@@ -1,6 +1,19 @@
# Copyright (c) 2015-2018 by Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
# Copyright (c) 2015-2018 by Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Python 2 Generic bytecode scanner/deparser
@@ -30,7 +43,9 @@ else:
from array import array
from xdis.code import iscode
from xdis.bytecode import Bytecode, op_has_argument, op_size, instruction_size
from xdis.bytecode import (
Bytecode, op_has_argument, instruction_size,
_get_const_info)
from xdis.util import code2num
from uncompyle6.scanner import Scanner
@@ -76,13 +91,14 @@ class Scanner2(Scanner):
def ingest(self, co, classname=None, code_objects={}, show_asm=None):
"""
Pick out tokens from an uncompyle6 code object, and transform them,
returning a list of uncompyle6 'Token's.
returning a list of uncompyle6 Token's.
The transformations are made to assist the deparsing grammar.
Specificially:
- various types of LOAD_CONST's are categorized in terms of what they load
- COME_FROM instructions are added to assist parsing control structures
- MAKE_FUNCTION and FUNCTION_CALLS append the number of positional arguments
- some EXTENDED_ARGS instructions are removed
Also, when we encounter certain tokens, we add them to a set which will cause custom
grammar rules. Specifically, variable arg tokens like MAKE_FUNCTION or BUILD_LIST
@@ -145,8 +161,10 @@ class Scanner2(Scanner):
if names[self.get_argument(i+3)] == 'AssertionError':
self.load_asserts.add(i+3)
# Get jump targets
# Format: {target offset: [jump offsets]}
jump_targets = self.find_jump_targets(show_asm)
# contains (code, [addrRefToCode])
# print("XXX2", jump_targets)
last_stmt = self.next_stmt[0]
i = self.next_stmt[last_stmt]
@@ -221,7 +239,13 @@ class Scanner2(Scanner):
# (id(const), const.co_filename, const.co_name)
pattr = '<code_object ' + const.co_name + '>'
else:
if oparg < len(co.co_consts):
argval, _ = _get_const_info(oparg, co.co_consts)
# Why don't we use _ above for "pattr" rather than "const"?
# This *is* a little hoaky, but we have to coordinate with
# other parts like n_LOAD_CONST in pysource.py for example.
pattr = const
pass
elif op in self.opc.NAME_OPS:
pattr = names[oparg]
elif op in self.opc.JREL_OPS:
@@ -271,9 +295,22 @@ class Scanner2(Scanner):
target = self.get_target(offset)
if target <= offset:
op_name = 'JUMP_BACK'
if (offset in self.stmts
and self.code[offset+3] not in (self.opc.END_FINALLY,
self.opc.POP_BLOCK)):
# 'Continue's include jumps to loops that are not
# and the end of a block which follow with POP_BLOCK and COME_FROM_LOOP.
# If the JUMP_ABSOLUTE is
# either to a FOR_ITER or the instruction after a SETUP_LOOP
# and it is followed by another JUMP_FORWARD
# then we'll take it as a "continue".
j = self.offset2inst_index[offset]
target_index = self.offset2inst_index[target]
is_continue = (self.insts[target_index-1].opname == 'SETUP_LOOP'
and self.insts[j+1].opname == 'JUMP_FORWARD')
if is_continue:
op_name = 'CONTINUE'
if (offset in self.stmts and
self.code[offset+3] not in (self.opc.END_FINALLY,
self.opc.POP_BLOCK)):
if ((offset in self.linestartoffsets and
self.code[self.prev[offset]] == self.opc.JUMP_ABSOLUTE)
or self.code[target] == self.opc.FOR_ITER
@@ -387,7 +424,7 @@ class Scanner2(Scanner):
if elem != code[i]:
match = False
break
i += op_size(code[i], self.opc)
i += instruction_size(code[i], self.opc)
if match:
i = self.prev[i]
@@ -633,7 +670,7 @@ class Scanner2(Scanner):
'start': jump_back_offset+3,
'end': loop_end_offset})
elif op == self.opc.SETUP_EXCEPT:
start = offset + op_size(op, self.opc)
start = offset + instruction_size(op, self.opc)
target = self.get_target(offset, op)
end_offset = self.restrict_to_parent(target, parent)
if target != end_offset:
@@ -657,7 +694,7 @@ class Scanner2(Scanner):
setup_except_nest -= 1
elif self.code[end_finally_offset] == self.opc.SETUP_EXCEPT:
setup_except_nest += 1
end_finally_offset += op_size(code[end_finally_offset], self.opc)
end_finally_offset += instruction_size(code[end_finally_offset], self.opc)
pass
# Add the except blocks
@@ -870,7 +907,7 @@ class Scanner2(Scanner):
else:
# We still have the case in 2.7 that the next instruction
# is a jump to a SETUP_LOOP target.
next_offset = target + op_size(self.code[target], self.opc)
next_offset = target + instruction_size(self.code[target], self.opc)
next_op = self.code[next_offset]
if self.op_name(next_op) == 'JUMP_FORWARD':
jump_target = self.get_target(next_offset, next_op)
@@ -962,17 +999,32 @@ class Scanner2(Scanner):
'end': end_offset})
elif code_pre_rtarget == self.opc.RETURN_VALUE:
if self.version == 2.7 or pre_rtarget not in self.ignore_if:
# 10 is exception-match. If there is an exception match in the
# compare, then this is an exception clause not an if-then clause
# Below, 10 is exception-match. If there is an exception
# match in the compare, then this is an exception
# clause not an if-then clause
if (self.code[self.prev[offset]] != self.opc.COMPARE_OP or
self.code[self.prev[offset]+1] != 10):
self.structs.append({'type': 'if-then',
'start': start,
'end': rtarget})
self.thens[start] = rtarget
if self.version == 2.7 or code[pre_rtarget+1] != self.opc.JUMP_FORWARD:
if (self.version == 2.7 or
code[pre_rtarget+1] != self.opc.JUMP_FORWARD):
# The below is a big hack until we get
# better control flow analysis: disallow
# END_IF if the instruction before the
# END_IF instruction happens to be a jump
# target. In this case, probably what's
# gone on is that we messed up on the
# END_IF location and it should be the
# instruction before.
self.fixed_jumps[offset] = rtarget
self.return_end_ifs.add(pre_rtarget)
if (self.version == 2.7 and
self.insts[self.offset2inst_index[pre[pre_rtarget]]].is_jump_target):
self.return_end_ifs.add(pre[pre_rtarget])
pass
else:
self.return_end_ifs.add(pre_rtarget)
pass
pass
pass
@@ -1079,7 +1131,13 @@ class Scanner2(Scanner):
source = self.setup_loops[label]
else:
source = offset
targets[label] = targets.get(label, []) + [source]
# FIXME: The grammar for 2.6 and before doesn't
# handle COME_FROM's from a loop inside if's
# It probably should.
if (self.version > 2.6 or
self.code[source] != self.opc.SETUP_LOOP or
self.code[label] != self.opc.JUMP_FORWARD):
targets[label] = targets.get(label, []) + [source]
pass
pass
pass

View File

@@ -1,6 +1,19 @@
# Copyright (c) 2015-2017 by Rocky Bernstein
# Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org>
# Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Python 2.6 bytecode scanner
@@ -20,6 +33,8 @@ from uncompyle6.scanner import L65536
# bytecode verification, verify(), uses JUMP_OPs from here
from xdis.opcodes import opcode_26
from xdis.bytecode import Bytecode
from xdis.bytecode import _get_const_info
JUMP_OPS = opcode_26.JUMP_OPS
class Scanner26(scan.Scanner2):
@@ -212,7 +227,13 @@ class Scanner26(scan.Scanner2):
# (id(const), const.co_filename, const.co_name)
pattr = '<code_object ' + const.co_name + '>'
else:
if oparg < len(co.co_consts):
argval, _ = _get_const_info(oparg, co.co_consts)
# Why don't we use _ above for "pattr" rather than "const"?
# This *is* a little hoaky, but we have to coordinate with
# other parts like n_LOAD_CONST in pysource.py for example.
pattr = const
pass
elif op in self.opc.NAME_OPS:
pattr = names[oparg]
elif op in self.opc.JREL_OPS:

Some files were not shown because too many files have changed in this diff Show More