Upload 30 files
Browse files- .gitattributes +1 -0
- renpy/UnRen_Island.7z +3 -0
- renpy/rpaExtract.7z +3 -0
- renpy/rpaExtract.exe +3 -0
- renpy/rpaext.7z +3 -0
- renpy/rpaext/rpaext.exe +0 -0
- renpy/rpaext/zlib.net.dll +0 -0
- renpy/rpycdec.7z +3 -0
- renpy/rpycdec/rpycdec.bat +141 -0
- renpy/rpycdec/rpycdecdata/decompiler/__init__.py +958 -0
- renpy/rpycdec/rpycdecdata/decompiler/__init__.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/astdump.py +283 -0
- renpy/rpycdec/rpycdecdata/decompiler/astdump.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/codegen.py +1102 -0
- renpy/rpycdec/rpycdecdata/decompiler/codegen.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/magic.py +674 -0
- renpy/rpycdec/rpycdecdata/decompiler/magic.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/screendecompiler.py +678 -0
- renpy/rpycdec/rpycdecdata/decompiler/screendecompiler.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/sl2decompiler.py +374 -0
- renpy/rpycdec/rpycdecdata/decompiler/sl2decompiler.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/testcasedecompiler.py +142 -0
- renpy/rpycdec/rpycdecdata/decompiler/testcasedecompiler.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/translate.py +158 -0
- renpy/rpycdec/rpycdecdata/decompiler/translate.pyo +0 -0
- renpy/rpycdec/rpycdecdata/decompiler/util.py +502 -0
- renpy/rpycdec/rpycdecdata/decompiler/util.pyo +0 -0
- renpy/rpycdec/rpycdecdata/deobfuscate.py +347 -0
- renpy/rpycdec/rpycdecdata/deobfuscate.pyo +0 -0
- renpy/rpycdec/rpycdecdata/unrpyc.py +301 -0
- renpy/rpycdec/rpycdecdata/unrpyc.pyo +0 -0
.gitattributes
CHANGED
@@ -82,3 +82,4 @@ UEExtractor/UEExtractor.dll filter=lfs diff=lfs merge=lfs -text
|
|
82 |
UEExtractor/UEExtractor.exe filter=lfs diff=lfs merge=lfs -text
|
83 |
gdre_tools/gdre_tools.exe filter=lfs diff=lfs merge=lfs -text
|
84 |
gdre_tools/gdre_tools.pck filter=lfs diff=lfs merge=lfs -text
|
|
|
|
82 |
UEExtractor/UEExtractor.exe filter=lfs diff=lfs merge=lfs -text
|
83 |
gdre_tools/gdre_tools.exe filter=lfs diff=lfs merge=lfs -text
|
84 |
gdre_tools/gdre_tools.pck filter=lfs diff=lfs merge=lfs -text
|
85 |
+
renpy/rpaExtract.exe filter=lfs diff=lfs merge=lfs -text
|
renpy/UnRen_Island.7z
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c41c954b6da84dd9df80a78631b96983d34278745397a4e064870ae09d82e8fb
|
3 |
+
size 2372523
|
renpy/rpaExtract.7z
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cefb9d0a732eb8d3561923113ccb8056f1173bd419ad5161b156de4f435e2c94
|
3 |
+
size 6578002
|
renpy/rpaExtract.exe
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b5c07979238d1a2678e0121abdb043ec087261ff9d1b5bdb647160eb8cca51be
|
3 |
+
size 6777710
|
renpy/rpaext.7z
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:248354fcec3d2adc2a0109692551912c9e79d2237bfea1f5b3007e658b2834fc
|
3 |
+
size 24646
|
renpy/rpaext/rpaext.exe
ADDED
Binary file (16.9 kB). View file
|
|
renpy/rpaext/zlib.net.dll
ADDED
Binary file (69.6 kB). View file
|
|
renpy/rpycdec.7z
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8513f7449091e1c27f6b2055c5307ed9b6a114c5051f13400c94fde023006978
|
3 |
+
size 85068
|
renpy/rpycdec/rpycdec.bat
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
REM --------------------------------------------------------------------------------
|
3 |
+
REM Configuration:
|
4 |
+
REM Set a Quick Save and Quick Load hotkey - http://www.pygame.org/docs/ref/key.html
|
5 |
+
REM --------------------------------------------------------------------------------
|
6 |
+
set "quicksavekey=K_F5"
|
7 |
+
set "quickloadkey=K_F9"
|
8 |
+
REM --------------------------------------------------------------------------------
|
9 |
+
REM !! END CONFIG !!
|
10 |
+
REM --------------------------------------------------------------------------------
|
11 |
+
REM The following variables are Base64 encoded strings for unrpyc and rpatool
|
12 |
+
REM Due to batch limitations on variable lengths, they need to be split into
|
13 |
+
REM multiple variables, and joined later using powershell.
|
14 |
+
REM --------------------------------------------------------------------------------
|
15 |
+
REM unrpyc by CensoredUsername
|
16 |
+
REM https://github.com/CensoredUsername/unrpyc
|
17 |
+
REM Edited to remove multiprocessing and adjust output spacing 44febb0 2019-10-07T07:06:47.000Z
|
18 |
+
REM https://github.com/F95Sam/unrpyc
|
19 |
+
REM --------------------------------------------------------------------------------
|
20 |
+
REM !! DO NOT EDIT BELOW THIS LINE !!
|
21 |
+
REM --------------------------------------------------------------------------------
|
22 |
+
set "version=0.91 (includes Gideon.v5 mods) (191007)"
|
23 |
+
title UnRen.bat v%version%
|
24 |
+
:init
|
25 |
+
REM --------------------------------------------------------------------------------
|
26 |
+
REM Splash screen
|
27 |
+
REM --------------------------------------------------------------------------------
|
28 |
+
cls
|
29 |
+
echo.
|
30 |
+
echo __ __ ____ __ __
|
31 |
+
echo / / / /___ / __ \___ ____ / /_ ____ _/ /_
|
32 |
+
echo / / / / __ \/ /_/ / _ \/ __ \ / __ \/ __ ^`/ __/
|
33 |
+
echo / /_/ / / / / _^, _/ __/ / / / / /_/ / /_/ / /_
|
34 |
+
echo \____/_/ /_/_/ ^|_^|\___/_/ /_(_)_.___/\__^,_/\__/ v%version%
|
35 |
+
echo.
|
36 |
+
echo ----------------------------------------------------
|
37 |
+
echo.
|
38 |
+
|
39 |
+
REM --------------------------------------------------------------------------------
|
40 |
+
REM We need powershell for later, make sure it exists
|
41 |
+
REM --------------------------------------------------------------------------------
|
42 |
+
if not exist "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" (
|
43 |
+
echo ! Error: Powershell is required, unable to continue.
|
44 |
+
echo This is included in Windows 7, 8, 10. XP/Vista users can
|
45 |
+
echo download it here: http://support.microsoft.com/kb/968929
|
46 |
+
echo.
|
47 |
+
rem pause>nul|set/p=. Press any key to exit...
|
48 |
+
exit
|
49 |
+
)
|
50 |
+
|
51 |
+
REM --------------------------------------------------------------------------------
|
52 |
+
REM Set our paths, and make sure we can find python exe
|
53 |
+
REM --------------------------------------------------------------------------------
|
54 |
+
set "currentdir=%~dp0%"
|
55 |
+
set "pythondir=%currentdir%..\lib\windows-i686\"
|
56 |
+
set "renpydir=%currentdir%..\renpy\"
|
57 |
+
set "gamedir=%currentdir%"
|
58 |
+
if exist "game" if exist "lib" if exist "renpy" (
|
59 |
+
set "pythondir=%currentdir%lib\windows-i686\"
|
60 |
+
set "renpydir=%currentdir%renpy\"
|
61 |
+
set "gamedir=%currentdir%game\"
|
62 |
+
)
|
63 |
+
|
64 |
+
if not exist "%pythondir%python.exe" (
|
65 |
+
set "pythondir=%currentdir%..\lib\windows-x86_64\"
|
66 |
+
set "renpydir=%currentdir%..\renpy\"
|
67 |
+
set "gamedir=%currentdir%"
|
68 |
+
if exist "game" if exist "lib" if exist "renpy" (
|
69 |
+
set "pythondir=%currentdir%lib\windows-x86_64\"
|
70 |
+
set "renpydir=%currentdir%renpy\"
|
71 |
+
set "gamedir=%currentdir%game\"
|
72 |
+
)
|
73 |
+
)
|
74 |
+
|
75 |
+
if not exist "%pythondir%python.exe" (
|
76 |
+
echo ! Error: Cannot locate python.exe, unable to continue.
|
77 |
+
echo Are you sure we're in the game's root or game directory?
|
78 |
+
echo.
|
79 |
+
rem pause>nul|set/p=. Press any key to exit...
|
80 |
+
exit
|
81 |
+
)
|
82 |
+
|
83 |
+
:menu
|
84 |
+
goto decompile
|
85 |
+
|
86 |
+
:decompile
|
87 |
+
REM --------------------------------------------------------------------------------
|
88 |
+
REM Write to temporary file first, then convert. Needed due to binary file
|
89 |
+
REM --------------------------------------------------------------------------------
|
90 |
+
set "decompcab=%currentdir%rpycdecdata\_decomp.cab"
|
91 |
+
set "decompilerdir=%currentdir%rpycdecdata\decompiler"
|
92 |
+
set "unrpycpy=%currentdir%rpycdecdata\unrpyc.py"
|
93 |
+
set "deobfuscate=%currentdir%rpycdecdata\deobfuscate.py"
|
94 |
+
if not exist "%gamedir%*.rpyc" (
|
95 |
+
echo No .rpyc files found in %gamedir%!
|
96 |
+
echo.
|
97 |
+
goto finish
|
98 |
+
)
|
99 |
+
|
100 |
+
|
101 |
+
REM --------------------------------------------------------------------------------
|
102 |
+
REM Decompile rpyc files
|
103 |
+
REM --------------------------------------------------------------------------------
|
104 |
+
echo Searching for rpyc files...
|
105 |
+
cd "%gamedir%"
|
106 |
+
set "PYTHONPATH=%pythondir%Lib"
|
107 |
+
for /r %%f in (*.rpyc) do (
|
108 |
+
if not %%~nf == un (
|
109 |
+
echo + Decompiling "%%~nf%%~xf" - %%~zf bytes
|
110 |
+
"%pythondir%python.exe" -O "%unrpycpy%" -c --init-offset "%%f"
|
111 |
+
)
|
112 |
+
)
|
113 |
+
echo.
|
114 |
+
|
115 |
+
REM --------------------------------------------------------------------------------
|
116 |
+
REM Clean up
|
117 |
+
REM --------------------------------------------------------------------------------
|
118 |
+
echo Cleaning up temporary files...
|
119 |
+
del "%unrpycpy%"
|
120 |
+
del "%unrpycpy%o"
|
121 |
+
del "%decompcab%.tmp"
|
122 |
+
del "%decompcab%"
|
123 |
+
del "%deobfuscate%"
|
124 |
+
del "%deobfuscate%o"
|
125 |
+
rmdir /Q /S "%decompilerdir%"
|
126 |
+
rmdir /Q /S "%currentdir%rpycdecdata\"
|
127 |
+
echo.
|
128 |
+
|
129 |
+
goto finish
|
130 |
+
|
131 |
+
|
132 |
+
|
133 |
+
:finish
|
134 |
+
REM --------------------------------------------------------------------------------
|
135 |
+
REM We are done
|
136 |
+
REM --------------------------------------------------------------------------------
|
137 |
+
echo ----------------------------------------------------
|
138 |
+
echo Finished!
|
139 |
+
echo ----------------------------------------------------
|
140 |
+
|
141 |
+
exit
|
renpy/rpycdec/rpycdecdata/decompiler/__init__.py
ADDED
@@ -0,0 +1,958 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2012 Yuri K. Schlesner
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
from __future__ import unicode_literals
|
22 |
+
from util import DecompilerBase, First, WordConcatenator, reconstruct_paraminfo, \
|
23 |
+
reconstruct_arginfo, string_escape, split_logical_lines, Dispatcher
|
24 |
+
from util import say_get_code
|
25 |
+
|
26 |
+
from operator import itemgetter
|
27 |
+
from StringIO import StringIO
|
28 |
+
|
29 |
+
import magic
|
30 |
+
magic.fake_package(b"renpy")
|
31 |
+
import renpy
|
32 |
+
|
33 |
+
import screendecompiler
|
34 |
+
import sl2decompiler
|
35 |
+
import testcasedecompiler
|
36 |
+
import codegen
|
37 |
+
import astdump
|
38 |
+
|
39 |
+
__all__ = ["astdump", "codegen", "magic", "screendecompiler", "sl2decompiler", "testcasedecompiler", "translate", "util", "pprint", "Decompiler"]
|
40 |
+
|
41 |
+
# Main API
|
42 |
+
|
43 |
+
def pprint(out_file, ast, indent_level=0,
|
44 |
+
decompile_python=False, printlock=None, translator=None, init_offset=False, tag_outside_block=False):
|
45 |
+
Decompiler(out_file, printlock=printlock,
|
46 |
+
decompile_python=decompile_python, translator=translator).dump(ast, indent_level, init_offset, tag_outside_block)
|
47 |
+
|
48 |
+
# Implementation
|
49 |
+
|
50 |
+
class Decompiler(DecompilerBase):
|
51 |
+
"""
|
52 |
+
An object which hanldes the decompilation of renpy asts to a given stream
|
53 |
+
"""
|
54 |
+
|
55 |
+
# This dictionary is a mapping of Class: unbount_method, which is used to determine
|
56 |
+
# what method to call for which ast class
|
57 |
+
dispatch = Dispatcher()
|
58 |
+
|
59 |
+
def __init__(self, out_file=None, decompile_python=False,
|
60 |
+
indentation = ' ', printlock=None, translator=None):
|
61 |
+
super(Decompiler, self).__init__(out_file, indentation, printlock)
|
62 |
+
self.decompile_python = decompile_python
|
63 |
+
self.translator = translator
|
64 |
+
|
65 |
+
self.paired_with = False
|
66 |
+
self.say_inside_menu = None
|
67 |
+
self.label_inside_menu = None
|
68 |
+
self.in_init = False
|
69 |
+
self.missing_init = False
|
70 |
+
self.init_offset = 0
|
71 |
+
self.is_356c6e34_or_later = False
|
72 |
+
self.most_lines_behind = 0
|
73 |
+
self.last_lines_behind = 0
|
74 |
+
self.tag_outside_block = False
|
75 |
+
|
76 |
+
def advance_to_line(self, linenumber):
|
77 |
+
self.last_lines_behind = max(self.linenumber + (0 if self.skip_indent_until_write else 1) - linenumber, 0)
|
78 |
+
self.most_lines_behind = max(self.last_lines_behind, self.most_lines_behind)
|
79 |
+
super(Decompiler, self).advance_to_line(linenumber)
|
80 |
+
|
81 |
+
def save_state(self):
|
82 |
+
return (super(Decompiler, self).save_state(),
|
83 |
+
self.paired_with, self.say_inside_menu, self.label_inside_menu, self.in_init, self.missing_init, self.most_lines_behind, self.last_lines_behind)
|
84 |
+
|
85 |
+
def commit_state(self, state):
|
86 |
+
super(Decompiler, self).commit_state(state[0])
|
87 |
+
|
88 |
+
def rollback_state(self, state):
|
89 |
+
self.paired_with = state[1]
|
90 |
+
self.say_inside_menu = state[2]
|
91 |
+
self.label_inside_menu = state[3]
|
92 |
+
self.in_init = state[4]
|
93 |
+
self.missing_init = state[5]
|
94 |
+
self.most_lines_behind = state[6]
|
95 |
+
self.last_lines_behind = state[7]
|
96 |
+
super(Decompiler, self).rollback_state(state[0])
|
97 |
+
|
98 |
+
def dump(self, ast, indent_level=0, init_offset=False, tag_outside_block=False):
|
99 |
+
if (isinstance(ast, (tuple, list)) and len(ast) > 1 and
|
100 |
+
isinstance(ast[-1], renpy.ast.Return) and
|
101 |
+
(not hasattr(ast[-1], 'expression') or ast[-1].expression is None) and
|
102 |
+
ast[-1].linenumber == ast[-2].linenumber):
|
103 |
+
# A very crude version check, but currently the best we can do.
|
104 |
+
# Note that this commit first appears in the 6.99 release.
|
105 |
+
self.is_356c6e34_or_later = True
|
106 |
+
|
107 |
+
self.tag_outside_block = tag_outside_block
|
108 |
+
|
109 |
+
if self.translator:
|
110 |
+
self.translator.translate_dialogue(ast)
|
111 |
+
|
112 |
+
if init_offset and isinstance(ast, (tuple, list)):
|
113 |
+
self.set_best_init_offset(ast)
|
114 |
+
|
115 |
+
# skip_indent_until_write avoids an initial blank line
|
116 |
+
super(Decompiler, self).dump(ast, indent_level, skip_indent_until_write=True)
|
117 |
+
# if there's anything we wanted to write out but didn't yet, do it now
|
118 |
+
for m in self.blank_line_queue:
|
119 |
+
m(None)
|
120 |
+
self.write("\n# Decompiled by unrpyc: https://github.com/CensoredUsername/unrpyc\n")
|
121 |
+
assert not self.missing_init, "A required init, init label, or translate block was missing"
|
122 |
+
|
123 |
+
def print_node(self, ast):
|
124 |
+
# We special-case line advancement for some types in their print
|
125 |
+
# methods, so don't advance lines for them here.
|
126 |
+
if hasattr(ast, 'linenumber') and not isinstance(ast, (renpy.ast.TranslateString, renpy.ast.With, renpy.ast.Label, renpy.ast.Pass, renpy.ast.Return)):
|
127 |
+
self.advance_to_line(ast.linenumber)
|
128 |
+
# It doesn't matter what line "block:" is on. The loc of a RawBlock
|
129 |
+
# refers to the first statement inside the block, which we advance
|
130 |
+
# to from print_atl.
|
131 |
+
elif hasattr(ast, 'loc') and not isinstance(ast, renpy.atl.RawBlock):
|
132 |
+
self.advance_to_line(ast.loc[1])
|
133 |
+
self.dispatch.get(type(ast), type(self).print_unknown)(self, ast)
|
134 |
+
|
135 |
+
# ATL printing functions
|
136 |
+
|
137 |
+
def print_atl(self, ast):
|
138 |
+
with self.increase_indent():
|
139 |
+
self.advance_to_line(ast.loc[1])
|
140 |
+
if ast.statements:
|
141 |
+
self.print_nodes(ast.statements)
|
142 |
+
# If a statement ends with a colon but has no block after it, loc will
|
143 |
+
# get set to ('', 0). That isn't supposed to be valid syntax, but it's
|
144 |
+
# the only thing that can generate that.
|
145 |
+
elif ast.loc != ('', 0):
|
146 |
+
self.indent()
|
147 |
+
self.write("pass")
|
148 |
+
|
149 |
+
@dispatch(renpy.atl.RawMultipurpose)
|
150 |
+
def print_atl_rawmulti(self, ast):
|
151 |
+
warp_words = WordConcatenator(False)
|
152 |
+
|
153 |
+
# warpers
|
154 |
+
if ast.warp_function:
|
155 |
+
warp_words.append("warp", ast.warp_function, ast.duration)
|
156 |
+
elif ast.warper:
|
157 |
+
warp_words.append(ast.warper, ast.duration)
|
158 |
+
elif ast.duration != "0":
|
159 |
+
warp_words.append("pause", ast.duration)
|
160 |
+
|
161 |
+
warp = warp_words.join()
|
162 |
+
words = WordConcatenator(warp and warp[-1] != ' ', True)
|
163 |
+
|
164 |
+
# revolution
|
165 |
+
if ast.revolution:
|
166 |
+
words.append(ast.revolution)
|
167 |
+
|
168 |
+
# circles
|
169 |
+
if ast.circles != "0":
|
170 |
+
words.append("circles %s" % ast.circles)
|
171 |
+
|
172 |
+
# splines
|
173 |
+
spline_words = WordConcatenator(False)
|
174 |
+
for name, expressions in ast.splines:
|
175 |
+
spline_words.append(name, expressions[-1])
|
176 |
+
for expression in expressions[:-1]:
|
177 |
+
spline_words.append("knot", expression)
|
178 |
+
words.append(spline_words.join())
|
179 |
+
|
180 |
+
# properties
|
181 |
+
property_words = WordConcatenator(False)
|
182 |
+
for key, value in ast.properties:
|
183 |
+
property_words.append(key, value)
|
184 |
+
words.append(property_words.join())
|
185 |
+
|
186 |
+
# with
|
187 |
+
expression_words = WordConcatenator(False)
|
188 |
+
# TODO There's a lot of cases where pass isn't needed, since we could
|
189 |
+
# reorder stuff so there's never 2 expressions in a row. (And it's never
|
190 |
+
# necessary for the last one, but we don't know what the last one is
|
191 |
+
# since it could get reordered.)
|
192 |
+
needs_pass = len(ast.expressions) > 1
|
193 |
+
for (expression, with_expression) in ast.expressions:
|
194 |
+
expression_words.append(expression)
|
195 |
+
if with_expression:
|
196 |
+
expression_words.append("with", with_expression)
|
197 |
+
if needs_pass:
|
198 |
+
expression_words.append("pass")
|
199 |
+
words.append(expression_words.join())
|
200 |
+
|
201 |
+
to_write = warp + words.join()
|
202 |
+
if to_write:
|
203 |
+
self.indent()
|
204 |
+
self.write(to_write)
|
205 |
+
else:
|
206 |
+
# A trailing comma results in an empty RawMultipurpose being
|
207 |
+
# generated on the same line as the last real one.
|
208 |
+
self.write(",")
|
209 |
+
|
210 |
+
@dispatch(renpy.atl.RawBlock)
|
211 |
+
def print_atl_rawblock(self, ast):
|
212 |
+
self.indent()
|
213 |
+
self.write("block:")
|
214 |
+
self.print_atl(ast)
|
215 |
+
|
216 |
+
@dispatch(renpy.atl.RawChild)
|
217 |
+
def print_atl_rawchild(self, ast):
|
218 |
+
for child in ast.children:
|
219 |
+
self.indent()
|
220 |
+
self.write("contains:")
|
221 |
+
self.print_atl(child)
|
222 |
+
|
223 |
+
@dispatch(renpy.atl.RawChoice)
|
224 |
+
def print_atl_rawchoice(self, ast):
|
225 |
+
for chance, block in ast.choices:
|
226 |
+
self.indent()
|
227 |
+
self.write("choice")
|
228 |
+
if chance != "1.0":
|
229 |
+
self.write(" %s" % chance)
|
230 |
+
self.write(":")
|
231 |
+
self.print_atl(block)
|
232 |
+
if (self.index + 1 < len(self.block) and
|
233 |
+
isinstance(self.block[self.index + 1], renpy.atl.RawChoice)):
|
234 |
+
self.indent()
|
235 |
+
self.write("pass")
|
236 |
+
|
237 |
+
@dispatch(renpy.atl.RawContainsExpr)
|
238 |
+
def print_atl_rawcontainsexpr(self, ast):
|
239 |
+
self.indent()
|
240 |
+
self.write("contains %s" % ast.expression)
|
241 |
+
|
242 |
+
@dispatch(renpy.atl.RawEvent)
|
243 |
+
def print_atl_rawevent(self, ast):
|
244 |
+
self.indent()
|
245 |
+
self.write("event %s" % ast.name)
|
246 |
+
|
247 |
+
@dispatch(renpy.atl.RawFunction)
|
248 |
+
def print_atl_rawfunction(self, ast):
|
249 |
+
self.indent()
|
250 |
+
self.write("function %s" % ast.expr)
|
251 |
+
|
252 |
+
@dispatch(renpy.atl.RawOn)
|
253 |
+
def print_atl_rawon(self, ast):
|
254 |
+
for name, block in sorted(ast.handlers.items(),
|
255 |
+
key=lambda i: i[1].loc[1]):
|
256 |
+
self.indent()
|
257 |
+
self.write("on %s:" % name)
|
258 |
+
self.print_atl(block)
|
259 |
+
|
260 |
+
@dispatch(renpy.atl.RawParallel)
|
261 |
+
def print_atl_rawparallel(self, ast):
|
262 |
+
for block in ast.blocks:
|
263 |
+
self.indent()
|
264 |
+
self.write("parallel:")
|
265 |
+
self.print_atl(block)
|
266 |
+
if (self.index + 1 < len(self.block) and
|
267 |
+
isinstance(self.block[self.index + 1], renpy.atl.RawParallel)):
|
268 |
+
self.indent()
|
269 |
+
self.write("pass")
|
270 |
+
|
271 |
+
@dispatch(renpy.atl.RawRepeat)
|
272 |
+
def print_atl_rawrepeat(self, ast):
|
273 |
+
self.indent()
|
274 |
+
self.write("repeat")
|
275 |
+
if ast.repeats:
|
276 |
+
self.write(" %s" % ast.repeats) # not sure if this is even a string
|
277 |
+
|
278 |
+
@dispatch(renpy.atl.RawTime)
|
279 |
+
def print_atl_rawtime(self, ast):
|
280 |
+
self.indent()
|
281 |
+
self.write("time %s" % ast.time)
|
282 |
+
|
283 |
+
# Displayable related functions
|
284 |
+
|
285 |
+
def print_imspec(self, imspec):
|
286 |
+
if imspec[1] is not None:
|
287 |
+
begin = "expression %s" % imspec[1]
|
288 |
+
else:
|
289 |
+
begin = " ".join(imspec[0])
|
290 |
+
|
291 |
+
words = WordConcatenator(begin and begin[-1] != ' ', True)
|
292 |
+
if imspec[2] is not None:
|
293 |
+
words.append("as %s" % imspec[2])
|
294 |
+
|
295 |
+
if len(imspec[6]) > 0:
|
296 |
+
words.append("behind %s" % ', '.join(imspec[6]))
|
297 |
+
|
298 |
+
if isinstance(imspec[4], unicode):
|
299 |
+
words.append("onlayer %s" % imspec[4])
|
300 |
+
|
301 |
+
if imspec[5] is not None:
|
302 |
+
words.append("zorder %s" % imspec[5])
|
303 |
+
|
304 |
+
if len(imspec[3]) > 0:
|
305 |
+
words.append("at %s" % ', '.join(imspec[3]))
|
306 |
+
|
307 |
+
self.write(begin + words.join())
|
308 |
+
return words.needs_space
|
309 |
+
|
310 |
+
@dispatch(renpy.ast.Image)
|
311 |
+
def print_image(self, ast):
|
312 |
+
self.require_init()
|
313 |
+
self.indent()
|
314 |
+
self.write("image %s" % ' '.join(ast.imgname))
|
315 |
+
if ast.code is not None:
|
316 |
+
self.write(" = %s" % ast.code.source)
|
317 |
+
else:
|
318 |
+
if hasattr(ast, "atl") and ast.atl is not None:
|
319 |
+
self.write(":")
|
320 |
+
self.print_atl(ast.atl)
|
321 |
+
|
322 |
+
@dispatch(renpy.ast.Transform)
|
323 |
+
def print_transform(self, ast):
|
324 |
+
self.require_init()
|
325 |
+
self.indent()
|
326 |
+
|
327 |
+
# If we have an implicit init block with a non-default priority, we need to store the priority here.
|
328 |
+
priority = ""
|
329 |
+
if isinstance(self.parent, renpy.ast.Init):
|
330 |
+
init = self.parent
|
331 |
+
if init.priority != self.init_offset and len(init.block) == 1 and not self.should_come_before(init, ast):
|
332 |
+
priority = " %d" % (init.priority - self.init_offset)
|
333 |
+
self.write("transform%s %s" % (priority, ast.varname))
|
334 |
+
if ast.parameters is not None:
|
335 |
+
self.write(reconstruct_paraminfo(ast.parameters))
|
336 |
+
|
337 |
+
if hasattr(ast, "atl") and ast.atl is not None:
|
338 |
+
self.write(":")
|
339 |
+
self.print_atl(ast.atl)
|
340 |
+
|
341 |
+
# Directing related functions
|
342 |
+
|
343 |
+
@dispatch(renpy.ast.Show)
|
344 |
+
def print_show(self, ast):
|
345 |
+
self.indent()
|
346 |
+
self.write("show ")
|
347 |
+
needs_space = self.print_imspec(ast.imspec)
|
348 |
+
|
349 |
+
if self.paired_with:
|
350 |
+
if needs_space:
|
351 |
+
self.write(" ")
|
352 |
+
self.write("with %s" % self.paired_with)
|
353 |
+
self.paired_with = True
|
354 |
+
|
355 |
+
if hasattr(ast, "atl") and ast.atl is not None:
|
356 |
+
self.write(":")
|
357 |
+
self.print_atl(ast.atl)
|
358 |
+
|
359 |
+
@dispatch(renpy.ast.ShowLayer)
|
360 |
+
def print_showlayer(self, ast):
|
361 |
+
self.indent()
|
362 |
+
self.write("show layer %s" % ast.layer)
|
363 |
+
|
364 |
+
if ast.at_list:
|
365 |
+
self.write(" at %s" % ', '.join(ast.at_list))
|
366 |
+
|
367 |
+
if hasattr(ast, "atl") and ast.atl is not None:
|
368 |
+
self.write(":")
|
369 |
+
self.print_atl(ast.atl)
|
370 |
+
|
371 |
+
@dispatch(renpy.ast.Scene)
|
372 |
+
def print_scene(self, ast):
|
373 |
+
self.indent()
|
374 |
+
self.write("scene")
|
375 |
+
|
376 |
+
if ast.imspec is None:
|
377 |
+
if isinstance(ast.layer, unicode):
|
378 |
+
self.write(" onlayer %s" % ast.layer)
|
379 |
+
needs_space = True
|
380 |
+
else:
|
381 |
+
self.write(" ")
|
382 |
+
needs_space = self.print_imspec(ast.imspec)
|
383 |
+
|
384 |
+
if self.paired_with:
|
385 |
+
if needs_space:
|
386 |
+
self.write(" ")
|
387 |
+
self.write("with %s" % self.paired_with)
|
388 |
+
self.paired_with = True
|
389 |
+
|
390 |
+
if hasattr(ast, "atl") and ast.atl is not None:
|
391 |
+
self.write(":")
|
392 |
+
self.print_atl(ast.atl)
|
393 |
+
|
394 |
+
@dispatch(renpy.ast.Hide)
|
395 |
+
def print_hide(self, ast):
|
396 |
+
self.indent()
|
397 |
+
self.write("hide ")
|
398 |
+
needs_space = self.print_imspec(ast.imspec)
|
399 |
+
if self.paired_with:
|
400 |
+
if needs_space:
|
401 |
+
self.write(" ")
|
402 |
+
self.write("with %s" % self.paired_with)
|
403 |
+
self.paired_with = True
|
404 |
+
|
405 |
+
@dispatch(renpy.ast.With)
|
406 |
+
def print_with(self, ast):
|
407 |
+
# the 'paired' attribute indicates that this with
|
408 |
+
# and with node afterwards are part of a postfix
|
409 |
+
# with statement. detect this and process it properly
|
410 |
+
if hasattr(ast, "paired") and ast.paired is not None:
|
411 |
+
# Sanity check. check if there's a matching with statement two nodes further
|
412 |
+
if not(isinstance(self.block[self.index + 2], renpy.ast.With) and
|
413 |
+
self.block[self.index + 2].expr == ast.paired):
|
414 |
+
raise Exception("Unmatched paired with {0} != {1}".format(
|
415 |
+
repr(self.paired_with), repr(ast.expr)))
|
416 |
+
|
417 |
+
self.paired_with = ast.paired
|
418 |
+
|
419 |
+
elif self.paired_with:
|
420 |
+
# Check if it was consumed by a show/scene statement
|
421 |
+
if self.paired_with is not True:
|
422 |
+
self.write(" with %s" % ast.expr)
|
423 |
+
self.paired_with = False
|
424 |
+
else:
|
425 |
+
self.advance_to_line(ast.linenumber)
|
426 |
+
self.indent()
|
427 |
+
self.write("with %s" % ast.expr)
|
428 |
+
self.paired_with = False
|
429 |
+
|
430 |
+
# Flow control
|
431 |
+
|
432 |
+
@dispatch(renpy.ast.Label)
|
433 |
+
def print_label(self, ast):
|
434 |
+
# If a Call block preceded us, it printed us as "from"
|
435 |
+
if (self.index and isinstance(self.block[self.index - 1], renpy.ast.Call)):
|
436 |
+
return
|
437 |
+
remaining_blocks = len(self.block) - self.index
|
438 |
+
if remaining_blocks > 1:
|
439 |
+
next_ast = self.block[self.index + 1]
|
440 |
+
# See if we're the label for a menu, rather than a standalone label.
|
441 |
+
if (not ast.block and (not hasattr(ast, 'parameters') or ast.parameters is None) and
|
442 |
+
hasattr(next_ast, 'linenumber') and next_ast.linenumber == ast.linenumber and
|
443 |
+
(isinstance(next_ast, renpy.ast.Menu) or (remaining_blocks > 2 and
|
444 |
+
isinstance(next_ast, renpy.ast.Say) and
|
445 |
+
self.say_belongs_to_menu(next_ast, self.block[self.index + 2])))):
|
446 |
+
self.label_inside_menu = ast
|
447 |
+
return
|
448 |
+
self.advance_to_line(ast.linenumber)
|
449 |
+
self.indent()
|
450 |
+
|
451 |
+
# It's possible that we're an "init label", not a regular label. There's no way to know
|
452 |
+
# if we are until we parse our children, so temporarily redirect all of our output until
|
453 |
+
# that's done, so that we can squeeze in an "init " if we are.
|
454 |
+
out_file = self.out_file
|
455 |
+
self.out_file = StringIO()
|
456 |
+
missing_init = self.missing_init
|
457 |
+
self.missing_init = False
|
458 |
+
try:
|
459 |
+
self.write("label %s%s%s:" % (
|
460 |
+
ast.name,
|
461 |
+
reconstruct_paraminfo(ast.parameters) if hasattr(ast, 'parameters') else '',
|
462 |
+
" hide" if hasattr(ast, 'hide') and ast.hide else ""))
|
463 |
+
self.print_nodes(ast.block, 1)
|
464 |
+
finally:
|
465 |
+
if self.missing_init:
|
466 |
+
out_file.write("init ")
|
467 |
+
self.missing_init = missing_init
|
468 |
+
out_file.write(self.out_file.getvalue())
|
469 |
+
self.out_file = out_file
|
470 |
+
|
471 |
+
@dispatch(renpy.ast.Jump)
|
472 |
+
def print_jump(self, ast):
|
473 |
+
self.indent()
|
474 |
+
self.write("jump %s%s" % ("expression " if ast.expression else "", ast.target))
|
475 |
+
|
476 |
+
@dispatch(renpy.ast.Call)
|
477 |
+
def print_call(self, ast):
|
478 |
+
self.indent()
|
479 |
+
words = WordConcatenator(False)
|
480 |
+
words.append("call")
|
481 |
+
if ast.expression:
|
482 |
+
words.append("expression")
|
483 |
+
words.append(ast.label)
|
484 |
+
|
485 |
+
if hasattr(ast, 'arguments') and ast.arguments is not None:
|
486 |
+
if ast.expression:
|
487 |
+
words.append("pass")
|
488 |
+
words.append(reconstruct_arginfo(ast.arguments))
|
489 |
+
|
490 |
+
# We don't have to check if there's enough elements here,
|
491 |
+
# since a Label or a Pass is always emitted after a Call.
|
492 |
+
next_block = self.block[self.index + 1]
|
493 |
+
if isinstance(next_block, renpy.ast.Label):
|
494 |
+
words.append("from %s" % next_block.name)
|
495 |
+
|
496 |
+
self.write(words.join())
|
497 |
+
|
498 |
+
@dispatch(renpy.ast.Return)
|
499 |
+
def print_return(self, ast):
|
500 |
+
if ((not hasattr(ast, 'expression') or ast.expression is None) and self.parent is None and
|
501 |
+
self.index + 1 == len(self.block) and self.index and
|
502 |
+
ast.linenumber == self.block[self.index - 1].linenumber):
|
503 |
+
# As of Ren'Py commit 356c6e34, a return statement is added to
|
504 |
+
# the end of each rpyc file. Don't include this in the source.
|
505 |
+
return
|
506 |
+
|
507 |
+
self.advance_to_line(ast.linenumber)
|
508 |
+
self.indent()
|
509 |
+
self.write("return")
|
510 |
+
|
511 |
+
if hasattr(ast, 'expression') and ast.expression is not None:
|
512 |
+
self.write(" %s" % ast.expression)
|
513 |
+
|
514 |
+
@dispatch(renpy.ast.If)
|
515 |
+
def print_if(self, ast):
|
516 |
+
statement = First("if %s:", "elif %s:")
|
517 |
+
|
518 |
+
for i, (condition, block) in enumerate(ast.entries):
|
519 |
+
# The non-Unicode string "True" is the condition for else:.
|
520 |
+
if (i + 1) == len(ast.entries) and not isinstance(condition, unicode):
|
521 |
+
self.indent()
|
522 |
+
self.write("else:")
|
523 |
+
else:
|
524 |
+
if(hasattr(condition, 'linenumber')):
|
525 |
+
self.advance_to_line(condition.linenumber)
|
526 |
+
self.indent()
|
527 |
+
self.write(statement() % condition)
|
528 |
+
|
529 |
+
self.print_nodes(block, 1)
|
530 |
+
|
531 |
+
@dispatch(renpy.ast.While)
|
532 |
+
def print_while(self, ast):
|
533 |
+
self.indent()
|
534 |
+
self.write("while %s:" % ast.condition)
|
535 |
+
|
536 |
+
self.print_nodes(ast.block, 1)
|
537 |
+
|
538 |
+
@dispatch(renpy.ast.Pass)
|
539 |
+
def print_pass(self, ast):
|
540 |
+
if (self.index and
|
541 |
+
isinstance(self.block[self.index - 1], renpy.ast.Call)):
|
542 |
+
return
|
543 |
+
|
544 |
+
if (self.index > 1 and
|
545 |
+
isinstance(self.block[self.index - 2], renpy.ast.Call) and
|
546 |
+
isinstance(self.block[self.index - 1], renpy.ast.Label) and
|
547 |
+
self.block[self.index - 2].linenumber == ast.linenumber):
|
548 |
+
return
|
549 |
+
|
550 |
+
self.advance_to_line(ast.linenumber)
|
551 |
+
self.indent()
|
552 |
+
self.write("pass")
|
553 |
+
|
554 |
+
def should_come_before(self, first, second):
|
555 |
+
return first.linenumber < second.linenumber
|
556 |
+
|
557 |
+
def require_init(self):
|
558 |
+
if not self.in_init:
|
559 |
+
self.missing_init = True
|
560 |
+
|
561 |
+
def set_best_init_offset(self, nodes):
|
562 |
+
votes = {}
|
563 |
+
for ast in nodes:
|
564 |
+
if not isinstance(ast, renpy.ast.Init):
|
565 |
+
continue
|
566 |
+
offset = ast.priority
|
567 |
+
# Keep this block in sync with print_init
|
568 |
+
if len(ast.block) == 1 and not self.should_come_before(ast, ast.block[0]):
|
569 |
+
if isinstance(ast.block[0], renpy.ast.Screen):
|
570 |
+
offset -= -500
|
571 |
+
elif isinstance(ast.block[0], renpy.ast.Testcase):
|
572 |
+
offset -= 500
|
573 |
+
elif isinstance(ast.block[0], renpy.ast.Image):
|
574 |
+
offset -= 500 if self.is_356c6e34_or_later else 990
|
575 |
+
votes[offset] = votes.get(offset, 0) + 1
|
576 |
+
if votes:
|
577 |
+
winner = max(votes, key=votes.get)
|
578 |
+
# It's only worth setting an init offset if it would save
|
579 |
+
# more than one priority specification versus not setting one.
|
580 |
+
if votes.get(0, 0) + 1 < votes[winner]:
|
581 |
+
self.set_init_offset(winner)
|
582 |
+
|
583 |
+
def set_init_offset(self, offset):
|
584 |
+
def do_set_init_offset(linenumber):
|
585 |
+
# if we got to the end of the file and haven't emitted this yet,
|
586 |
+
# don't bother, since it only applies to stuff below it.
|
587 |
+
if linenumber is None or linenumber - self.linenumber <= 1 or self.indent_level:
|
588 |
+
return True
|
589 |
+
if offset != self.init_offset:
|
590 |
+
self.indent()
|
591 |
+
self.write("init offset = %s" % offset)
|
592 |
+
self.init_offset = offset
|
593 |
+
return False
|
594 |
+
|
595 |
+
self.do_when_blank_line(do_set_init_offset)
|
596 |
+
|
597 |
+
@dispatch(renpy.ast.Init)
|
598 |
+
def print_init(self, ast):
|
599 |
+
in_init = self.in_init
|
600 |
+
self.in_init = True
|
601 |
+
try:
|
602 |
+
# A bunch of statements can have implicit init blocks
|
603 |
+
# Define has a default priority of 0, screen of -500 and image of 990
|
604 |
+
# Keep this block in sync with set_best_init_offset
|
605 |
+
# TODO merge this and require_init into another decorator or something
|
606 |
+
if len(ast.block) == 1 and (
|
607 |
+
isinstance(ast.block[0], (renpy.ast.Define,
|
608 |
+
renpy.ast.Default,
|
609 |
+
renpy.ast.Transform)) or
|
610 |
+
(ast.priority == -500 + self.init_offset and isinstance(ast.block[0], renpy.ast.Screen)) or
|
611 |
+
(ast.priority == self.init_offset and isinstance(ast.block[0], renpy.ast.Style)) or
|
612 |
+
(ast.priority == 500 + self.init_offset and isinstance(ast.block[0], renpy.ast.Testcase)) or
|
613 |
+
(ast.priority == 0 + self.init_offset and isinstance(ast.block[0], renpy.ast.UserStatement) and ast.block[0].line.startswith("layeredimage ")) or
|
614 |
+
# Images had their default init priority changed in commit 679f9e31 (Ren'Py 6.99.10).
|
615 |
+
# We don't have any way of detecting this commit, though. The closest one we can
|
616 |
+
# detect is 356c6e34 (Ren'Py 6.99). For any versions in between these, we'll emit
|
617 |
+
# an unnecessary "init 990 " before image statements, but this doesn't affect the AST,
|
618 |
+
# and any other solution would result in incorrect code being generated in some cases.
|
619 |
+
(ast.priority == (500 if self.is_356c6e34_or_later else 990) + self.init_offset and isinstance(ast.block[0], renpy.ast.Image))) and not (
|
620 |
+
self.should_come_before(ast, ast.block[0])):
|
621 |
+
# If they fulfill this criteria we just print the contained statement
|
622 |
+
self.print_nodes(ast.block)
|
623 |
+
|
624 |
+
# translatestring statements are split apart and put in an init block.
|
625 |
+
elif (len(ast.block) > 0 and
|
626 |
+
ast.priority == self.init_offset and
|
627 |
+
all(isinstance(i, renpy.ast.TranslateString) for i in ast.block) and
|
628 |
+
all(i.language == ast.block[0].language for i in ast.block[1:])):
|
629 |
+
self.print_nodes(ast.block)
|
630 |
+
|
631 |
+
else:
|
632 |
+
self.indent()
|
633 |
+
self.write("init")
|
634 |
+
if ast.priority != self.init_offset:
|
635 |
+
self.write(" %d" % (ast.priority - self.init_offset))
|
636 |
+
|
637 |
+
if len(ast.block) == 1 and not self.should_come_before(ast, ast.block[0]):
|
638 |
+
self.write(" ")
|
639 |
+
self.skip_indent_until_write = True
|
640 |
+
self.print_nodes(ast.block)
|
641 |
+
else:
|
642 |
+
self.write(":")
|
643 |
+
self.print_nodes(ast.block, 1)
|
644 |
+
finally:
|
645 |
+
self.in_init = in_init
|
646 |
+
|
647 |
+
def print_say_inside_menu(self):
|
648 |
+
self.print_say(self.say_inside_menu, inmenu=True)
|
649 |
+
self.say_inside_menu = None
|
650 |
+
|
651 |
+
def print_menu_item(self, label, condition, block, arguments):
|
652 |
+
self.indent()
|
653 |
+
self.write('"%s"' % string_escape(label))
|
654 |
+
|
655 |
+
if arguments is not None:
|
656 |
+
self.write(reconstruct_arginfo(arguments))
|
657 |
+
|
658 |
+
if block is not None:
|
659 |
+
if isinstance(condition, unicode):
|
660 |
+
self.write(" if %s" % condition)
|
661 |
+
self.write(":")
|
662 |
+
self.print_nodes(block, 1)
|
663 |
+
|
664 |
+
@dispatch(renpy.ast.Menu)
|
665 |
+
def print_menu(self, ast):
|
666 |
+
self.indent()
|
667 |
+
self.write("menu")
|
668 |
+
if self.label_inside_menu is not None:
|
669 |
+
self.write(" %s" % self.label_inside_menu.name)
|
670 |
+
self.label_inside_menu = None
|
671 |
+
|
672 |
+
if hasattr(ast, "arguments") and ast.arguments is not None:
|
673 |
+
self.write(reconstruct_arginfo(ast.arguments))
|
674 |
+
|
675 |
+
self.write(":")
|
676 |
+
|
677 |
+
with self.increase_indent():
|
678 |
+
if ast.with_ is not None:
|
679 |
+
self.indent()
|
680 |
+
self.write("with %s" % ast.with_)
|
681 |
+
|
682 |
+
if ast.set is not None:
|
683 |
+
self.indent()
|
684 |
+
self.write("set %s" % ast.set)
|
685 |
+
|
686 |
+
if hasattr(ast, "item_arguments"):
|
687 |
+
item_arguments = ast.item_arguments
|
688 |
+
else:
|
689 |
+
item_arguments = [None] * len(ast.items)
|
690 |
+
|
691 |
+
for (label, condition, block), arguments in zip(ast.items, item_arguments):
|
692 |
+
if self.translator:
|
693 |
+
label = self.translator.strings.get(label, label)
|
694 |
+
|
695 |
+
state = None
|
696 |
+
|
697 |
+
# if the condition is a unicode subclass with a "linenumber" attribute it was script.
|
698 |
+
# If it isn't ren'py used to insert a "True" string. This string used to be of type str
|
699 |
+
# but nowadays it's of time unicode, just not of type PyExpr
|
700 |
+
if isinstance(condition, unicode) and hasattr(condition, "linenumber"):
|
701 |
+
if self.say_inside_menu is not None and condition.linenumber > self.linenumber + 1:
|
702 |
+
# The easy case: we know the line number that the menu item is on, because the condition tells us
|
703 |
+
# So we put the say statement here if there's room for it, or don't if there's not
|
704 |
+
self.print_say_inside_menu()
|
705 |
+
self.advance_to_line(condition.linenumber)
|
706 |
+
elif self.say_inside_menu is not None:
|
707 |
+
# The hard case: we don't know the line number that the menu item is on
|
708 |
+
# So try to put it in, but be prepared to back it out if that puts us behind on the line number
|
709 |
+
state = self.save_state()
|
710 |
+
self.most_lines_behind = self.last_lines_behind
|
711 |
+
self.print_say_inside_menu()
|
712 |
+
|
713 |
+
self.print_menu_item(label, condition, block, arguments)
|
714 |
+
|
715 |
+
if state is not None:
|
716 |
+
if self.most_lines_behind > state[7]: # state[7] is the saved value of self.last_lines_behind
|
717 |
+
# We tried to print the say statement that's inside the menu, but it didn't fit here
|
718 |
+
# Undo it and print this item again without it. We'll fit it in later
|
719 |
+
self.rollback_state(state)
|
720 |
+
self.print_menu_item(label, condition, block, arguments)
|
721 |
+
else:
|
722 |
+
self.most_lines_behind = max(state[6], self.most_lines_behind) # state[6] is the saved value of self.most_lines_behind
|
723 |
+
self.commit_state(state)
|
724 |
+
|
725 |
+
if self.say_inside_menu is not None:
|
726 |
+
# There was no room for this before any of the menu options, so it will just have to go after them all
|
727 |
+
self.print_say_inside_menu()
|
728 |
+
|
729 |
+
# Programming related functions
|
730 |
+
|
731 |
+
@dispatch(renpy.ast.Python)
|
732 |
+
def print_python(self, ast, early=False):
|
733 |
+
self.indent()
|
734 |
+
|
735 |
+
code = ast.code.source
|
736 |
+
if code[0] == '\n':
|
737 |
+
code = code[1:]
|
738 |
+
self.write("python")
|
739 |
+
if early:
|
740 |
+
self.write(" early")
|
741 |
+
if ast.hide:
|
742 |
+
self.write(" hide")
|
743 |
+
if hasattr(ast, "store") and ast.store != "store":
|
744 |
+
self.write(" in ")
|
745 |
+
# Strip prepended "store."
|
746 |
+
self.write(ast.store[6:])
|
747 |
+
self.write(":")
|
748 |
+
|
749 |
+
with self.increase_indent():
|
750 |
+
self.write_lines(split_logical_lines(code))
|
751 |
+
|
752 |
+
else:
|
753 |
+
self.write("$ %s" % code)
|
754 |
+
|
755 |
+
@dispatch(renpy.ast.EarlyPython)
|
756 |
+
def print_earlypython(self, ast):
|
757 |
+
self.print_python(ast, early=True)
|
758 |
+
|
759 |
+
@dispatch(renpy.ast.Define)
|
760 |
+
@dispatch(renpy.ast.Default)
|
761 |
+
def print_define(self, ast):
|
762 |
+
self.require_init()
|
763 |
+
self.indent()
|
764 |
+
if isinstance(ast, renpy.ast.Default):
|
765 |
+
name = "default"
|
766 |
+
else:
|
767 |
+
name = "define"
|
768 |
+
|
769 |
+
# If we have an implicit init block with a non-default priority, we need to store the priority here.
|
770 |
+
priority = ""
|
771 |
+
if isinstance(self.parent, renpy.ast.Init):
|
772 |
+
init = self.parent
|
773 |
+
if init.priority != self.init_offset and len(init.block) == 1 and not self.should_come_before(init, ast):
|
774 |
+
priority = " %d" % (init.priority - self.init_offset)
|
775 |
+
index = ""
|
776 |
+
if hasattr(ast, "index") and ast.index is not None:
|
777 |
+
index = "[%s]" % ast.index.source
|
778 |
+
if not hasattr(ast, "store") or ast.store == "store":
|
779 |
+
self.write("%s%s %s%s = %s" % (name, priority, ast.varname, index, ast.code.source))
|
780 |
+
else:
|
781 |
+
self.write("%s%s %s.%s%s = %s" % (name, priority, ast.store[6:], ast.varname, index, ast.code.source))
|
782 |
+
|
783 |
+
# Specials
|
784 |
+
|
785 |
+
# Returns whether a Say statement immediately preceding a Menu statement
|
786 |
+
# actually belongs inside of the Menu statement.
|
787 |
+
def say_belongs_to_menu(self, say, menu):
|
788 |
+
return (not say.interact and say.who is not None and
|
789 |
+
say.with_ is None and
|
790 |
+
(not hasattr(say, "attributes") or say.attributes is None) and
|
791 |
+
isinstance(menu, renpy.ast.Menu) and
|
792 |
+
menu.items[0][2] is not None and
|
793 |
+
not self.should_come_before(say, menu))
|
794 |
+
|
795 |
+
@dispatch(renpy.ast.Say)
|
796 |
+
def print_say(self, ast, inmenu=False):
|
797 |
+
if (not inmenu and self.index + 1 < len(self.block) and
|
798 |
+
self.say_belongs_to_menu(ast, self.block[self.index + 1])):
|
799 |
+
self.say_inside_menu = ast
|
800 |
+
return
|
801 |
+
self.indent()
|
802 |
+
self.write(say_get_code(ast, inmenu))
|
803 |
+
|
804 |
+
@dispatch(renpy.ast.UserStatement)
|
805 |
+
def print_userstatement(self, ast):
|
806 |
+
self.indent()
|
807 |
+
self.write(ast.line)
|
808 |
+
|
809 |
+
if hasattr(ast, "block") and ast.block:
|
810 |
+
with self.increase_indent():
|
811 |
+
self.print_lex(ast.block)
|
812 |
+
|
813 |
+
def print_lex(self, lex):
|
814 |
+
for file, linenumber, content, block in lex:
|
815 |
+
self.advance_to_line(linenumber)
|
816 |
+
self.indent()
|
817 |
+
self.write(content)
|
818 |
+
if block:
|
819 |
+
with self.increase_indent():
|
820 |
+
self.print_lex(block)
|
821 |
+
|
822 |
+
@dispatch(renpy.ast.Style)
|
823 |
+
def print_style(self, ast):
|
824 |
+
self.require_init()
|
825 |
+
keywords = {ast.linenumber: WordConcatenator(False, True)}
|
826 |
+
|
827 |
+
# These don't store a line number, so just put them on the first line
|
828 |
+
if ast.parent is not None:
|
829 |
+
keywords[ast.linenumber].append("is %s" % ast.parent)
|
830 |
+
if ast.clear:
|
831 |
+
keywords[ast.linenumber].append("clear")
|
832 |
+
if ast.take is not None:
|
833 |
+
keywords[ast.linenumber].append("take %s" % ast.take)
|
834 |
+
for delname in ast.delattr:
|
835 |
+
keywords[ast.linenumber].append("del %s" % delname)
|
836 |
+
|
837 |
+
# These do store a line number
|
838 |
+
if ast.variant is not None:
|
839 |
+
if ast.variant.linenumber not in keywords:
|
840 |
+
keywords[ast.variant.linenumber] = WordConcatenator(False)
|
841 |
+
keywords[ast.variant.linenumber].append("variant %s" % ast.variant)
|
842 |
+
for key, value in ast.properties.iteritems():
|
843 |
+
if value.linenumber not in keywords:
|
844 |
+
keywords[value.linenumber] = WordConcatenator(False)
|
845 |
+
keywords[value.linenumber].append("%s %s" % (key, value))
|
846 |
+
|
847 |
+
keywords = sorted([(k, v.join()) for k, v in keywords.items()],
|
848 |
+
key=itemgetter(0))
|
849 |
+
self.indent()
|
850 |
+
self.write("style %s" % ast.style_name)
|
851 |
+
if keywords[0][1]:
|
852 |
+
self.write(" %s" % keywords[0][1])
|
853 |
+
if len(keywords) > 1:
|
854 |
+
self.write(":")
|
855 |
+
with self.increase_indent():
|
856 |
+
for i in keywords[1:]:
|
857 |
+
self.advance_to_line(i[0])
|
858 |
+
self.indent()
|
859 |
+
self.write(i[1])
|
860 |
+
|
861 |
+
# Translation functions
|
862 |
+
|
863 |
+
@dispatch(renpy.ast.Translate)
|
864 |
+
def print_translate(self, ast):
|
865 |
+
self.indent()
|
866 |
+
self.write("translate %s %s:" % (ast.language or "None", ast.identifier))
|
867 |
+
|
868 |
+
self.print_nodes(ast.block, 1)
|
869 |
+
|
870 |
+
@dispatch(renpy.ast.EndTranslate)
|
871 |
+
def print_endtranslate(self, ast):
|
872 |
+
# an implicitly added node which does nothing...
|
873 |
+
pass
|
874 |
+
|
875 |
+
@dispatch(renpy.ast.TranslateString)
|
876 |
+
def print_translatestring(self, ast):
|
877 |
+
self.require_init()
|
878 |
+
# Was the last node a translatestrings node?
|
879 |
+
if not(self.index and
|
880 |
+
isinstance(self.block[self.index - 1], renpy.ast.TranslateString) and
|
881 |
+
self.block[self.index - 1].language == ast.language):
|
882 |
+
self.indent()
|
883 |
+
self.write("translate %s strings:" % ast.language or "None")
|
884 |
+
|
885 |
+
# TranslateString's linenumber refers to the line with "old", not to the
|
886 |
+
# line with "translate %s strings:"
|
887 |
+
with self.increase_indent():
|
888 |
+
self.advance_to_line(ast.linenumber)
|
889 |
+
self.indent()
|
890 |
+
self.write('old "%s"' % string_escape(ast.old))
|
891 |
+
if hasattr(ast, 'newloc'):
|
892 |
+
self.advance_to_line(ast.newloc[1])
|
893 |
+
self.indent()
|
894 |
+
self.write('new "%s"' % string_escape(ast.new))
|
895 |
+
|
896 |
+
@dispatch(renpy.ast.TranslateBlock)
|
897 |
+
@dispatch(renpy.ast.TranslateEarlyBlock)
|
898 |
+
def print_translateblock(self, ast):
|
899 |
+
self.indent()
|
900 |
+
self.write("translate %s " % (ast.language or "None"))
|
901 |
+
|
902 |
+
self.skip_indent_until_write = True
|
903 |
+
|
904 |
+
in_init = self.in_init
|
905 |
+
if len(ast.block) == 1 and isinstance(ast.block[0], (renpy.ast.Python, renpy.ast.Style)):
|
906 |
+
# Ren'Py counts the TranslateBlock from "translate python" and "translate style" as an Init.
|
907 |
+
self.in_init = True
|
908 |
+
try:
|
909 |
+
self.print_nodes(ast.block)
|
910 |
+
finally:
|
911 |
+
self.in_init = in_init
|
912 |
+
|
913 |
+
# Screens
|
914 |
+
|
915 |
+
@dispatch(renpy.ast.Screen)
|
916 |
+
def print_screen(self, ast):
|
917 |
+
self.require_init()
|
918 |
+
screen = ast.screen
|
919 |
+
if isinstance(screen, renpy.screenlang.ScreenLangScreen):
|
920 |
+
self.linenumber = screendecompiler.pprint(self.out_file, screen, self.indent_level,
|
921 |
+
self.linenumber,
|
922 |
+
self.decompile_python,
|
923 |
+
self.skip_indent_until_write,
|
924 |
+
self.printlock)
|
925 |
+
self.skip_indent_until_write = False
|
926 |
+
|
927 |
+
elif isinstance(screen, renpy.sl2.slast.SLScreen):
|
928 |
+
def print_atl_callback(linenumber, indent_level, atl):
|
929 |
+
old_linenumber = self.linenumber
|
930 |
+
self.linenumber = linenumber
|
931 |
+
with self.increase_indent(indent_level - self.indent_level):
|
932 |
+
self.print_atl(atl)
|
933 |
+
new_linenumber = self.linenumber
|
934 |
+
self.linenumber = old_linenumber
|
935 |
+
return new_linenumber
|
936 |
+
|
937 |
+
self.linenumber = sl2decompiler.pprint(self.out_file, screen, print_atl_callback,
|
938 |
+
self.indent_level,
|
939 |
+
self.linenumber,
|
940 |
+
self.skip_indent_until_write,
|
941 |
+
self.printlock,
|
942 |
+
self.tag_outside_block)
|
943 |
+
self.skip_indent_until_write = False
|
944 |
+
else:
|
945 |
+
self.print_unknown(screen)
|
946 |
+
|
947 |
+
# Testcases
|
948 |
+
|
949 |
+
@dispatch(renpy.ast.Testcase)
|
950 |
+
def print_testcase(self, ast):
|
951 |
+
self.require_init()
|
952 |
+
self.indent()
|
953 |
+
self.write('testcase %s:' % ast.label)
|
954 |
+
self.linenumber = testcasedecompiler.pprint(self.out_file, ast.test.block, self.indent_level + 1,
|
955 |
+
self.linenumber,
|
956 |
+
self.skip_indent_until_write,
|
957 |
+
self.printlock)
|
958 |
+
self.skip_indent_until_write = False
|
renpy/rpycdec/rpycdecdata/decompiler/__init__.pyo
ADDED
Binary file (37.9 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/astdump.py
ADDED
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2013 CensoredUsername
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
from __future__ import unicode_literals
|
22 |
+
|
23 |
+
import sys
|
24 |
+
import inspect
|
25 |
+
import codegen
|
26 |
+
import ast as py_ast
|
27 |
+
import renpy
|
28 |
+
|
29 |
+
def pprint(out_file, ast, decompile_python=False, comparable=False, no_pyexpr=False):
|
30 |
+
# The main function of this module, a wrapper which sets
|
31 |
+
# the config and creates the AstDumper instance
|
32 |
+
AstDumper(out_file, decompile_python=decompile_python, comparable=comparable, no_pyexpr=no_pyexpr).dump(ast)
|
33 |
+
|
34 |
+
class AstDumper(object):
|
35 |
+
"""
|
36 |
+
An object which handles the walking of a tree of python objects
|
37 |
+
it will create a human-readable representation of all interesting
|
38 |
+
attributes and write this to a given stream
|
39 |
+
"""
|
40 |
+
MAP_OPEN = {list: '[', tuple: '(', set: '{', frozenset: 'frozenset({'}
|
41 |
+
MAP_CLOSE = {list: ']', tuple: ')', set: '}', frozenset: '})'}
|
42 |
+
|
43 |
+
def __init__(self, out_file=None, decompile_python=False, no_pyexpr=False,
|
44 |
+
comparable=False, indentation=u' '):
|
45 |
+
self.indentation = indentation
|
46 |
+
self.out_file = out_file or sys.stdout
|
47 |
+
self.decompile_python = decompile_python
|
48 |
+
self.comparable = comparable
|
49 |
+
self.no_pyexpr = no_pyexpr
|
50 |
+
|
51 |
+
def dump(self, ast):
|
52 |
+
self.linenumber = 1
|
53 |
+
self.indent = 0
|
54 |
+
self.passed = [] # We'll keep a stack of objects which we've traversed here so we don't recurse endlessly on circular references
|
55 |
+
self.passed_where = []
|
56 |
+
self.print_ast(ast)
|
57 |
+
|
58 |
+
def print_ast(self, ast):
|
59 |
+
# Decides which function should be used to print the given ast object.
|
60 |
+
try:
|
61 |
+
i = self.passed.index(ast)
|
62 |
+
except ValueError:
|
63 |
+
pass
|
64 |
+
else:
|
65 |
+
self.p('<circular reference to object on line %d>' % self.passed_where[i])
|
66 |
+
return
|
67 |
+
self.passed.append(ast)
|
68 |
+
self.passed_where.append(self.linenumber)
|
69 |
+
if isinstance(ast, (list, tuple, set, frozenset)):
|
70 |
+
self.print_list(ast)
|
71 |
+
elif isinstance(ast, renpy.ast.PyExpr):
|
72 |
+
self.print_pyexpr(ast)
|
73 |
+
elif isinstance(ast, dict):
|
74 |
+
self.print_dict(ast)
|
75 |
+
elif isinstance(ast, (str, unicode)):
|
76 |
+
self.print_string(ast)
|
77 |
+
elif isinstance(ast, (int, long, bool)) or ast is None:
|
78 |
+
self.print_other(ast)
|
79 |
+
elif inspect.isclass(ast):
|
80 |
+
self.print_class(ast)
|
81 |
+
elif isinstance(ast, object):
|
82 |
+
self.print_object(ast)
|
83 |
+
else:
|
84 |
+
self.print_other(ast)
|
85 |
+
self.passed_where.pop()
|
86 |
+
self.passed.pop()
|
87 |
+
|
88 |
+
def print_list(self, ast):
|
89 |
+
# handles the printing of simple containers of N elements.
|
90 |
+
if type(ast) not in (list, tuple, set, frozenset):
|
91 |
+
self.p(repr(type(ast)))
|
92 |
+
|
93 |
+
for k in (list, tuple, set, frozenset):
|
94 |
+
if isinstance(ast, k):
|
95 |
+
klass = k
|
96 |
+
|
97 |
+
else:
|
98 |
+
klass = ast.__class__
|
99 |
+
|
100 |
+
self.p(self.MAP_OPEN[klass])
|
101 |
+
|
102 |
+
self.ind(1, ast)
|
103 |
+
for i, obj in enumerate(ast):
|
104 |
+
self.print_ast(obj)
|
105 |
+
if i+1 != len(ast):
|
106 |
+
self.p(',')
|
107 |
+
self.ind()
|
108 |
+
self.ind(-1, ast)
|
109 |
+
self.p(self.MAP_CLOSE[klass])
|
110 |
+
|
111 |
+
def print_dict(self, ast):
|
112 |
+
# handles the printing of dictionaries
|
113 |
+
if type(ast) != dict:
|
114 |
+
self.p(repr(type(ast)))
|
115 |
+
|
116 |
+
self.p('{')
|
117 |
+
|
118 |
+
self.ind(1, ast)
|
119 |
+
for i, key in enumerate(ast):
|
120 |
+
self.print_ast(key)
|
121 |
+
self.p(': ')
|
122 |
+
self.print_ast(ast[key])
|
123 |
+
if i+1 != len(ast):
|
124 |
+
self.p(',')
|
125 |
+
self.ind()
|
126 |
+
self.ind(-1, ast)
|
127 |
+
self.p('}')
|
128 |
+
|
129 |
+
def should_print_key(self, ast, key):
|
130 |
+
if key.startswith('_') or not hasattr(ast, key) or inspect.isroutine(getattr(ast, key)):
|
131 |
+
return False
|
132 |
+
elif not self.comparable:
|
133 |
+
return True
|
134 |
+
elif key == 'serial':
|
135 |
+
ast.serial = 0
|
136 |
+
elif key == 'col_offset':
|
137 |
+
ast.col_offset = 0 # TODO maybe make this match?
|
138 |
+
elif key == 'name' and type(ast.name) == tuple:
|
139 |
+
name = ast.name[0]
|
140 |
+
if isinstance(name, unicode):
|
141 |
+
name = name.encode('utf-8')
|
142 |
+
ast.name = (name.split(b'/')[-1], 0, 0)
|
143 |
+
elif key == 'location' and type(ast.location) == tuple:
|
144 |
+
if len(ast.location) == 4:
|
145 |
+
ast.location = (ast.location[0].split('/')[-1].split('\\')[-1], ast.location[1], ast.location[2], 0)
|
146 |
+
elif len(ast.location) == 3:
|
147 |
+
ast.location = (ast.location[0].split('/')[-1].split('\\')[-1], ast.location[1], 0)
|
148 |
+
elif len(ast.location) == 2:
|
149 |
+
ast.location = (ast.location[0].split('/')[-1].split('\\')[-1], ast.location[1])
|
150 |
+
elif key == 'loc' and type(ast.loc) == tuple:
|
151 |
+
ast.loc = (ast.loc[0].split('/')[-1].split('\\')[-1], ast.loc[1])
|
152 |
+
elif key == 'filename':
|
153 |
+
ast.filename = ast.filename.split('/')[-1].split('\\')[-1]
|
154 |
+
elif (key == 'parameters' and ast.parameters is None and
|
155 |
+
isinstance(ast, renpy.screenlang.ScreenLangScreen)):
|
156 |
+
# When no parameters exist, some versions of Ren'Py set parameters
|
157 |
+
# to None and some don't set it at all.
|
158 |
+
return False
|
159 |
+
elif (key == 'hide' and ast.hide == False and
|
160 |
+
(isinstance(ast, renpy.ast.Python) or
|
161 |
+
isinstance(ast, renpy.ast.Label))):
|
162 |
+
# When hide isn't set, some versions of Ren'Py set it to False and
|
163 |
+
# some don't set it at all.
|
164 |
+
return False
|
165 |
+
elif (key == 'attributes' and ast.attributes is None and
|
166 |
+
isinstance(ast, renpy.ast.Say)):
|
167 |
+
# When no attributes are set, some versions of Ren'Py set it to None
|
168 |
+
# and some don't set it at all.
|
169 |
+
return False
|
170 |
+
elif (key == 'temporary_attributes' and ast.temporary_attributes is None and
|
171 |
+
isinstance(ast, renpy.ast.Say)):
|
172 |
+
# When no temporary attributes are set, some versions of Ren'Py set
|
173 |
+
# it to None and some don't set it at all.
|
174 |
+
return False
|
175 |
+
elif (key == 'rollback' and ast.rollback == 'normal' and
|
176 |
+
isinstance(ast, renpy.ast.Say)):
|
177 |
+
# When rollback is normal, some versions of Ren'Py set it to 'normal'
|
178 |
+
# and some don't set it at all.
|
179 |
+
return False
|
180 |
+
elif (key == 'block' and ast.block == [] and
|
181 |
+
isinstance(ast, renpy.ast.UserStatement)):
|
182 |
+
# When there's no block, some versions of Ren'Py set it to None
|
183 |
+
# and some don't set it at all.
|
184 |
+
return False
|
185 |
+
elif (key == 'store' and ast.store == 'store' and
|
186 |
+
isinstance(ast, renpy.ast.Python)):
|
187 |
+
# When a store isn't specified, some versions of Ren'Py set it to
|
188 |
+
# "store" and some don't set it at all.
|
189 |
+
return False
|
190 |
+
elif key == 'translatable' and isinstance(ast, renpy.ast.UserStatement):
|
191 |
+
# Old versions of Ren'Py didn't have this attribute, and it's not
|
192 |
+
# controllable from the source.
|
193 |
+
return False
|
194 |
+
elif key == 'hotspot' and isinstance(ast, renpy.sl2.slast.SLDisplayable):
|
195 |
+
# Old versions of Ren'Py didn't have this attribute, and it's not
|
196 |
+
# controllable from the source.
|
197 |
+
return False
|
198 |
+
return True
|
199 |
+
|
200 |
+
def print_object(self, ast):
|
201 |
+
# handles the printing of anything unknown which inherts from object.
|
202 |
+
# prints the values of relevant attributes in a dictionary-like way
|
203 |
+
# it will not print anything which is a bound method or starts with a _
|
204 |
+
self.p('<')
|
205 |
+
self.p(str(ast.__class__)[8:-2] if hasattr(ast, '__class__') else str(ast))
|
206 |
+
|
207 |
+
if isinstance(ast, py_ast.Module) and self.decompile_python:
|
208 |
+
self.p('.code = ')
|
209 |
+
self.print_ast(codegen.to_source(ast, unicode(self.indentation)))
|
210 |
+
self.p('>')
|
211 |
+
return
|
212 |
+
|
213 |
+
keys = list(i for i in dir(ast) if self.should_print_key(ast, i))
|
214 |
+
if keys:
|
215 |
+
self.p(' ')
|
216 |
+
self.ind(1, keys)
|
217 |
+
for i, key in enumerate(keys):
|
218 |
+
self.p('.')
|
219 |
+
self.p(str(key))
|
220 |
+
self.p(' = ')
|
221 |
+
self.print_ast(getattr(ast, key))
|
222 |
+
if i+1 != len(keys):
|
223 |
+
self.p(',')
|
224 |
+
self.ind()
|
225 |
+
self.ind(-1, keys)
|
226 |
+
self.p('>')
|
227 |
+
|
228 |
+
def print_pyexpr(self, ast):
|
229 |
+
if not self.no_pyexpr:
|
230 |
+
self.print_object(ast)
|
231 |
+
self.p(' = ')
|
232 |
+
self.print_string(ast)
|
233 |
+
|
234 |
+
def print_class(self, ast):
|
235 |
+
# handles the printing of classes
|
236 |
+
self.p('<class ')
|
237 |
+
self.p(str(ast)[8:-2])
|
238 |
+
self.p('>')
|
239 |
+
|
240 |
+
def print_string(self, ast):
|
241 |
+
# prints the representation of a string. If there are newlines in this string,
|
242 |
+
# it will print it as a docstring.
|
243 |
+
if b'\n' in ast:
|
244 |
+
astlist = ast.split(b'\n')
|
245 |
+
if isinstance(ast, unicode):
|
246 |
+
self.p('u')
|
247 |
+
self.p('"""')
|
248 |
+
self.p(self.escape_string(astlist.pop(0)))
|
249 |
+
for i, item in enumerate(astlist):
|
250 |
+
self.p('\n')
|
251 |
+
self.p(self.escape_string(item))
|
252 |
+
self.p('"""')
|
253 |
+
self.ind()
|
254 |
+
|
255 |
+
else:
|
256 |
+
self.p(repr(ast))
|
257 |
+
|
258 |
+
def escape_string(self, string):
|
259 |
+
# essentially the representation of a string without the surrounding quotes
|
260 |
+
if isinstance(string, unicode):
|
261 |
+
return repr(string)[2:-1]
|
262 |
+
elif isinstance(string, str):
|
263 |
+
return repr(string)[1:-1]
|
264 |
+
else:
|
265 |
+
return string
|
266 |
+
|
267 |
+
def print_other(self, ast):
|
268 |
+
# used as a last fallback
|
269 |
+
self.p(repr(ast))
|
270 |
+
|
271 |
+
def ind(self, diff_indent=0, ast=None):
|
272 |
+
# print a newline and indent. diff_indent represents the difference in indentation
|
273 |
+
# compared to the last line. it will chech the length of ast to determine if it
|
274 |
+
# shouldn't indent in case there's only one or zero objects in this object to print
|
275 |
+
if ast is None or len(ast) > 1:
|
276 |
+
self.indent += diff_indent
|
277 |
+
self.p(u'\n' + self.indentation * self.indent)
|
278 |
+
|
279 |
+
def p(self, string):
|
280 |
+
# write the string to the stream
|
281 |
+
string = unicode(string)
|
282 |
+
self.linenumber += string.count('\n')
|
283 |
+
self.out_file.write(string)
|
renpy/rpycdec/rpycdecdata/decompiler/astdump.pyo
ADDED
Binary file (10.9 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/codegen.py
ADDED
@@ -0,0 +1,1102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# License
|
2 |
+
# Copyright (c) 2008, Armin Ronacher
|
3 |
+
# All rights reserved.
|
4 |
+
|
5 |
+
# Redistribution and use in source and binary forms, with or without modification,
|
6 |
+
# are permitted provided that the following conditions are met:
|
7 |
+
|
8 |
+
# - Redistributions of source code must retain the above copyright notice, this list of
|
9 |
+
# conditions and the following disclaimer.
|
10 |
+
# - Redistributions in binary form must reproduce the above copyright notice, this list of
|
11 |
+
# conditions and the following disclaimer in the documentation and/or other materials
|
12 |
+
# provided with the distribution.
|
13 |
+
# - Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to
|
14 |
+
# endorse or promote products derived from this software without specific prior written
|
15 |
+
# permission.
|
16 |
+
|
17 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
|
18 |
+
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
19 |
+
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
|
20 |
+
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
21 |
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
22 |
+
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
|
23 |
+
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
|
24 |
+
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
25 |
+
|
26 |
+
# Taken from http://github.com/jonathaneunice/codegen
|
27 |
+
|
28 |
+
"""
|
29 |
+
codegen
|
30 |
+
~~~~~~~
|
31 |
+
|
32 |
+
Extension to ast that allow ast -> python code generation.
|
33 |
+
|
34 |
+
:copyright: Copyright 2008 by Armin Ronacher.
|
35 |
+
:license: BSD.
|
36 |
+
"""
|
37 |
+
|
38 |
+
import sys
|
39 |
+
PY3 = sys.version_info >= (3, 0)
|
40 |
+
# These might not exist, so we put them equal to NoneType
|
41 |
+
Try = TryExcept = TryFinally = YieldFrom = MatMult = Await = type(None)
|
42 |
+
|
43 |
+
from ast import *
|
44 |
+
|
45 |
+
class Sep(object):
|
46 |
+
# Performs the common pattern of returning a different symbol the first
|
47 |
+
# time the object is called
|
48 |
+
def __init__(self, last, first=''):
|
49 |
+
self.last = last
|
50 |
+
self.first = first
|
51 |
+
self.begin = True
|
52 |
+
def __call__(self):
|
53 |
+
if self.begin:
|
54 |
+
self.begin = False
|
55 |
+
return self.first
|
56 |
+
return self.last
|
57 |
+
|
58 |
+
def to_source(node, indent_with=' ' * 4, add_line_information=False, correct_line_numbers=False):
|
59 |
+
"""This function can convert a node tree back into python sourcecode.
|
60 |
+
This is useful for debugging purposes, especially if you're dealing with
|
61 |
+
custom asts not generated by python itself.
|
62 |
+
|
63 |
+
It could be that the sourcecode is evaluable when the AST itself is not
|
64 |
+
compilable / evaluable. The reason for this is that the AST contains some
|
65 |
+
more data than regular sourcecode does, which is dropped during
|
66 |
+
conversion.
|
67 |
+
|
68 |
+
Each level of indentation is replaced with `indent_with`. Per default this
|
69 |
+
parameter is equal to four spaces as suggested by PEP 8, but it might be
|
70 |
+
adjusted to match the application's styleguide.
|
71 |
+
|
72 |
+
If `add_line_information` is set to `True` comments for the line numbers
|
73 |
+
of the nodes are added to the output. This can be used to spot wrong line
|
74 |
+
number information of statement nodes.
|
75 |
+
"""
|
76 |
+
if correct_line_numbers:
|
77 |
+
if hasattr(node, 'lineno'):
|
78 |
+
return SourceGenerator(indent_with, add_line_information, True, node.lineno).process(node)
|
79 |
+
else:
|
80 |
+
return SourceGenerator(indent_with, add_line_information, True).process(node)
|
81 |
+
else:
|
82 |
+
return SourceGenerator(indent_with, add_line_information).process(node)
|
83 |
+
|
84 |
+
|
85 |
+
class SourceGenerator(NodeVisitor):
|
86 |
+
"""This visitor is able to transform a well formed syntax tree into python
|
87 |
+
sourcecode. For more details have a look at the docstring of the
|
88 |
+
`node_to_source` function.
|
89 |
+
"""
|
90 |
+
|
91 |
+
COMMA = ', '
|
92 |
+
COLON = ': '
|
93 |
+
ASSIGN = ' = '
|
94 |
+
SEMICOLON = '; '
|
95 |
+
ARROW = ' -> '
|
96 |
+
|
97 |
+
BOOLOP_SYMBOLS = {
|
98 |
+
And: (' and ', 5),
|
99 |
+
Or: (' or ', 4)
|
100 |
+
}
|
101 |
+
|
102 |
+
BINOP_SYMBOLS = {
|
103 |
+
Add: (' + ', 12),
|
104 |
+
Sub: (' - ', 12),
|
105 |
+
Mult: (' * ', 13),
|
106 |
+
MatMult: (' @ ', 13),
|
107 |
+
Div: (' / ', 13),
|
108 |
+
FloorDiv: (' // ', 13),
|
109 |
+
Mod: (' % ', 13),
|
110 |
+
Pow: (' ** ', 15),
|
111 |
+
LShift: (' << ', 11),
|
112 |
+
RShift: (' >> ', 11),
|
113 |
+
BitOr: (' | ', 8),
|
114 |
+
BitAnd: (' & ', 10),
|
115 |
+
BitXor: (' ^ ', 9)
|
116 |
+
}
|
117 |
+
|
118 |
+
CMPOP_SYMBOLS = {
|
119 |
+
Eq: (' == ', 7),
|
120 |
+
Gt: (' > ', 7),
|
121 |
+
GtE: (' >= ', 7),
|
122 |
+
In: (' in ', 7),
|
123 |
+
Is: (' is ', 7),
|
124 |
+
IsNot: (' is not ', 7),
|
125 |
+
Lt: (' < ', 7),
|
126 |
+
LtE: (' <= ', 7),
|
127 |
+
NotEq: (' != ', 7),
|
128 |
+
NotIn: (' not in ', 7)
|
129 |
+
}
|
130 |
+
|
131 |
+
UNARYOP_SYMBOLS = {
|
132 |
+
Invert: ('~', 14),
|
133 |
+
Not: ('not ', 6),
|
134 |
+
UAdd: ('+', 14),
|
135 |
+
USub: ('-', 14)
|
136 |
+
}
|
137 |
+
|
138 |
+
BLOCK_NODES = (If, For, While, With, Try, TryExcept, TryFinally,
|
139 |
+
FunctionDef, ClassDef)
|
140 |
+
|
141 |
+
def __init__(self, indent_with, add_line_information=False, correct_line_numbers=False, line_number=1):
|
142 |
+
self.result = []
|
143 |
+
self.indent_with = indent_with
|
144 |
+
self.add_line_information = add_line_information
|
145 |
+
self.indentation = 0
|
146 |
+
self.new_lines = 0
|
147 |
+
|
148 |
+
# precedence_stack: what precedence level are we on, could we safely newline before and is this operator left-to-right
|
149 |
+
self.precedence_stack = [[0, False, None]]
|
150 |
+
|
151 |
+
self.correct_line_numbers = correct_line_numbers
|
152 |
+
# The current line number we *think* we are on. As in it's most likely
|
153 |
+
# the line number of the last node we passed which can differ when
|
154 |
+
# the ast is broken
|
155 |
+
self.line_number = line_number
|
156 |
+
# Can we insert a newline here without having to escape it?
|
157 |
+
# (are we between delimiting characters)
|
158 |
+
self.can_newline = False
|
159 |
+
# after a colon, we don't have to print a semi colon. set to 1 when self.body() is called,
|
160 |
+
# set to 2 or 0 when it's actually used. set to 0 at the end of the body
|
161 |
+
self.after_colon = 0
|
162 |
+
# reset by a call to self.newline, set by the first call to write() afterwards
|
163 |
+
# determines if we have to print the newlines and indent
|
164 |
+
self.indented = False
|
165 |
+
# the amount of newlines to be printed
|
166 |
+
self.newlines = 0
|
167 |
+
# force the printing of a proper newline (and not a semicolon)
|
168 |
+
self.force_newline = False
|
169 |
+
|
170 |
+
def process(self, node):
|
171 |
+
self.visit(node)
|
172 |
+
result = ''.join(self.result)
|
173 |
+
self.result = []
|
174 |
+
return result
|
175 |
+
|
176 |
+
# Precedence management
|
177 |
+
|
178 |
+
def prec_start(self, value, ltr=None):
|
179 |
+
newline = self.can_newline
|
180 |
+
if value < self.precedence_stack[-1][0]:
|
181 |
+
self.write('(')
|
182 |
+
self.can_newline = True
|
183 |
+
if ltr == False:
|
184 |
+
value += 1
|
185 |
+
self.precedence_stack.append([value, newline, ltr])
|
186 |
+
|
187 |
+
def prec_middle(self, level=None):
|
188 |
+
if level is not None:
|
189 |
+
self.precedence_stack[-1][0] = level
|
190 |
+
elif self.precedence_stack[-1][2]:
|
191 |
+
self.precedence_stack[-1][0] += 1
|
192 |
+
elif self.precedence_stack[-1][2] is False:
|
193 |
+
self.precedence_stack[-1][0] -= 1
|
194 |
+
|
195 |
+
def prec_end(self):
|
196 |
+
precedence, newline, ltr = self.precedence_stack.pop()
|
197 |
+
if ltr:
|
198 |
+
precedence -= 1
|
199 |
+
if precedence < self.precedence_stack[-1][0]:
|
200 |
+
self.write(')')
|
201 |
+
self.can_newline = newline
|
202 |
+
|
203 |
+
def paren_start(self, symbol='('):
|
204 |
+
self.precedence_stack.append([0, self.can_newline, None])
|
205 |
+
self.write(symbol)
|
206 |
+
self.can_newline = True
|
207 |
+
|
208 |
+
def paren_end(self, symbol=')'):
|
209 |
+
_, self.can_newline, _ = self.precedence_stack.pop()
|
210 |
+
self.write(symbol)
|
211 |
+
|
212 |
+
# convenience functions
|
213 |
+
|
214 |
+
def write(self, x):
|
215 |
+
# ignore empty writes
|
216 |
+
if not x:
|
217 |
+
return
|
218 |
+
|
219 |
+
# Before we write, we must check if newlines have been queued.
|
220 |
+
# If this is the case, we have to handle them properly
|
221 |
+
if self.correct_line_numbers:
|
222 |
+
if not self.indented:
|
223 |
+
self.new_lines = max(self.new_lines, 1 if self.force_newline else 0)
|
224 |
+
self.force_newline = False
|
225 |
+
|
226 |
+
if self.new_lines:
|
227 |
+
# we have new lines to print
|
228 |
+
if self.after_colon == 2:
|
229 |
+
self.result.append(';'+'\\\n' * self.new_lines)
|
230 |
+
else:
|
231 |
+
self.after_colon = 0
|
232 |
+
self.result.append('\n' * self.new_lines)
|
233 |
+
self.result.append(self.indent_with * self.indentation)
|
234 |
+
elif self.after_colon == 1:
|
235 |
+
# we're directly after a block-having statement and can write on the same line
|
236 |
+
self.after_colon = 2
|
237 |
+
self.result.append(' ')
|
238 |
+
elif self.result:
|
239 |
+
# we're after any statement. or at the start of the file
|
240 |
+
self.result.append(self.SEMICOLON)
|
241 |
+
self.indented = True
|
242 |
+
elif self.new_lines > 0:
|
243 |
+
if self.can_newline:
|
244 |
+
self.result.append('\n' * self.new_lines)
|
245 |
+
self.result.append(self.indent_with * (self.indentation + 1))
|
246 |
+
else:
|
247 |
+
self.result.append('\\\n' * self.new_lines)
|
248 |
+
self.result.append(self.indent_with * (self.indentation + 1))
|
249 |
+
self.new_lines = 0
|
250 |
+
|
251 |
+
|
252 |
+
elif self.new_lines:
|
253 |
+
# normal behaviour
|
254 |
+
self.result.append('\n' * self.new_lines)
|
255 |
+
self.result.append(self.indent_with * self.indentation)
|
256 |
+
self.new_lines = 0
|
257 |
+
self.result.append(x)
|
258 |
+
|
259 |
+
def newline(self, node=None, extra=0, force=False):
|
260 |
+
if not self.correct_line_numbers:
|
261 |
+
self.new_lines = max(self.new_lines, 1 + extra)
|
262 |
+
if not self.result:
|
263 |
+
self.new_lines = 0
|
264 |
+
if node is not None and self.add_line_information:
|
265 |
+
self.write('# line: %s' % node.lineno)
|
266 |
+
self.new_lines = 1
|
267 |
+
else:
|
268 |
+
if extra:
|
269 |
+
#Ignore extra
|
270 |
+
return
|
271 |
+
|
272 |
+
self.indented = False
|
273 |
+
|
274 |
+
if node is None:
|
275 |
+
# else/finally statement. insert one true newline. body is implicit
|
276 |
+
self.force_newline = True
|
277 |
+
self.new_lines += 1
|
278 |
+
self.line_number += 1
|
279 |
+
|
280 |
+
elif force:
|
281 |
+
# statement with a block: needs a true newline before it
|
282 |
+
self.force_newline = True
|
283 |
+
self.new_lines += node.lineno - self.line_number
|
284 |
+
self.line_number = node.lineno
|
285 |
+
|
286 |
+
else:
|
287 |
+
# block-less statement: needs a semicolon, colon, or newline in front of it
|
288 |
+
self.new_lines += node.lineno - self.line_number
|
289 |
+
self.line_number = node.lineno
|
290 |
+
|
291 |
+
def maybe_break(self, node):
|
292 |
+
if self.correct_line_numbers:
|
293 |
+
self.new_lines += node.lineno - self.line_number
|
294 |
+
self.line_number = node.lineno
|
295 |
+
|
296 |
+
def body(self, statements):
|
297 |
+
self.force_newline = any(isinstance(i, self.BLOCK_NODES) for i in statements)
|
298 |
+
self.indentation += 1
|
299 |
+
self.after_colon = 1
|
300 |
+
for stmt in statements:
|
301 |
+
self.visit(stmt)
|
302 |
+
self.indentation -= 1
|
303 |
+
self.force_newline = True
|
304 |
+
self.after_colon = 0 # do empty blocks even exist?
|
305 |
+
|
306 |
+
def body_or_else(self, node):
|
307 |
+
self.body(node.body)
|
308 |
+
if node.orelse:
|
309 |
+
self.newline()
|
310 |
+
self.write('else:')
|
311 |
+
self.body(node.orelse)
|
312 |
+
|
313 |
+
def visit_bare(self, node):
|
314 |
+
# this node is allowed to be a bare tuple
|
315 |
+
if isinstance(node, Tuple):
|
316 |
+
self.visit_Tuple(node, False)
|
317 |
+
else:
|
318 |
+
self.visit(node)
|
319 |
+
|
320 |
+
def visit_bareyield(self, node):
|
321 |
+
if isinstance(node, Yield):
|
322 |
+
self.visit_Yield(node, False)
|
323 |
+
elif isinstance(node, YieldFrom):
|
324 |
+
self.visit_YieldFrom(node, False)
|
325 |
+
else:
|
326 |
+
self.visit_bare(node)
|
327 |
+
|
328 |
+
def decorators(self, node):
|
329 |
+
for decorator in node.decorator_list:
|
330 |
+
self.newline(decorator, force=True)
|
331 |
+
self.write('@')
|
332 |
+
self.visit(decorator)
|
333 |
+
if node.decorator_list:
|
334 |
+
self.newline()
|
335 |
+
else:
|
336 |
+
self.newline(node, force=True)
|
337 |
+
|
338 |
+
# Module
|
339 |
+
def visit_Module(self, node):
|
340 |
+
self.generic_visit(node)
|
341 |
+
self.write('\n')
|
342 |
+
self.line_number += 1
|
343 |
+
|
344 |
+
# Statements
|
345 |
+
|
346 |
+
def visit_Assert(self, node):
|
347 |
+
self.newline(node)
|
348 |
+
self.write('assert ')
|
349 |
+
self.visit(node.test)
|
350 |
+
if node.msg:
|
351 |
+
self.write(self.COMMA)
|
352 |
+
self.visit(node.msg)
|
353 |
+
|
354 |
+
def visit_Assign(self, node):
|
355 |
+
self.newline(node)
|
356 |
+
for target in node.targets:
|
357 |
+
self.visit_bare(target)
|
358 |
+
self.write(self.ASSIGN)
|
359 |
+
self.visit_bareyield(node.value)
|
360 |
+
|
361 |
+
def visit_AugAssign(self, node):
|
362 |
+
self.newline(node)
|
363 |
+
self.visit_bare(node.target)
|
364 |
+
self.write(self.BINOP_SYMBOLS[type(node.op)][0].rstrip() + self.ASSIGN.lstrip())
|
365 |
+
self.visit_bareyield(node.value)
|
366 |
+
|
367 |
+
def visit_Await(self, node):
|
368 |
+
self.maybe_break(node)
|
369 |
+
self.prec_start(16, True)
|
370 |
+
self.prec_middle()
|
371 |
+
self.write('await ')
|
372 |
+
self.visit(node.value)
|
373 |
+
self.prec_end()
|
374 |
+
|
375 |
+
def visit_ImportFrom(self, node):
|
376 |
+
self.newline(node)
|
377 |
+
self.write('from ')
|
378 |
+
self.write('%s%s' % ('.' * node.level, node.module or ''))
|
379 |
+
self.write(' import ')
|
380 |
+
sep = Sep(self.COMMA)
|
381 |
+
for item in node.names:
|
382 |
+
self.write(sep())
|
383 |
+
self.visit(item)
|
384 |
+
|
385 |
+
def visit_Import(self, node):
|
386 |
+
self.newline(node)
|
387 |
+
self.write('import ')
|
388 |
+
sep = Sep(self.COMMA)
|
389 |
+
for item in node.names:
|
390 |
+
self.write(sep())
|
391 |
+
self.visit(item)
|
392 |
+
|
393 |
+
def visit_Exec(self, node):
|
394 |
+
self.newline(node)
|
395 |
+
self.write('exec ')
|
396 |
+
self.visit(node.body)
|
397 |
+
if node.globals:
|
398 |
+
self.write(' in ')
|
399 |
+
self.visit(node.globals)
|
400 |
+
if node.locals:
|
401 |
+
self.write(self.COMMA)
|
402 |
+
self.visit(node.locals)
|
403 |
+
|
404 |
+
def visit_Expr(self, node):
|
405 |
+
self.newline(node)
|
406 |
+
self.visit_bareyield(node.value)
|
407 |
+
|
408 |
+
def visit_AsyncFunctionDef(self, node):
|
409 |
+
self.visit_FunctionDef(node, True)
|
410 |
+
|
411 |
+
def visit_FunctionDef(self, node, async=False):
|
412 |
+
self.newline(extra=1)
|
413 |
+
# first decorator line number will be used
|
414 |
+
self.decorators(node)
|
415 |
+
if async:
|
416 |
+
self.write('async ')
|
417 |
+
self.write('def ')
|
418 |
+
self.write(node.name)
|
419 |
+
self.paren_start()
|
420 |
+
self.visit_arguments(node.args)
|
421 |
+
self.paren_end()
|
422 |
+
if hasattr(node, 'returns') and node.returns is not None:
|
423 |
+
self.write(self.ARROW)
|
424 |
+
self.visit(node.returns)
|
425 |
+
self.write(':')
|
426 |
+
self.body(node.body)
|
427 |
+
|
428 |
+
def visit_arguments(self, node):
|
429 |
+
sep = Sep(self.COMMA)
|
430 |
+
padding = [None] * (len(node.args) - len(node.defaults))
|
431 |
+
if hasattr(node, 'kwonlyargs'):
|
432 |
+
for arg, default in zip(node.args, padding + node.defaults):
|
433 |
+
self.write(sep())
|
434 |
+
self.visit(arg)
|
435 |
+
if default is not None:
|
436 |
+
self.write('=')
|
437 |
+
self.visit(default)
|
438 |
+
if node.vararg is not None:
|
439 |
+
self.write(sep())
|
440 |
+
if hasattr(node, 'varargannotation'):
|
441 |
+
if node.varargannotation is None:
|
442 |
+
self.write('*' + node.vararg)
|
443 |
+
else:
|
444 |
+
self.maybe_break(node.varargannotation)
|
445 |
+
self.write('*' + node.vararg)
|
446 |
+
self.write(self.COLON)
|
447 |
+
self.visit(node.varargannotation)
|
448 |
+
else:
|
449 |
+
self.maybe_break(node.vararg)
|
450 |
+
self.write('*')
|
451 |
+
self.visit(node.vararg)
|
452 |
+
elif node.kwonlyargs:
|
453 |
+
self.write(sep() + '*')
|
454 |
+
|
455 |
+
for arg, default in zip(node.kwonlyargs, node.kw_defaults):
|
456 |
+
self.write(sep())
|
457 |
+
self.visit(arg)
|
458 |
+
if default is not None:
|
459 |
+
self.write('=')
|
460 |
+
self.visit(default)
|
461 |
+
if node.kwarg is not None:
|
462 |
+
self.write(sep())
|
463 |
+
if hasattr(node, 'kwargannotation'):
|
464 |
+
if node.kwargannotation is None:
|
465 |
+
self.write('**' + node.kwarg)
|
466 |
+
else:
|
467 |
+
self.maybe_break(node.kwargannotation)
|
468 |
+
self.write('**' + node.kwarg)
|
469 |
+
self.write(self.COLON)
|
470 |
+
self.visit(node.kwargannotation)
|
471 |
+
else:
|
472 |
+
self.maybe_break(node.kwarg)
|
473 |
+
self.write('**')
|
474 |
+
self.visit(node.kwarg)
|
475 |
+
else:
|
476 |
+
for arg, default in zip(node.args, padding + node.defaults):
|
477 |
+
self.write(sep())
|
478 |
+
self.visit(arg)
|
479 |
+
if default is not None:
|
480 |
+
self.write('=')
|
481 |
+
self.visit(default)
|
482 |
+
if node.vararg is not None:
|
483 |
+
self.write(sep())
|
484 |
+
self.write('*' + node.vararg)
|
485 |
+
if node.kwarg is not None:
|
486 |
+
self.write(sep())
|
487 |
+
self.write('**' + node.kwarg)
|
488 |
+
|
489 |
+
def visit_arg(self, node):
|
490 |
+
# Py3 only
|
491 |
+
self.maybe_break(node)
|
492 |
+
self.write(node.arg)
|
493 |
+
if node.annotation is not None:
|
494 |
+
self.write(self.COLON)
|
495 |
+
self.visit(node.annotation)
|
496 |
+
|
497 |
+
def visit_keyword(self, node):
|
498 |
+
self.maybe_break(node.value)
|
499 |
+
if node.arg is not None:
|
500 |
+
self.write(node.arg + '=')
|
501 |
+
else:
|
502 |
+
self.write('**')
|
503 |
+
self.visit(node.value)
|
504 |
+
|
505 |
+
def visit_ClassDef(self, node):
|
506 |
+
self.newline(extra=2)
|
507 |
+
# first decorator line number will be used
|
508 |
+
self.decorators(node)
|
509 |
+
self.write('class %s' % node.name)
|
510 |
+
|
511 |
+
if (node.bases or (hasattr(node, 'keywords') and node.keywords) or
|
512 |
+
(hasattr(node, 'starargs') and (node.starargs or node.kwargs))):
|
513 |
+
self.paren_start()
|
514 |
+
sep = Sep(self.COMMA)
|
515 |
+
|
516 |
+
for base in node.bases:
|
517 |
+
self.write(sep())
|
518 |
+
self.visit(base)
|
519 |
+
# XXX: the if here is used to keep this module compatible
|
520 |
+
# with python 2.6.
|
521 |
+
if hasattr(node, 'keywords'):
|
522 |
+
for keyword in node.keywords:
|
523 |
+
self.write(sep())
|
524 |
+
self.visit(keyword)
|
525 |
+
if hasattr(node, 'starargs'):
|
526 |
+
if node.starargs is not None:
|
527 |
+
self.write(sep())
|
528 |
+
self.maybe_break(node.starargs)
|
529 |
+
self.write('*')
|
530 |
+
self.visit(node.starargs)
|
531 |
+
if node.kwargs is not None:
|
532 |
+
self.write(sep())
|
533 |
+
self.maybe_break(node.kwargs)
|
534 |
+
self.write('**')
|
535 |
+
self.visit(node.kwargs)
|
536 |
+
self.paren_end()
|
537 |
+
self.write(':')
|
538 |
+
self.body(node.body)
|
539 |
+
|
540 |
+
def visit_If(self, node):
|
541 |
+
self.newline(node, force=True)
|
542 |
+
self.write('if ')
|
543 |
+
self.visit(node.test)
|
544 |
+
self.write(':')
|
545 |
+
self.body(node.body)
|
546 |
+
while True:
|
547 |
+
if len(node.orelse) == 1 and isinstance(node.orelse[0], If):
|
548 |
+
node = node.orelse[0]
|
549 |
+
self.newline(node.test, force=True)
|
550 |
+
self.write('elif ')
|
551 |
+
self.visit(node.test)
|
552 |
+
self.write(':')
|
553 |
+
self.body(node.body)
|
554 |
+
else:
|
555 |
+
if node.orelse:
|
556 |
+
self.newline()
|
557 |
+
self.write('else:')
|
558 |
+
self.body(node.orelse)
|
559 |
+
break
|
560 |
+
|
561 |
+
def visit_AsyncFor(self, node):
|
562 |
+
self.visit_For(node, True)
|
563 |
+
|
564 |
+
def visit_For(self, node, async=False):
|
565 |
+
self.newline(node, force=True)
|
566 |
+
if async:
|
567 |
+
self.write('async ')
|
568 |
+
self.write('for ')
|
569 |
+
self.visit_bare(node.target)
|
570 |
+
self.write(' in ')
|
571 |
+
self.visit(node.iter)
|
572 |
+
self.write(':')
|
573 |
+
self.body_or_else(node)
|
574 |
+
|
575 |
+
def visit_While(self, node):
|
576 |
+
self.newline(node, force=True)
|
577 |
+
self.write('while ')
|
578 |
+
self.visit(node.test)
|
579 |
+
self.write(':')
|
580 |
+
self.body_or_else(node)
|
581 |
+
|
582 |
+
def visit_AsyncWith(self, node):
|
583 |
+
self.visit_With(node, True)
|
584 |
+
|
585 |
+
def visit_With(self, node, async=False):
|
586 |
+
self.newline(node, force=True)
|
587 |
+
if async:
|
588 |
+
self.write('async ')
|
589 |
+
self.write('with ')
|
590 |
+
|
591 |
+
if hasattr(node, 'items'):
|
592 |
+
sep = Sep(self.COMMA)
|
593 |
+
for item in node.items:
|
594 |
+
self.write(sep())
|
595 |
+
self.visit_withitem(item)
|
596 |
+
else:
|
597 |
+
# in python 2, similarly to the elif statement, multiple nested context managers
|
598 |
+
# are generally the multi-form of a single with statement
|
599 |
+
self.visit_withitem(node)
|
600 |
+
while len(node.body) == 1 and isinstance(node.body[0], With):
|
601 |
+
node = node.body[0]
|
602 |
+
self.write(self.COMMA)
|
603 |
+
self.visit_withitem(node)
|
604 |
+
self.write(':')
|
605 |
+
self.body(node.body)
|
606 |
+
|
607 |
+
def visit_withitem(self, node):
|
608 |
+
self.visit(node.context_expr)
|
609 |
+
if node.optional_vars is not None:
|
610 |
+
self.write(' as ')
|
611 |
+
self.visit(node.optional_vars)
|
612 |
+
|
613 |
+
def visit_Pass(self, node):
|
614 |
+
self.newline(node)
|
615 |
+
self.write('pass')
|
616 |
+
|
617 |
+
def visit_Print(self, node):
|
618 |
+
# XXX: python 2 only
|
619 |
+
self.newline(node)
|
620 |
+
self.write('print ')
|
621 |
+
sep = Sep(self.COMMA)
|
622 |
+
if node.dest is not None:
|
623 |
+
self.write(' >> ')
|
624 |
+
self.visit(node.dest)
|
625 |
+
sep()
|
626 |
+
for value in node.values:
|
627 |
+
self.write(sep())
|
628 |
+
self.visit(value)
|
629 |
+
if not node.nl:
|
630 |
+
self.write(',')
|
631 |
+
|
632 |
+
def visit_Delete(self, node):
|
633 |
+
self.newline(node)
|
634 |
+
self.write('del ')
|
635 |
+
sep = Sep(self.COMMA)
|
636 |
+
for target in node.targets:
|
637 |
+
self.write(sep())
|
638 |
+
self.visit(target)
|
639 |
+
|
640 |
+
def visit_Try(self, node):
|
641 |
+
# Python 3 only. exploits the fact that TryExcept uses the same attribute names
|
642 |
+
self.visit_TryExcept(node)
|
643 |
+
if node.finalbody:
|
644 |
+
self.newline()
|
645 |
+
self.write('finally:')
|
646 |
+
self.body(node.finalbody)
|
647 |
+
|
648 |
+
def visit_TryExcept(self, node):
|
649 |
+
self.newline(node, force=True)
|
650 |
+
self.write('try:')
|
651 |
+
self.body(node.body)
|
652 |
+
for handler in node.handlers:
|
653 |
+
self.visit(handler)
|
654 |
+
if node.orelse:
|
655 |
+
self.newline()
|
656 |
+
self.write('else:')
|
657 |
+
self.body(node.orelse)
|
658 |
+
|
659 |
+
def visit_TryFinally(self, node):
|
660 |
+
# Python 2 only
|
661 |
+
if len(node.body) == 1 and isinstance(node.body[0], TryExcept):
|
662 |
+
self.visit_TryExcept(node.body[0])
|
663 |
+
else:
|
664 |
+
self.newline(node, force=True)
|
665 |
+
self.write('try:')
|
666 |
+
self.body(node.body)
|
667 |
+
self.newline()
|
668 |
+
self.write('finally:')
|
669 |
+
self.body(node.finalbody)
|
670 |
+
|
671 |
+
def visit_ExceptHandler(self, node):
|
672 |
+
self.newline(node, force=True)
|
673 |
+
self.write('except')
|
674 |
+
if node.type:
|
675 |
+
self.write(' ')
|
676 |
+
self.visit(node.type)
|
677 |
+
if node.name:
|
678 |
+
self.write(' as ')
|
679 |
+
# Compatability
|
680 |
+
if isinstance(node.name, AST):
|
681 |
+
self.visit(node.name)
|
682 |
+
else:
|
683 |
+
self.write(node.name)
|
684 |
+
self.write(':')
|
685 |
+
self.body(node.body)
|
686 |
+
|
687 |
+
def visit_Global(self, node):
|
688 |
+
self.newline(node)
|
689 |
+
self.write('global ' + self.COMMA.join(node.names))
|
690 |
+
|
691 |
+
def visit_Nonlocal(self, node):
|
692 |
+
self.newline(node)
|
693 |
+
self.write('nonlocal ' + self.COMMA.join(node.names))
|
694 |
+
|
695 |
+
def visit_Return(self, node):
|
696 |
+
self.newline(node)
|
697 |
+
if node.value is not None:
|
698 |
+
self.write('return ')
|
699 |
+
self.visit(node.value)
|
700 |
+
else:
|
701 |
+
self.write('return')
|
702 |
+
|
703 |
+
def visit_Break(self, node):
|
704 |
+
self.newline(node)
|
705 |
+
self.write('break')
|
706 |
+
|
707 |
+
def visit_Continue(self, node):
|
708 |
+
self.newline(node)
|
709 |
+
self.write('continue')
|
710 |
+
|
711 |
+
def visit_Raise(self, node):
|
712 |
+
# XXX: Python 2.6 / 3.0 compatibility
|
713 |
+
self.newline(node)
|
714 |
+
if hasattr(node, 'exc') and node.exc is not None:
|
715 |
+
self.write('raise ')
|
716 |
+
self.visit(node.exc)
|
717 |
+
if node.cause is not None:
|
718 |
+
self.write(' from ')
|
719 |
+
self.visit(node.cause)
|
720 |
+
elif hasattr(node, 'type') and node.type is not None:
|
721 |
+
self.write('raise ')
|
722 |
+
self.visit(node.type)
|
723 |
+
if node.inst is not None:
|
724 |
+
self.write(self.COMMA)
|
725 |
+
self.visit(node.inst)
|
726 |
+
if node.tback is not None:
|
727 |
+
self.write(self.COMMA)
|
728 |
+
self.visit(node.tback)
|
729 |
+
else:
|
730 |
+
self.write('raise')
|
731 |
+
|
732 |
+
# Expressions
|
733 |
+
|
734 |
+
def visit_Attribute(self, node):
|
735 |
+
self.maybe_break(node)
|
736 |
+
# Edge case: due to the use of \d*[.]\d* for floats \d*[.]\w*, you have
|
737 |
+
# to put parenthesis around an integer literal do get an attribute from it
|
738 |
+
if isinstance(node.value, Num):
|
739 |
+
self.paren_start()
|
740 |
+
self.visit(node.value)
|
741 |
+
self.paren_end()
|
742 |
+
else:
|
743 |
+
self.prec_start(17)
|
744 |
+
self.visit(node.value)
|
745 |
+
self.prec_end()
|
746 |
+
self.write('.' + node.attr)
|
747 |
+
|
748 |
+
def visit_Call(self, node):
|
749 |
+
self.maybe_break(node)
|
750 |
+
#need to put parenthesis around numbers being called (this makes no sense)
|
751 |
+
if isinstance(node.func, Num):
|
752 |
+
self.paren_start()
|
753 |
+
self.visit_Num(node.func)
|
754 |
+
self.paren_end()
|
755 |
+
else:
|
756 |
+
self.prec_start(17)
|
757 |
+
self.visit(node.func)
|
758 |
+
self.prec_end()
|
759 |
+
# special case generator expressions as only argument
|
760 |
+
if (len(node.args) == 1 and isinstance(node.args[0], GeneratorExp) and
|
761 |
+
not node.keywords and hasattr(node, 'starargs') and
|
762 |
+
not node.starargs and not node.kwargs):
|
763 |
+
self.visit_GeneratorExp(node.args[0])
|
764 |
+
return
|
765 |
+
|
766 |
+
self.paren_start()
|
767 |
+
sep = Sep(self.COMMA)
|
768 |
+
for arg in node.args:
|
769 |
+
self.write(sep())
|
770 |
+
self.maybe_break(arg)
|
771 |
+
self.visit(arg)
|
772 |
+
for keyword in node.keywords:
|
773 |
+
self.write(sep())
|
774 |
+
self.visit(keyword)
|
775 |
+
if hasattr(node, 'starargs'):
|
776 |
+
if node.starargs is not None:
|
777 |
+
self.write(sep())
|
778 |
+
self.maybe_break(node.starargs)
|
779 |
+
self.write('*')
|
780 |
+
self.visit(node.starargs)
|
781 |
+
if node.kwargs is not None:
|
782 |
+
self.write(sep())
|
783 |
+
self.maybe_break(node.kwargs)
|
784 |
+
self.write('**')
|
785 |
+
self.visit(node.kwargs)
|
786 |
+
self.paren_end()
|
787 |
+
|
788 |
+
def visit_Name(self, node):
|
789 |
+
self.maybe_break(node)
|
790 |
+
self.write(node.id)
|
791 |
+
|
792 |
+
def visit_NameConstant(self, node):
|
793 |
+
self.maybe_break(node)
|
794 |
+
self.write(repr(node.value))
|
795 |
+
|
796 |
+
def visit_Str(self, node, frombytes=False):
|
797 |
+
self.maybe_break(node)
|
798 |
+
if frombytes:
|
799 |
+
newline_count = node.s.count('\n'.encode('utf-8'))
|
800 |
+
else:
|
801 |
+
newline_count = node.s.count('\n')
|
802 |
+
|
803 |
+
# heuristic, expand when more than 1 newline and when at least 80%
|
804 |
+
# of the characters aren't newlines
|
805 |
+
expand = newline_count > 1 and len(node.s) > 5 * newline_count
|
806 |
+
if self.correct_line_numbers:
|
807 |
+
# Also check if we have enougn newlines to expand in if we're going for correct line numbers
|
808 |
+
if self.after_colon:
|
809 |
+
# Although this makes little sense just after a colon
|
810 |
+
expand = expand and self.new_lines > newline_count
|
811 |
+
else:
|
812 |
+
expand = expand and self.new_lines >= newline_count
|
813 |
+
|
814 |
+
if expand and (not self.correct_line_numbers or self.new_lines >= newline_count):
|
815 |
+
if self.correct_line_numbers:
|
816 |
+
self.new_lines -= newline_count
|
817 |
+
|
818 |
+
a = repr(node.s)
|
819 |
+
delimiter = a[-1]
|
820 |
+
header, content = a[:-1].split(delimiter, 1)
|
821 |
+
lines = []
|
822 |
+
chain = False
|
823 |
+
for i in content.split('\\n'):
|
824 |
+
if chain:
|
825 |
+
i = lines.pop() + i
|
826 |
+
chain = False
|
827 |
+
if (len(i) - len(i.rstrip('\\'))) % 2:
|
828 |
+
i += '\\n'
|
829 |
+
chain = True
|
830 |
+
lines.append(i)
|
831 |
+
assert newline_count + 1 == len(lines)
|
832 |
+
self.write(header)
|
833 |
+
self.write(delimiter * 3)
|
834 |
+
self.write('\n'.join(lines))
|
835 |
+
self.write(delimiter * 3)
|
836 |
+
else:
|
837 |
+
self.write(repr(node.s))
|
838 |
+
|
839 |
+
def visit_Bytes(self, node):
|
840 |
+
self.visit_Str(node, True)
|
841 |
+
|
842 |
+
def visit_Num(self, node):
|
843 |
+
self.maybe_break(node)
|
844 |
+
|
845 |
+
negative = (node.n.imag or node.n.real) < 0 and not PY3
|
846 |
+
if negative:
|
847 |
+
self.prec_start(self.UNARYOP_SYMBOLS[USub][1])
|
848 |
+
|
849 |
+
# 1e999 and related friends are parsed into inf
|
850 |
+
if abs(node.n) == 1e999:
|
851 |
+
if negative:
|
852 |
+
self.write('-')
|
853 |
+
self.write('1e999')
|
854 |
+
if node.n.imag:
|
855 |
+
self.write('j')
|
856 |
+
else:
|
857 |
+
self.write(repr(node.n))
|
858 |
+
|
859 |
+
if negative:
|
860 |
+
self.prec_end()
|
861 |
+
|
862 |
+
def visit_Tuple(self, node, guard=True):
|
863 |
+
if guard or not node.elts:
|
864 |
+
self.paren_start()
|
865 |
+
sep = Sep(self.COMMA)
|
866 |
+
for item in node.elts:
|
867 |
+
self.write(sep())
|
868 |
+
self.visit(item)
|
869 |
+
if len(node.elts) == 1:
|
870 |
+
self.write(',')
|
871 |
+
if guard or not node.elts:
|
872 |
+
self.paren_end()
|
873 |
+
|
874 |
+
def _sequence_visit(left, right): # pylint: disable=E0213
|
875 |
+
def visit(self, node):
|
876 |
+
self.maybe_break(node)
|
877 |
+
self.paren_start(left)
|
878 |
+
sep = Sep(self.COMMA)
|
879 |
+
for item in node.elts:
|
880 |
+
self.write(sep())
|
881 |
+
self.visit(item)
|
882 |
+
self.paren_end(right)
|
883 |
+
return visit
|
884 |
+
|
885 |
+
visit_List = _sequence_visit('[', ']')
|
886 |
+
visit_Set = _sequence_visit('{', '}')
|
887 |
+
|
888 |
+
def visit_Dict(self, node):
|
889 |
+
self.maybe_break(node)
|
890 |
+
self.paren_start('{')
|
891 |
+
sep = Sep(self.COMMA)
|
892 |
+
for key, value in zip(node.keys, node.values):
|
893 |
+
self.write(sep())
|
894 |
+
self.visit(key)
|
895 |
+
self.write(self.COLON)
|
896 |
+
self.visit(value)
|
897 |
+
self.paren_end('}')
|
898 |
+
|
899 |
+
def visit_BinOp(self, node):
|
900 |
+
self.maybe_break(node)
|
901 |
+
symbol, precedence = self.BINOP_SYMBOLS[type(node.op)]
|
902 |
+
self.prec_start(precedence, type(node.op) != Pow)
|
903 |
+
|
904 |
+
# work around python's negative integer literal optimization
|
905 |
+
if isinstance(node.op, Pow):
|
906 |
+
self.visit(node.left)
|
907 |
+
self.prec_middle(14)
|
908 |
+
else:
|
909 |
+
self.visit(node.left)
|
910 |
+
self.prec_middle()
|
911 |
+
self.write(symbol)
|
912 |
+
self.visit(node.right)
|
913 |
+
self.prec_end()
|
914 |
+
|
915 |
+
def visit_BoolOp(self, node):
|
916 |
+
self.maybe_break(node)
|
917 |
+
symbol, precedence = self.BOOLOP_SYMBOLS[type(node.op)]
|
918 |
+
self.prec_start(precedence, True)
|
919 |
+
self.prec_middle()
|
920 |
+
sep = Sep(symbol)
|
921 |
+
for value in node.values:
|
922 |
+
self.write(sep())
|
923 |
+
self.visit(value)
|
924 |
+
self.prec_end()
|
925 |
+
|
926 |
+
def visit_Compare(self, node):
|
927 |
+
self.maybe_break(node)
|
928 |
+
self.prec_start(7, True)
|
929 |
+
self.prec_middle()
|
930 |
+
self.visit(node.left)
|
931 |
+
for op, right in zip(node.ops, node.comparators):
|
932 |
+
self.write(self.CMPOP_SYMBOLS[type(op)][0])
|
933 |
+
self.visit(right)
|
934 |
+
self.prec_end()
|
935 |
+
|
936 |
+
def visit_UnaryOp(self, node):
|
937 |
+
self.maybe_break(node)
|
938 |
+
symbol, precedence = self.UNARYOP_SYMBOLS[type(node.op)]
|
939 |
+
self.prec_start(precedence)
|
940 |
+
self.write(symbol)
|
941 |
+
# workaround: in python 2, an explicit USub node around a number literal
|
942 |
+
# indicates the literal was surrounded by parenthesis
|
943 |
+
if (not PY3 and isinstance(node.op, USub) and isinstance(node.operand, Num)
|
944 |
+
and (node.operand.n.real or node.operand.n.imag) >= 0):
|
945 |
+
self.paren_start()
|
946 |
+
self.visit(node.operand)
|
947 |
+
self.paren_end()
|
948 |
+
else:
|
949 |
+
self.visit(node.operand)
|
950 |
+
self.prec_end()
|
951 |
+
|
952 |
+
def visit_Subscript(self, node):
|
953 |
+
self.maybe_break(node)
|
954 |
+
# have to surround literals by parenthesis (at least in Py2)
|
955 |
+
if isinstance(node.value, Num):
|
956 |
+
self.paren_start()
|
957 |
+
self.visit_Num(node.value)
|
958 |
+
self.paren_end()
|
959 |
+
else:
|
960 |
+
self.prec_start(17)
|
961 |
+
self.visit(node.value)
|
962 |
+
self.prec_end()
|
963 |
+
self.paren_start('[')
|
964 |
+
self.visit(node.slice)
|
965 |
+
self.paren_end(']')
|
966 |
+
|
967 |
+
def visit_Index(self, node, guard=False):
|
968 |
+
# Index has no lineno information
|
969 |
+
# When a subscript includes a tuple directly, the parenthesis can be dropped
|
970 |
+
if not guard:
|
971 |
+
self.visit_bare(node.value)
|
972 |
+
else:
|
973 |
+
self.visit(node.value)
|
974 |
+
|
975 |
+
def visit_Slice(self, node):
|
976 |
+
# Slice has no lineno information
|
977 |
+
if node.lower is not None:
|
978 |
+
self.visit(node.lower)
|
979 |
+
self.write(':')
|
980 |
+
if node.upper is not None:
|
981 |
+
self.visit(node.upper)
|
982 |
+
if node.step is not None:
|
983 |
+
self.write(':')
|
984 |
+
if not (isinstance(node.step, Name) and node.step.id == 'None'):
|
985 |
+
self.visit(node.step)
|
986 |
+
|
987 |
+
def visit_Ellipsis(self, node):
|
988 |
+
# Ellipsis has no lineno information
|
989 |
+
self.write('...')
|
990 |
+
|
991 |
+
def visit_ExtSlice(self, node):
|
992 |
+
# Extslice has no lineno information
|
993 |
+
for idx, item in enumerate(node.dims):
|
994 |
+
if idx:
|
995 |
+
self.write(self.COMMA)
|
996 |
+
if isinstance(item, Index):
|
997 |
+
self.visit_Index(item, True)
|
998 |
+
else:
|
999 |
+
self.visit(item)
|
1000 |
+
|
1001 |
+
def visit_Yield(self, node, paren=True):
|
1002 |
+
# yield can only be used in a statement context, or we're between parenthesis
|
1003 |
+
self.maybe_break(node)
|
1004 |
+
if paren:
|
1005 |
+
self.paren_start()
|
1006 |
+
if node.value is not None:
|
1007 |
+
self.write('yield ')
|
1008 |
+
self.visit_bare(node.value)
|
1009 |
+
else:
|
1010 |
+
self.write('yield')
|
1011 |
+
if paren:
|
1012 |
+
self.paren_end()
|
1013 |
+
|
1014 |
+
def visit_YieldFrom(self, node, paren=True):
|
1015 |
+
# Even though yield and yield from technically occupy precedence level 1, certain code
|
1016 |
+
# using them is illegal e.g. "return yield from a()" will not work unless you
|
1017 |
+
# put the yield from statement within parenthesis.
|
1018 |
+
self.maybe_break(node)
|
1019 |
+
if paren:
|
1020 |
+
self.paren_start()
|
1021 |
+
self.write('yield from ')
|
1022 |
+
self.visit(node.value)
|
1023 |
+
if paren:
|
1024 |
+
self.paren_end()
|
1025 |
+
|
1026 |
+
def visit_Lambda(self, node):
|
1027 |
+
self.maybe_break(node)
|
1028 |
+
self.prec_start(2)
|
1029 |
+
self.write('lambda ')
|
1030 |
+
self.visit_arguments(node.args)
|
1031 |
+
self.write(self.COLON)
|
1032 |
+
self.visit(node.body)
|
1033 |
+
self.prec_end()
|
1034 |
+
|
1035 |
+
def _generator_visit(left, right):
|
1036 |
+
def visit(self, node):
|
1037 |
+
self.maybe_break(node)
|
1038 |
+
self.paren_start(left)
|
1039 |
+
self.visit(node.elt)
|
1040 |
+
for comprehension in node.generators:
|
1041 |
+
self.visit(comprehension)
|
1042 |
+
self.paren_end(right)
|
1043 |
+
return visit
|
1044 |
+
|
1045 |
+
visit_ListComp = _generator_visit('[', ']')
|
1046 |
+
visit_GeneratorExp = _generator_visit('(', ')')
|
1047 |
+
visit_SetComp = _generator_visit('{', '}')
|
1048 |
+
|
1049 |
+
def visit_DictComp(self, node):
|
1050 |
+
self.maybe_break(node)
|
1051 |
+
self.paren_start('{')
|
1052 |
+
self.visit(node.key)
|
1053 |
+
self.write(self.COLON)
|
1054 |
+
self.visit(node.value)
|
1055 |
+
for comprehension in node.generators:
|
1056 |
+
self.visit(comprehension)
|
1057 |
+
self.paren_end('}')
|
1058 |
+
|
1059 |
+
def visit_IfExp(self, node):
|
1060 |
+
self.maybe_break(node)
|
1061 |
+
self.prec_start(3, False)
|
1062 |
+
self.visit(node.body)
|
1063 |
+
self.write(' if ')
|
1064 |
+
self.visit(node.test)
|
1065 |
+
self.prec_middle(2)
|
1066 |
+
self.write(' else ')
|
1067 |
+
self.visit(node.orelse)
|
1068 |
+
self.prec_end()
|
1069 |
+
|
1070 |
+
def visit_Starred(self, node):
|
1071 |
+
self.maybe_break(node)
|
1072 |
+
self.write('*')
|
1073 |
+
self.visit(node.value)
|
1074 |
+
|
1075 |
+
def visit_Repr(self, node):
|
1076 |
+
# XXX: python 2.6 only
|
1077 |
+
self.maybe_break(node)
|
1078 |
+
self.write('`')
|
1079 |
+
self.visit(node.value)
|
1080 |
+
self.write('`')
|
1081 |
+
|
1082 |
+
# Helper Nodes
|
1083 |
+
|
1084 |
+
def visit_alias(self, node):
|
1085 |
+
# alias does not have line number information
|
1086 |
+
self.write(node.name)
|
1087 |
+
if node.asname is not None:
|
1088 |
+
self.write(' as ' + node.asname)
|
1089 |
+
|
1090 |
+
def visit_comprehension(self, node):
|
1091 |
+
self.maybe_break(node.target)
|
1092 |
+
self.write(' for ')
|
1093 |
+
self.visit_bare(node.target)
|
1094 |
+
self.write(' in ')
|
1095 |
+
# workaround: lambda and ternary need to be within parenthesis here
|
1096 |
+
self.prec_start(4)
|
1097 |
+
self.visit(node.iter)
|
1098 |
+
self.prec_end()
|
1099 |
+
|
1100 |
+
for if_ in node.ifs:
|
1101 |
+
self.write(' if ')
|
1102 |
+
self.visit(if_)
|
renpy/rpycdec/rpycdecdata/decompiler/codegen.pyo
ADDED
Binary file (44.4 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/magic.py
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2015 CensoredUsername
|
2 |
+
|
3 |
+
# This module provides tools for safely analyizing pickle files programmatically
|
4 |
+
|
5 |
+
import sys
|
6 |
+
|
7 |
+
PY3 = sys.version_info >= (3, 0)
|
8 |
+
PY2 = not PY3
|
9 |
+
|
10 |
+
import types
|
11 |
+
import pickle
|
12 |
+
import struct
|
13 |
+
|
14 |
+
if PY3:
|
15 |
+
from io import BytesIO as StringIO
|
16 |
+
else:
|
17 |
+
from cStringIO import StringIO
|
18 |
+
|
19 |
+
__all__ = [
|
20 |
+
"load", "loads", "safe_load", "safe_loads", "safe_dump", "safe_dumps",
|
21 |
+
"fake_package", "remove_fake_package",
|
22 |
+
"FakeModule", "FakePackage", "FakePackageLoader",
|
23 |
+
"FakeClassType", "FakeClassFactory",
|
24 |
+
"FakeClass", "FakeStrict", "FakeWarning", "FakeIgnore",
|
25 |
+
"FakeUnpicklingError", "FakeUnpickler", "SafeUnpickler",
|
26 |
+
"SafePickler"
|
27 |
+
]
|
28 |
+
|
29 |
+
# Fake class implementation
|
30 |
+
|
31 |
+
class FakeClassType(type):
|
32 |
+
"""
|
33 |
+
The metaclass used to create fake classes. To support comparisons between
|
34 |
+
fake classes and :class:`FakeModule` instances custom behaviour is defined
|
35 |
+
here which follows this logic:
|
36 |
+
|
37 |
+
If the other object does not have ``other.__name__`` set, they are not equal.
|
38 |
+
|
39 |
+
Else if it does not have ``other.__module__`` set, they are equal if
|
40 |
+
``self.__module__ + "." + self.__name__ == other.__name__``.
|
41 |
+
|
42 |
+
Else, they are equal if
|
43 |
+
``self.__module__ == other.__module__ and self.__name__ == other.__name__``
|
44 |
+
|
45 |
+
Using this behaviour, ``==``, ``!=``, ``hash()``, ``isinstance()`` and ``issubclass()``
|
46 |
+
are implemented allowing comparison between :class:`FakeClassType` instances
|
47 |
+
and :class:`FakeModule` instances to succeed if they are pretending to be in the same
|
48 |
+
place in the python module hierarchy.
|
49 |
+
|
50 |
+
To create a fake class using this metaclass, you can either use this metaclass directly or
|
51 |
+
inherit from the fake class base instances given below. When doing this, the module that
|
52 |
+
this fake class is pretending to be in should be specified using the *module* argument
|
53 |
+
when the metaclass is called directly or a :attr:``__module__`` class attribute in a class statement.
|
54 |
+
|
55 |
+
This is a subclass of :class:`type`.
|
56 |
+
"""
|
57 |
+
|
58 |
+
# instance creation logic
|
59 |
+
|
60 |
+
def __new__(cls, name, bases, attributes, module=None):
|
61 |
+
# This would be a lie
|
62 |
+
attributes.pop("__qualname__", None)
|
63 |
+
|
64 |
+
# figure out what module we should say we're in
|
65 |
+
# note that if no module is explicitly passed, the current module will be chosen
|
66 |
+
# due to the class statement implicitly specifying __module__ as __name__
|
67 |
+
if module is not None:
|
68 |
+
attributes["__module__"] = module
|
69 |
+
|
70 |
+
if "__module__" not in attributes:
|
71 |
+
raise TypeError("No module has been specified for FakeClassType {0}".format(name))
|
72 |
+
|
73 |
+
# assemble instance
|
74 |
+
return type.__new__(cls, name, bases, attributes)
|
75 |
+
|
76 |
+
def __init__(self, name, bases, attributes, module=None):
|
77 |
+
type.__init__(self, name, bases, attributes)
|
78 |
+
|
79 |
+
# comparison logic
|
80 |
+
|
81 |
+
def __eq__(self, other):
|
82 |
+
if not hasattr(other, "__name__"):
|
83 |
+
return False
|
84 |
+
if hasattr(other, "__module__"):
|
85 |
+
return self.__module__ == other.__module__ and self.__name__ == other.__name__
|
86 |
+
else:
|
87 |
+
return self.__module__ + "." + self.__name__ == other.__name__
|
88 |
+
|
89 |
+
def __ne__(self, other):
|
90 |
+
return not self == other
|
91 |
+
|
92 |
+
def __hash__(self):
|
93 |
+
return hash(self.__module__ + "." + self.__name__)
|
94 |
+
|
95 |
+
def __instancecheck__(self, instance):
|
96 |
+
return self.__subclasscheck__(instance.__class__)
|
97 |
+
|
98 |
+
def __subclasscheck__(self, subclass):
|
99 |
+
return (self == subclass or
|
100 |
+
(bool(subclass.__bases__) and
|
101 |
+
any(self.__subclasscheck__(base) for base in subclass.__bases__)))
|
102 |
+
|
103 |
+
# PY2 doesn't like the PY3 way of metaclasses and PY3 doesn't support the PY2 way
|
104 |
+
# so we call the metaclass directly
|
105 |
+
FakeClass = FakeClassType("FakeClass", (), {"__doc__": """
|
106 |
+
A barebones instance of :class:`FakeClassType`. Inherit from this to create fake classes.
|
107 |
+
"""}, module=__name__)
|
108 |
+
|
109 |
+
class FakeStrict(FakeClass, object):
|
110 |
+
def __new__(cls, *args, **kwargs):
|
111 |
+
self = FakeClass.__new__(cls)
|
112 |
+
if args or kwargs:
|
113 |
+
raise FakeUnpicklingError("{0} was instantiated with unexpected arguments {1}, {2}".format(cls, args, kwargs))
|
114 |
+
return self
|
115 |
+
|
116 |
+
def __setstate__(self, state):
|
117 |
+
slotstate = None
|
118 |
+
|
119 |
+
if (isinstance(state, tuple) and len(state) == 2 and
|
120 |
+
(state[0] is None or isinstance(state[0], dict)) and
|
121 |
+
(state[1] is None or isinstance(state[1], dict))):
|
122 |
+
state, slotstate = state
|
123 |
+
|
124 |
+
if state:
|
125 |
+
# Don't have to check for slotstate here since it's either None or a dict
|
126 |
+
if not isinstance(state, dict):
|
127 |
+
raise FakeUnpicklingError("{0}.__setstate__() got unexpected arguments {1}".format(self.__class__, state))
|
128 |
+
else:
|
129 |
+
self.__dict__.update(state)
|
130 |
+
|
131 |
+
if slotstate:
|
132 |
+
self.__dict__.update(slotstate)
|
133 |
+
|
134 |
+
class FakeWarning(FakeClass, object):
|
135 |
+
def __new__(cls, *args, **kwargs):
|
136 |
+
self = FakeClass.__new__(cls)
|
137 |
+
if args or kwargs:
|
138 |
+
print("{0} was instantiated with unexpected arguments {1}, {2}".format(cls, args, kwargs))
|
139 |
+
self._new_args = args
|
140 |
+
return self
|
141 |
+
|
142 |
+
def __setstate__(self, state):
|
143 |
+
slotstate = None
|
144 |
+
|
145 |
+
if (isinstance(state, tuple) and len(state) == 2 and
|
146 |
+
(state[0] is None or isinstance(state[0], dict)) and
|
147 |
+
(state[1] is None or isinstance(state[1], dict))):
|
148 |
+
state, slotstate = state
|
149 |
+
|
150 |
+
if state:
|
151 |
+
# Don't have to check for slotstate here since it's either None or a dict
|
152 |
+
if not isinstance(state, dict):
|
153 |
+
print("{0}.__setstate__() got unexpected arguments {1}".format(self.__class__, state))
|
154 |
+
self._setstate_args = state
|
155 |
+
else:
|
156 |
+
self.__dict__.update(state)
|
157 |
+
|
158 |
+
if slotstate:
|
159 |
+
self.__dict__.update(slotstate)
|
160 |
+
|
161 |
+
class FakeIgnore(FakeClass, object):
|
162 |
+
def __new__(cls, *args, **kwargs):
|
163 |
+
self = FakeClass.__new__(cls)
|
164 |
+
if args:
|
165 |
+
self._new_args = args
|
166 |
+
if kwargs:
|
167 |
+
self._new_kwargs = kwargs
|
168 |
+
return self
|
169 |
+
|
170 |
+
def __setstate__(self, state):
|
171 |
+
slotstate = None
|
172 |
+
|
173 |
+
if (isinstance(state, tuple) and len(state) == 2 and
|
174 |
+
(state[0] is None or isinstance(state[0], dict)) and
|
175 |
+
(state[1] is None or isinstance(state[1], dict))):
|
176 |
+
state, slotstate = state
|
177 |
+
|
178 |
+
if state:
|
179 |
+
# Don't have to check for slotstate here since it's either None or a dict
|
180 |
+
if not isinstance(state, dict):
|
181 |
+
self._setstate_args = state
|
182 |
+
else:
|
183 |
+
self.__dict__.update(state)
|
184 |
+
|
185 |
+
if slotstate:
|
186 |
+
self.__dict__.update(slotstate)
|
187 |
+
|
188 |
+
class FakeClassFactory(object):
|
189 |
+
"""
|
190 |
+
Factory of fake classses. It will create fake class definitions on demand
|
191 |
+
based on the passed arguments.
|
192 |
+
"""
|
193 |
+
|
194 |
+
def __init__(self, special_cases=(), default_class=FakeStrict):
|
195 |
+
"""
|
196 |
+
*special_cases* should be an iterable containing fake classes which should be treated
|
197 |
+
as special cases during the fake unpickling process. This way you can specify custom methods
|
198 |
+
and attributes on these classes as they're used during unpickling.
|
199 |
+
|
200 |
+
*default_class* should be a FakeClassType instance which will be subclassed to create the
|
201 |
+
necessary non-special case fake classes during unpickling. This should usually be set to
|
202 |
+
:class:`FakeStrict`, :class:`FakeWarning` or :class:`FakeIgnore`. These classes have
|
203 |
+
:meth:`__new__` and :meth:`__setstate__` methods which extract data from the pickle stream
|
204 |
+
and provide means of inspecting the stream when it is not clear how the data should be interpreted.
|
205 |
+
|
206 |
+
As an example, we can define the fake class generated for definition bar in module foo,
|
207 |
+
which has a :meth:`__str__` method which returns ``"baz"``::
|
208 |
+
|
209 |
+
class bar(FakeStrict, object):
|
210 |
+
def __str__(self):
|
211 |
+
return "baz"
|
212 |
+
|
213 |
+
special_cases = [bar]
|
214 |
+
|
215 |
+
Alternatively they can also be instantiated using :class:`FakeClassType` directly::
|
216 |
+
special_cases = [FakeClassType(c.__name__, c.__bases__, c.__dict__, c.__module__)]
|
217 |
+
"""
|
218 |
+
self.special_cases = dict(((i.__module__, i.__name__), i) for i in special_cases)
|
219 |
+
self.default = default_class
|
220 |
+
|
221 |
+
self.class_cache = {}
|
222 |
+
|
223 |
+
def __call__(self, name, module):
|
224 |
+
"""
|
225 |
+
Return the right class for the specified *module* and *name*.
|
226 |
+
|
227 |
+
This class will either be one of the special cases in case the name and module match,
|
228 |
+
or a subclass of *default_class* will be created with the correct name and module.
|
229 |
+
|
230 |
+
Created class definitions are cached per factory instance.
|
231 |
+
"""
|
232 |
+
# Check if we've got this class cached
|
233 |
+
klass = self.class_cache.get((module, name), None)
|
234 |
+
if klass is not None:
|
235 |
+
return klass
|
236 |
+
|
237 |
+
klass = self.special_cases.get((module, name), None)
|
238 |
+
|
239 |
+
if not klass:
|
240 |
+
# generate a new class def which inherits from the default fake class
|
241 |
+
klass = type(name, (self.default,), {"__module__": module})
|
242 |
+
|
243 |
+
self.class_cache[(module, name)] = klass
|
244 |
+
return klass
|
245 |
+
|
246 |
+
# Fake module implementation
|
247 |
+
|
248 |
+
class FakeModule(types.ModuleType):
|
249 |
+
"""
|
250 |
+
An object which pretends to be a module.
|
251 |
+
|
252 |
+
*name* is the name of the module and should be a ``"."`` separated
|
253 |
+
alphanumeric string.
|
254 |
+
|
255 |
+
On initialization the module is added to sys.modules so it can be
|
256 |
+
imported properly. Further if *name* is a submodule and if its parent
|
257 |
+
does not exist, it will automatically create a parent :class:`FakeModule`.
|
258 |
+
This operates recursively until the parent is a top-level module or
|
259 |
+
when the parent is an existing module.
|
260 |
+
|
261 |
+
If any fake submodules are removed from this module they will
|
262 |
+
automatically be removed from :data:`sys.modules`.
|
263 |
+
|
264 |
+
Just as :class:`FakeClassType`, it supports comparison with
|
265 |
+
:class:`FakeClassType` instances, using the following logic:
|
266 |
+
|
267 |
+
If the object does not have ``other.__name__`` set, they are not equal.
|
268 |
+
|
269 |
+
Else if the other object does not have ``other.__module__`` set, they are equal if:
|
270 |
+
``self.__name__ == other.__name__``
|
271 |
+
|
272 |
+
Else, they are equal if:
|
273 |
+
``self.__name__ == other.__module__ + "." + other.__name__``
|
274 |
+
|
275 |
+
Using this behaviour, ``==``, ``!=``, ``hash()``, ``isinstance()`` and ``issubclass()``
|
276 |
+
are implemented allowing comparison between :class:`FakeClassType` instances
|
277 |
+
and :class:`FakeModule` instances to succeed if they are pretending to bein the same
|
278 |
+
place in the python module hierarchy.
|
279 |
+
|
280 |
+
It inherits from :class:`types.ModuleType`.
|
281 |
+
"""
|
282 |
+
def __init__(self, name):
|
283 |
+
super(FakeModule, self).__init__(name)
|
284 |
+
sys.modules[name] = self
|
285 |
+
|
286 |
+
if "." in name:
|
287 |
+
parent_name, child_name = name.rsplit(".", 1)
|
288 |
+
|
289 |
+
try:
|
290 |
+
__import__(parent_name)
|
291 |
+
parent = sys.modules[parent_name]
|
292 |
+
except:
|
293 |
+
parent = FakeModule(parent_name)
|
294 |
+
setattr(parent, child_name, self)
|
295 |
+
|
296 |
+
def __repr__(self):
|
297 |
+
return "<module '{0}' (fake)>".format(self.__name__)
|
298 |
+
|
299 |
+
def __str__(self):
|
300 |
+
return self.__repr__()
|
301 |
+
|
302 |
+
def __setattr__(self, name, value):
|
303 |
+
# If a fakemodule is removed we need to remove its entry from sys.modules
|
304 |
+
if (name in self.__dict__ and
|
305 |
+
isinstance(self.__dict__[name], FakeModule) and not
|
306 |
+
isinstance(value, FakeModule)):
|
307 |
+
|
308 |
+
self.__dict__[name]._remove()
|
309 |
+
self.__dict__[name] = value
|
310 |
+
|
311 |
+
def __delattr__(self, name):
|
312 |
+
if isinstance(self.__dict__[name], FakeModule):
|
313 |
+
self.__dict__[name]._remove()
|
314 |
+
del self.__dict__[name]
|
315 |
+
|
316 |
+
def _remove(self):
|
317 |
+
"""
|
318 |
+
Removes this module from :data:`sys.modules` and calls :meth:`_remove` on any
|
319 |
+
sub-FakeModules.
|
320 |
+
"""
|
321 |
+
for i in tuple(self.__dict__.keys()):
|
322 |
+
if isinstance(self.__dict__[i], FakeModule):
|
323 |
+
self.__dict__[i]._remove()
|
324 |
+
del self.__dict__[i]
|
325 |
+
del sys.modules[self.__name__]
|
326 |
+
|
327 |
+
def __eq__(self, other):
|
328 |
+
if not hasattr(other, "__name__"):
|
329 |
+
return False
|
330 |
+
othername = other.__name__
|
331 |
+
if hasattr(other, "__module__"):
|
332 |
+
othername = other.__module__ + "." + other.__name__
|
333 |
+
|
334 |
+
return self.__name__ == othername
|
335 |
+
|
336 |
+
def __ne__(self, other):
|
337 |
+
return not self == other
|
338 |
+
|
339 |
+
def __hash__(self):
|
340 |
+
return hash(self.__name__)
|
341 |
+
|
342 |
+
def __instancecheck__(self, instance):
|
343 |
+
return self.__subclasscheck__(instance.__class__)
|
344 |
+
|
345 |
+
def __subclasscheck__(self, subclass):
|
346 |
+
return (self == subclass or
|
347 |
+
(bool(subclass.__bases__) and
|
348 |
+
any(self.__subclasscheck__(base) for base in subclass.__bases__)))
|
349 |
+
|
350 |
+
class FakePackage(FakeModule):
|
351 |
+
"""
|
352 |
+
A :class:`FakeModule` subclass which lazily creates :class:`FakePackage`
|
353 |
+
instances on its attributes when they're requested.
|
354 |
+
|
355 |
+
This ensures that any attribute of this module is a valid FakeModule
|
356 |
+
which can be used to compare against fake classes.
|
357 |
+
"""
|
358 |
+
__path__ = []
|
359 |
+
|
360 |
+
def __call__(self, *args, **kwargs):
|
361 |
+
# This mainly exists to print a nicer error message when
|
362 |
+
# someone tries to call a FakePackage instance
|
363 |
+
raise TypeError("'{0}' FakePackage object is not callable".format(self.__name__))
|
364 |
+
|
365 |
+
def __getattr__(self, name):
|
366 |
+
modname = self.__name__ + "." + name
|
367 |
+
mod = sys.modules.get(modname, None)
|
368 |
+
if mod is None:
|
369 |
+
try:
|
370 |
+
__import__(modname)
|
371 |
+
except:
|
372 |
+
mod = FakePackage(modname)
|
373 |
+
else:
|
374 |
+
mod = sys.modules[modname]
|
375 |
+
return mod
|
376 |
+
|
377 |
+
class FakePackageLoader(object):
|
378 |
+
"""
|
379 |
+
A :term:`loader` of :class:`FakePackage` modules. When added to
|
380 |
+
:data:`sys.meta_path` it will ensure that any attempt to import
|
381 |
+
module *root* or its submodules results in a FakePackage.
|
382 |
+
|
383 |
+
Together with the attribute creation from :class:`FakePackage`
|
384 |
+
this ensures that any attempt to get a submodule from module *root*
|
385 |
+
results in a FakePackage, creating the illusion that *root* is an
|
386 |
+
actual package tree.
|
387 |
+
"""
|
388 |
+
def __init__(self, root):
|
389 |
+
self.root = root
|
390 |
+
|
391 |
+
def find_module(self, fullname, path=None):
|
392 |
+
if fullname == self.root or fullname.startswith(self.root + "."):
|
393 |
+
return self
|
394 |
+
else:
|
395 |
+
return None
|
396 |
+
|
397 |
+
def load_module(self, fullname):
|
398 |
+
return FakePackage(fullname)
|
399 |
+
|
400 |
+
# Fake unpickler implementation
|
401 |
+
|
402 |
+
class FakeUnpicklingError(pickle.UnpicklingError):
|
403 |
+
"""
|
404 |
+
Error raised when there is not enough information to perform the fake
|
405 |
+
unpickling process completely. It inherits from :exc:`pickle.UnpicklingError`.
|
406 |
+
"""
|
407 |
+
pass
|
408 |
+
|
409 |
+
class FakeUnpickler(pickle.Unpickler if PY2 else pickle._Unpickler):
|
410 |
+
"""
|
411 |
+
A forgiving unpickler. On uncountering references to class definitions
|
412 |
+
in the pickle stream which it cannot locate, it will create fake classes
|
413 |
+
and if necessary fake modules to house them in. Since it still allows access
|
414 |
+
to all modules and builtins, it should only be used to unpickle trusted data.
|
415 |
+
|
416 |
+
*file* is the :term:`binary file` to unserialize.
|
417 |
+
|
418 |
+
The optional keyword arguments are *class_factory*, *encoding and *errors*.
|
419 |
+
*class_factory* can be used to control how the missing class definitions are
|
420 |
+
created. If set to ``None``, ``FakeClassFactory((), FakeStrict)`` will be used.
|
421 |
+
|
422 |
+
In Python 3, the optional keyword arguments *encoding* and *errors* can be used
|
423 |
+
to indicate how the unpickler should deal with pickle streams generated in python
|
424 |
+
2, specifically how to deal with 8-bit string instances. If set to "bytes" it will
|
425 |
+
load them as bytes objects, otherwise it will attempt to decode them into unicode
|
426 |
+
using the given *encoding* and *errors* arguments.
|
427 |
+
|
428 |
+
It inherits from :class:`pickle.Unpickler`. (In Python 3 this is actually
|
429 |
+
``pickle._Unpickler``)
|
430 |
+
"""
|
431 |
+
if PY2:
|
432 |
+
def __init__(self, file, class_factory=None, encoding="bytes", errors="strict"):
|
433 |
+
pickle.Unpickler.__init__(self, file,)
|
434 |
+
self.class_factory = class_factory or FakeClassFactory()
|
435 |
+
else:
|
436 |
+
def __init__(self, file, class_factory=None, encoding="bytes", errors="strict"):
|
437 |
+
super().__init__(file, fix_imports=False, encoding=encoding, errors=errors)
|
438 |
+
self.class_factory = class_factory or FakeClassFactory()
|
439 |
+
|
440 |
+
def find_class(self, module, name):
|
441 |
+
mod = sys.modules.get(module, None)
|
442 |
+
if mod is None:
|
443 |
+
try:
|
444 |
+
__import__(module)
|
445 |
+
except:
|
446 |
+
mod = FakeModule(module)
|
447 |
+
else:
|
448 |
+
mod = sys.modules[module]
|
449 |
+
|
450 |
+
klass = getattr(mod, name, None)
|
451 |
+
if klass is None or isinstance(klass, FakeModule):
|
452 |
+
klass = self.class_factory(name, module)
|
453 |
+
setattr(mod, name, klass)
|
454 |
+
|
455 |
+
return klass
|
456 |
+
|
457 |
+
class SafeUnpickler(FakeUnpickler):
|
458 |
+
"""
|
459 |
+
A safe unpickler. It will create fake classes for any references to class
|
460 |
+
definitions in the pickle stream. Further it can block access to the extension
|
461 |
+
registry making this unpickler safe to use on untrusted data.
|
462 |
+
|
463 |
+
*file* is the :term:`binary file` to unserialize.
|
464 |
+
|
465 |
+
The optional keyword arguments are *class_factory*, *safe_modules*, *use_copyreg*,
|
466 |
+
*encoding* and *errors*. *class_factory* can be used to control how the missing class
|
467 |
+
definitions are created. If set to ``None``, ``FakeClassFactory((), FakeStrict)`` will be
|
468 |
+
used. *safe_modules* can be set to a set of strings of module names, which will be
|
469 |
+
regarded as safe by the unpickling process, meaning that it will import objects
|
470 |
+
from that module instead of generating fake classes (this does not apply to objects
|
471 |
+
in submodules). *use_copyreg* is a boolean value indicating if it's allowed to
|
472 |
+
use extensions from the pickle extension registry (documented in the :mod:`copyreg`
|
473 |
+
module).
|
474 |
+
|
475 |
+
In Python 3, the optional keyword arguments *encoding* and *errors* can be used
|
476 |
+
to indicate how the unpickler should deal with pickle streams generated in python
|
477 |
+
2, specifically how to deal with 8-bit string instances. If set to "bytes" it will
|
478 |
+
load them as bytes objects, otherwise it will attempt to decode them into unicode
|
479 |
+
using the given *encoding* and *errors* arguments.
|
480 |
+
|
481 |
+
This function can be used to unpickle untrusted data safely with the default
|
482 |
+
class_factory when *safe_modules* is empty and *use_copyreg* is False.
|
483 |
+
It inherits from :class:`pickle.Unpickler`. (In Python 3 this is actually
|
484 |
+
``pickle._Unpickler``)
|
485 |
+
|
486 |
+
It should be noted though that when the unpickler tries to get a nonexistent
|
487 |
+
attribute of a safe module, an :exc:`AttributeError` will be raised.
|
488 |
+
|
489 |
+
This inherits from :class:`FakeUnpickler`
|
490 |
+
"""
|
491 |
+
def __init__(self, file, class_factory=None, safe_modules=(),
|
492 |
+
use_copyreg=False, encoding="bytes", errors="strict"):
|
493 |
+
FakeUnpickler.__init__(self, file, class_factory, encoding=encoding, errors=errors)
|
494 |
+
# A set of modules which are safe to load
|
495 |
+
self.safe_modules = set(safe_modules)
|
496 |
+
self.use_copyreg = use_copyreg
|
497 |
+
|
498 |
+
def find_class(self, module, name):
|
499 |
+
if module in self.safe_modules:
|
500 |
+
__import__(module)
|
501 |
+
mod = sys.modules[module]
|
502 |
+
klass = getattr(mod, name)
|
503 |
+
return klass
|
504 |
+
|
505 |
+
else:
|
506 |
+
return self.class_factory(name, module)
|
507 |
+
|
508 |
+
def get_extension(self, code):
|
509 |
+
if self.use_copyreg:
|
510 |
+
return FakeUnpickler.get_extension(self, code)
|
511 |
+
else:
|
512 |
+
return self.class_factory("extension_code_{0}".format(code), "copyreg")
|
513 |
+
|
514 |
+
class SafePickler(pickle.Pickler if PY2 else pickle._Pickler):
|
515 |
+
"""
|
516 |
+
A pickler which can repickle object hierarchies containing objects created by SafeUnpickler.
|
517 |
+
Due to reasons unknown, pythons pickle implementation will normally check if a given class
|
518 |
+
actually matches with the object specified at the __module__ and __name__ of the class. Since
|
519 |
+
this check is performed with object identity instead of object equality we cannot fake this from
|
520 |
+
the classes themselves, and we need to override the method used for normally saving classes.
|
521 |
+
"""
|
522 |
+
|
523 |
+
def save_global(self, obj, name=None, pack=struct.pack):
|
524 |
+
if isinstance(obj, FakeClassType):
|
525 |
+
self.write(pickle.GLOBAL + obj.__module__ + '\n' + obj.__name__ + '\n')
|
526 |
+
self.memoize(obj)
|
527 |
+
return
|
528 |
+
|
529 |
+
pickle.Pickler.save_global(self, obj, name, pack)
|
530 |
+
|
531 |
+
# the main API
|
532 |
+
|
533 |
+
def load(file, class_factory=None, encoding="bytes", errors="errors"):
|
534 |
+
"""
|
535 |
+
Read a pickled object representation from the open binary :term:`file object` *file*
|
536 |
+
and return the reconstitutded object hierarchy specified therein, generating
|
537 |
+
any missing class definitions at runtime. This is equivalent to
|
538 |
+
``FakeUnpickler(file).load()``.
|
539 |
+
|
540 |
+
The optional keyword arguments are *class_factory*, *encoding* and *errors*.
|
541 |
+
*class_factory* can be used to control how the missing class definitions are
|
542 |
+
created. If set to ``None``, ``FakeClassFactory({}, 'strict')`` will be used.
|
543 |
+
|
544 |
+
In Python 3, the optional keyword arguments *encoding* and *errors* can be used
|
545 |
+
to indicate how the unpickler should deal with pickle streams generated in python
|
546 |
+
2, specifically how to deal with 8-bit string instances. If set to "bytes" it will
|
547 |
+
load them as bytes objects, otherwise it will attempt to decode them into unicode
|
548 |
+
using the given *encoding* and *errors* arguments.
|
549 |
+
|
550 |
+
This function should only be used to unpickle trusted data.
|
551 |
+
"""
|
552 |
+
return FakeUnpickler(file, class_factory, encoding=encoding, errors=errors).load()
|
553 |
+
|
554 |
+
def loads(string, class_factory=None, encoding="bytes", errors="errors"):
|
555 |
+
"""
|
556 |
+
Simjilar to :func:`load`, but takes an 8-bit string (bytes in Python 3, str in Python 2)
|
557 |
+
as its first argument instead of a binary :term:`file object`.
|
558 |
+
"""
|
559 |
+
return FakeUnpickler(StringIO(string), class_factory,
|
560 |
+
encoding=encoding, errors=errors).load()
|
561 |
+
|
562 |
+
def safe_load(file, class_factory=None, safe_modules=(), use_copyreg=False,
|
563 |
+
encoding="bytes", errors="errors"):
|
564 |
+
"""
|
565 |
+
Read a pickled object representation from the open binary :term:`file object` *file*
|
566 |
+
and return the reconstitutded object hierarchy specified therein, substituting any
|
567 |
+
class definitions by fake classes, ensuring safety in the unpickling process.
|
568 |
+
This is equivalent to ``SafeUnpickler(file).load()``.
|
569 |
+
|
570 |
+
The optional keyword arguments are *class_factory*, *safe_modules*, *use_copyreg*,
|
571 |
+
*encoding* and *errors*. *class_factory* can be used to control how the missing class
|
572 |
+
definitions are created. If set to ``None``, ``FakeClassFactory({}, 'strict')`` will be
|
573 |
+
used. *safe_modules* can be set to a set of strings of module names, which will be
|
574 |
+
regarded as safe by the unpickling process, meaning that it will import objects
|
575 |
+
from that module instead of generating fake classes (this does not apply to objects
|
576 |
+
in submodules). *use_copyreg* is a boolean value indicating if it's allowed to
|
577 |
+
use extensions from the pickle extension registry (documented in the :mod:`copyreg`
|
578 |
+
module).
|
579 |
+
|
580 |
+
In Python 3, the optional keyword arguments *encoding* and *errors* can be used
|
581 |
+
to indicate how the unpickler should deal with pickle streams generated in python
|
582 |
+
2, specifically how to deal with 8-bit string instances. If set to "bytes" it will
|
583 |
+
load them as bytes objects, otherwise it will attempt to decode them into unicode
|
584 |
+
using the given *encoding* and *errors* arguments.
|
585 |
+
|
586 |
+
This function can be used to unpickle untrusted data safely with the default
|
587 |
+
class_factory when *safe_modules* is empty and *use_copyreg* is False.
|
588 |
+
"""
|
589 |
+
return SafeUnpickler(file, class_factory, safe_modules, use_copyreg,
|
590 |
+
encoding=encoding, errors=errors).load()
|
591 |
+
|
592 |
+
def safe_loads(string, class_factory=None, safe_modules=(), use_copyreg=False,
|
593 |
+
encoding="bytes", errors="errors"):
|
594 |
+
"""
|
595 |
+
Similar to :func:`safe_load`, but takes an 8-bit string (bytes in Python 3, str in Python 2)
|
596 |
+
as its first argument instead of a binary :term:`file object`.
|
597 |
+
"""
|
598 |
+
return SafeUnpickler(StringIO(string), class_factory, safe_modules, use_copyreg,
|
599 |
+
encoding=encoding, errors=errors).load()
|
600 |
+
|
601 |
+
def safe_dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL):
|
602 |
+
"""
|
603 |
+
A convenience function wrapping SafePickler. It functions similarly to pickle.dump
|
604 |
+
"""
|
605 |
+
SafePickler(file, protocol).dump(obj)
|
606 |
+
|
607 |
+
def safe_dumps(obj, protocol=pickle.HIGHEST_PROTOCOL):
|
608 |
+
"""
|
609 |
+
A convenience function wrapping SafePickler. It functions similarly to pickle.dumps
|
610 |
+
"""
|
611 |
+
file = StringIO()
|
612 |
+
SafePickler(file, protocol).dump(obj)
|
613 |
+
return file.getvalue()
|
614 |
+
|
615 |
+
def fake_package(name):
|
616 |
+
"""
|
617 |
+
Mounts a fake package tree with the name *name*. This causes any attempt to import
|
618 |
+
module *name*, attributes of the module or submodules will return a :class:`FakePackage`
|
619 |
+
instance which implements the same behaviour. These :class:`FakePackage` instances compare
|
620 |
+
properly with :class:`FakeClassType` instances allowing you to code using FakePackages as
|
621 |
+
if the modules and their attributes actually existed.
|
622 |
+
|
623 |
+
This is implemented by creating a :class:`FakePackageLoader` instance with root *name*
|
624 |
+
and inserting it in the first spot in :data:`sys.meta_path`. This ensures that importing the
|
625 |
+
module and submodules will work properly. Further the :class:`FakePackage` instances take
|
626 |
+
care of generating submodules as attributes on request.
|
627 |
+
|
628 |
+
If a fake package tree with the same *name* is already registered, no new fake package
|
629 |
+
tree will be mounted.
|
630 |
+
|
631 |
+
This returns the :class:`FakePackage` instance *name*.
|
632 |
+
"""
|
633 |
+
if name in sys.modules and isinstance(sys.modules[name], FakePackage):
|
634 |
+
return sys.modules[name]
|
635 |
+
else:
|
636 |
+
loader = FakePackageLoader(name)
|
637 |
+
sys.meta_path.insert(0, loader)
|
638 |
+
return __import__(name)
|
639 |
+
|
640 |
+
def remove_fake_package(name):
|
641 |
+
"""
|
642 |
+
Removes the fake package tree mounted at *name*.
|
643 |
+
|
644 |
+
This works by first looking for any FakePackageLoaders in :data:`sys.path`
|
645 |
+
with their root set to *name* and removing them from sys.path. Next it will
|
646 |
+
find the top-level :class:`FakePackage` instance *name* and from this point
|
647 |
+
traverse the tree of created submodules, removing them from :data:`sys.path`
|
648 |
+
and removing their attributes. After this the modules are not registered
|
649 |
+
anymore and if they are not referenced from user code anymore they will be
|
650 |
+
garbage collected.
|
651 |
+
|
652 |
+
If no fake package tree *name* exists a :exc:`ValueError` will be raised.
|
653 |
+
"""
|
654 |
+
|
655 |
+
# Get the package entry via its entry in sys.modules
|
656 |
+
package = sys.modules.get(name, None)
|
657 |
+
if package is None:
|
658 |
+
raise ValueError("No fake package with the name {0} found".format(name))
|
659 |
+
|
660 |
+
if not isinstance(package, FakePackage):
|
661 |
+
raise ValueError("The module {0} is not a fake package".format(name))
|
662 |
+
|
663 |
+
# Attempt to remove the loader from sys.meta_path
|
664 |
+
|
665 |
+
loaders = [i for i in sys.meta_path if isinstance(i, FakePackageLoader) and i.root == name]
|
666 |
+
for loader in loaders:
|
667 |
+
sys.meta_path.remove(loader)
|
668 |
+
|
669 |
+
# Remove all module and submodule entries from sys.modules
|
670 |
+
package._remove()
|
671 |
+
|
672 |
+
# It is impossible to kill references to the modules, but all traces
|
673 |
+
# of it have been removed from the import machinery and the submodule
|
674 |
+
# tree structure has been broken up.
|
renpy/rpycdec/rpycdecdata/decompiler/magic.pyo
ADDED
Binary file (37 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/screendecompiler.py
ADDED
@@ -0,0 +1,678 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2014 CensoredUsername
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
from __future__ import unicode_literals
|
22 |
+
|
23 |
+
import re
|
24 |
+
import ast
|
25 |
+
from operator import itemgetter
|
26 |
+
from contextlib import contextmanager
|
27 |
+
|
28 |
+
from util import DecompilerBase, WordConcatenator, reconstruct_paraminfo, \
|
29 |
+
simple_expression_guard, split_logical_lines, Dispatcher
|
30 |
+
import codegen
|
31 |
+
|
32 |
+
# Main API
|
33 |
+
|
34 |
+
def pprint(out_file, ast, indent_level=0, linenumber=1,
|
35 |
+
decompile_python=False,
|
36 |
+
skip_indent_until_write=False, printlock=None):
|
37 |
+
return SLDecompiler(out_file, printlock=printlock,
|
38 |
+
decompile_python=decompile_python).dump(
|
39 |
+
ast, indent_level, linenumber, skip_indent_until_write)
|
40 |
+
|
41 |
+
# implementation
|
42 |
+
|
43 |
+
class SLDecompiler(DecompilerBase):
|
44 |
+
"""
|
45 |
+
an object which handles the decompilation of renpy screen language 1 screens to a given stream
|
46 |
+
"""
|
47 |
+
|
48 |
+
# This dictionary is a mapping of string: unbound_method, which is used to determine
|
49 |
+
# what method to call for which statement
|
50 |
+
dispatch = Dispatcher()
|
51 |
+
|
52 |
+
def __init__(self, out_file=None, decompile_python=False,
|
53 |
+
indentation=" ", printlock=None):
|
54 |
+
super(SLDecompiler, self).__init__(out_file, indentation, printlock)
|
55 |
+
self.decompile_python = decompile_python
|
56 |
+
self.should_advance_to_line = True
|
57 |
+
self.is_root = True
|
58 |
+
|
59 |
+
def dump(self, ast, indent_level=0, linenumber=1, skip_indent_until_write=False):
|
60 |
+
self.indent_level = indent_level
|
61 |
+
self.linenumber = linenumber
|
62 |
+
self.skip_indent_until_write = skip_indent_until_write
|
63 |
+
self.print_screen(ast)
|
64 |
+
return self.linenumber
|
65 |
+
|
66 |
+
def advance_to_line(self, linenumber):
|
67 |
+
if self.should_advance_to_line:
|
68 |
+
super(SLDecompiler, self).advance_to_line(linenumber)
|
69 |
+
|
70 |
+
def save_state(self):
|
71 |
+
return (super(SLDecompiler, self).save_state(),
|
72 |
+
self.should_advance_to_line, self.is_root)
|
73 |
+
|
74 |
+
def commit_state(self, state):
|
75 |
+
super(SLDecompiler, self).commit_state(state[0])
|
76 |
+
|
77 |
+
def rollback_state(self, state):
|
78 |
+
self.should_advance_to_line = state[1]
|
79 |
+
self.is_root = state[2]
|
80 |
+
super(SLDecompiler, self).rollback_state(state[0])
|
81 |
+
|
82 |
+
def to_source(self, node):
|
83 |
+
return codegen.to_source(node, self.indentation, False, True)
|
84 |
+
|
85 |
+
@contextmanager
|
86 |
+
def not_root(self):
|
87 |
+
# Whenever anything except screen itself prints any child nodes, it
|
88 |
+
# should be inside a "with self.not_root()" block. It doesn't matter if
|
89 |
+
# you catch more inside of the with block than you need, as long as you
|
90 |
+
# don't fall back to calling print_python() from inside it.
|
91 |
+
is_root = self.is_root
|
92 |
+
self.is_root = False
|
93 |
+
try:
|
94 |
+
yield
|
95 |
+
finally:
|
96 |
+
self.is_root = is_root
|
97 |
+
|
98 |
+
# Entry point functions
|
99 |
+
|
100 |
+
def print_screen(self, ast):
|
101 |
+
# Here we do the processing of the screen statement, and we
|
102 |
+
# switch over to parsing of the python string representation
|
103 |
+
|
104 |
+
# Print the screen statement and create the block
|
105 |
+
self.indent()
|
106 |
+
self.write("screen %s" % ast.name)
|
107 |
+
# If we have parameters, print them.
|
108 |
+
if hasattr(ast, "parameters") and ast.parameters:
|
109 |
+
self.write(reconstruct_paraminfo(ast.parameters))
|
110 |
+
|
111 |
+
if ast.tag:
|
112 |
+
self.write(" tag %s" % ast.tag)
|
113 |
+
|
114 |
+
keywords = {ast.code.location[1]: WordConcatenator(False, True)}
|
115 |
+
for key in ('modal', 'zorder', 'variant', 'predict'):
|
116 |
+
value = getattr(ast, key)
|
117 |
+
# Non-Unicode strings are default values rather than user-supplied
|
118 |
+
# values, so we don't need to write them out.
|
119 |
+
if isinstance(value, unicode):
|
120 |
+
if value.linenumber not in keywords:
|
121 |
+
keywords[value.linenumber] = WordConcatenator(False, True)
|
122 |
+
keywords[value.linenumber].append("%s %s" % (key, value))
|
123 |
+
keywords = sorted([(k, v.join()) for k, v in keywords.items()],
|
124 |
+
key=itemgetter(0)) # so the first one is right
|
125 |
+
if self.decompile_python:
|
126 |
+
self.print_keywords_and_nodes(keywords, None, True)
|
127 |
+
with self.increase_indent():
|
128 |
+
self.indent()
|
129 |
+
self.write("python:")
|
130 |
+
with self.increase_indent():
|
131 |
+
# The first line is always "_1 = (_name, 0)", which gets included
|
132 |
+
# even if the python: block is the only thing in the screen. Don't
|
133 |
+
# include ours, since if we do, it'll be included twice when
|
134 |
+
# recompiled.
|
135 |
+
self.write_lines(self.to_source(ast.code.source).splitlines()[1:])
|
136 |
+
else:
|
137 |
+
self.print_keywords_and_nodes(keywords, ast.code.source.body, False)
|
138 |
+
|
139 |
+
def split_nodes_at_headers(self, nodes):
|
140 |
+
if not nodes:
|
141 |
+
return []
|
142 |
+
rv = [nodes[:1]]
|
143 |
+
parent_id = self.parse_header(nodes[0])
|
144 |
+
if parent_id is None:
|
145 |
+
raise Exception(
|
146 |
+
"First node passed to split_nodes_at_headers was not a header")
|
147 |
+
for i in nodes[1:]:
|
148 |
+
if self.parse_header(i) == parent_id:
|
149 |
+
rv.append([i])
|
150 |
+
header = i
|
151 |
+
else:
|
152 |
+
rv[-1].append(i)
|
153 |
+
return rv
|
154 |
+
|
155 |
+
def print_nodes(self, nodes, extra_indent=0, has_block=False):
|
156 |
+
# Print a block of statements, splitting it up on one level.
|
157 |
+
# The screen language parser emits lines in the shape _0 = (_0, 0) from which indentation can be revealed.
|
158 |
+
# It translates roughly to "id = (parent_id, index_in_parent_children)". When parsing a block
|
159 |
+
# parse the first header line to find the parent_id, and then split around headers with the same parent id
|
160 |
+
# in this block.
|
161 |
+
if has_block and not nodes:
|
162 |
+
raise BadHasBlockException()
|
163 |
+
split = self.split_nodes_at_headers(nodes)
|
164 |
+
with self.increase_indent(extra_indent):
|
165 |
+
for i in split:
|
166 |
+
self.print_node(i[0], i[1:], has_block)
|
167 |
+
|
168 |
+
def get_first_line(self, nodes):
|
169 |
+
if self.get_dispatch_key(nodes[0]):
|
170 |
+
return nodes[0].value.lineno
|
171 |
+
elif self.is_renpy_for(nodes):
|
172 |
+
return nodes[1].target.lineno
|
173 |
+
elif self.is_renpy_if(nodes):
|
174 |
+
return nodes[0].test.lineno
|
175 |
+
else:
|
176 |
+
# We should never get here, but just in case...
|
177 |
+
return nodes[0].lineno
|
178 |
+
|
179 |
+
def make_printable_keywords(self, keywords, lineno):
|
180 |
+
keywords = [(i.arg, simple_expression_guard(self.to_source(i.value)),
|
181 |
+
i.value.lineno) for i in keywords if not (isinstance(
|
182 |
+
i.value, ast.Name) and (
|
183 |
+
(i.arg == 'id' and i.value.id.startswith('_')) or
|
184 |
+
(i.arg == 'scope' and i.value.id == '_scope')))]
|
185 |
+
# Sort the keywords according to what line they belong on
|
186 |
+
# The first element always exists for the line the block starts on,
|
187 |
+
# even if there's no keywords that go on it
|
188 |
+
keywords_by_line = []
|
189 |
+
current_line = []
|
190 |
+
for i in keywords:
|
191 |
+
if i[2] > lineno:
|
192 |
+
keywords_by_line.append((lineno, ' '.join(current_line)))
|
193 |
+
lineno = i[2]
|
194 |
+
current_line = []
|
195 |
+
current_line.extend(i[:2])
|
196 |
+
keywords_by_line.append((lineno, ' '.join(current_line)))
|
197 |
+
return keywords_by_line
|
198 |
+
|
199 |
+
def print_keywords_and_nodes(self, keywords, nodes, needs_colon):
|
200 |
+
# Keywords and child nodes can be mixed with each other, so they need
|
201 |
+
# to be printed at the same time. This function takes each list and
|
202 |
+
# combines them into one, then prints it.
|
203 |
+
#
|
204 |
+
# This function assumes line numbers of nodes before keywords are
|
205 |
+
# correct, which is the case for the "screen" statement itself.
|
206 |
+
if keywords:
|
207 |
+
if keywords[0][1]:
|
208 |
+
self.write(" %s" % keywords[0][1])
|
209 |
+
if len(keywords) != 1:
|
210 |
+
needs_colon = True
|
211 |
+
if nodes:
|
212 |
+
nodelists = [(self.get_first_line(i[1:]), i)
|
213 |
+
for i in self.split_nodes_at_headers(nodes)]
|
214 |
+
needs_colon = True
|
215 |
+
else:
|
216 |
+
nodelists = []
|
217 |
+
if needs_colon:
|
218 |
+
self.write(":")
|
219 |
+
stuff_to_print = sorted(keywords[1:] + nodelists, key=itemgetter(0))
|
220 |
+
with self.increase_indent():
|
221 |
+
for i in stuff_to_print:
|
222 |
+
# Nodes are lists. Keywords are ready-to-print strings.
|
223 |
+
if type(i[1]) == list:
|
224 |
+
self.print_node(i[1][0], i[1][1:])
|
225 |
+
else:
|
226 |
+
self.advance_to_line(i[0])
|
227 |
+
self.indent()
|
228 |
+
self.write(i[1])
|
229 |
+
|
230 |
+
def get_lines_used_by_node(self, node):
|
231 |
+
state = self.save_state()
|
232 |
+
self.print_node(node[0], node[1:])
|
233 |
+
linenumber = self.linenumber
|
234 |
+
self.rollback_state(state)
|
235 |
+
return linenumber - self.linenumber
|
236 |
+
|
237 |
+
def print_buggy_keywords_and_nodes(self, keywords, nodes, needs_colon, has_block):
|
238 |
+
# Keywords and child nodes can be mixed with each other, so they need
|
239 |
+
# to be printed at the same time. This function takes each list and
|
240 |
+
# combines them into one, then prints it.
|
241 |
+
#
|
242 |
+
# This function assumes line numbers of nodes before keywords are
|
243 |
+
# incorrect, which is the case for everything except the "screen"
|
244 |
+
# statement itself.
|
245 |
+
last_keyword_lineno = None
|
246 |
+
if keywords:
|
247 |
+
if keywords[0][1]:
|
248 |
+
self.write(" %s" % keywords[0][1])
|
249 |
+
remaining_keywords = keywords[1:]
|
250 |
+
if remaining_keywords:
|
251 |
+
needs_colon = True
|
252 |
+
last_keyword_lineno = remaining_keywords[-1][0]
|
253 |
+
if nodes:
|
254 |
+
nodelists = [(self.get_first_line(i[1:]), i)
|
255 |
+
for i in self.split_nodes_at_headers(nodes)]
|
256 |
+
else:
|
257 |
+
nodelists = []
|
258 |
+
for key, value in enumerate(nodelists):
|
259 |
+
if last_keyword_lineno is None or value[0] > last_keyword_lineno:
|
260 |
+
nodes_before_keywords = nodelists[:key]
|
261 |
+
nodes_after_keywords = nodelists[key:]
|
262 |
+
break
|
263 |
+
else:
|
264 |
+
nodes_before_keywords = nodelists
|
265 |
+
nodes_after_keywords = []
|
266 |
+
if nodes_before_keywords or (not has_block and nodes_after_keywords):
|
267 |
+
needs_colon = True
|
268 |
+
if needs_colon:
|
269 |
+
self.write(":")
|
270 |
+
with self.increase_indent():
|
271 |
+
should_advance_to_line = self.should_advance_to_line
|
272 |
+
self.should_advance_to_line = False
|
273 |
+
while nodes_before_keywords:
|
274 |
+
if not remaining_keywords:
|
275 |
+
# Something went wrong. We already printed the last keyword,
|
276 |
+
# yet there's still nodes left that should have been printed
|
277 |
+
# before the last keyword. Just print them now.
|
278 |
+
for i in nodes_before_keywords:
|
279 |
+
self.print_node(i[1][0], i[1][1:])
|
280 |
+
break
|
281 |
+
# subtract 1 line since .indent() uses 1
|
282 |
+
lines_to_go = remaining_keywords[0][0] - self.linenumber - 1
|
283 |
+
next_node = nodes_before_keywords[0][1]
|
284 |
+
if lines_to_go >= self.get_lines_used_by_node(next_node):
|
285 |
+
self.print_node(next_node[0], next_node[1:])
|
286 |
+
nodes_before_keywords.pop(0)
|
287 |
+
elif not should_advance_to_line or lines_to_go <= 0:
|
288 |
+
self.indent()
|
289 |
+
self.write(remaining_keywords.pop(0)[1])
|
290 |
+
else:
|
291 |
+
self.write("\n" * lines_to_go)
|
292 |
+
self.should_advance_to_line = should_advance_to_line
|
293 |
+
for i in remaining_keywords:
|
294 |
+
self.advance_to_line(i[0])
|
295 |
+
self.indent()
|
296 |
+
self.write(i[1])
|
297 |
+
with self.increase_indent(1 if not has_block else 0):
|
298 |
+
for i in nodes_after_keywords:
|
299 |
+
self.print_node(i[1][0], i[1][1:])
|
300 |
+
|
301 |
+
def get_dispatch_key(self, node):
|
302 |
+
if (isinstance(node, ast.Expr) and
|
303 |
+
isinstance(node.value, ast.Call) and
|
304 |
+
isinstance(node.value.func, ast.Attribute) and
|
305 |
+
isinstance(node.value.func.value, ast.Name)):
|
306 |
+
return node.value.func.value.id, node.value.func.attr
|
307 |
+
else:
|
308 |
+
return None
|
309 |
+
|
310 |
+
def print_node(self, header, code, has_block=False):
|
311 |
+
# Here we derermine how to handle a statement.
|
312 |
+
# To do this we look at how the first line in the statement code starts, after the header.
|
313 |
+
# Then we call the appropriate function as specified in ui_function_dict.
|
314 |
+
# If the statement is unknown, we can still emit valid screen code by just
|
315 |
+
# stuffing it inside a python block.
|
316 |
+
|
317 |
+
# There's 3 categories of things that we can convert to screencode:
|
318 |
+
# if statements, for statements, and function calls of the
|
319 |
+
# form "first.second(...)". Anything else gets converted to Python.
|
320 |
+
dispatch_key = self.get_dispatch_key(code[0])
|
321 |
+
if dispatch_key:
|
322 |
+
func = self.dispatch.get(dispatch_key, self.print_python.__func__)
|
323 |
+
if has_block:
|
324 |
+
if func not in (self.print_onechild.__func__,
|
325 |
+
self.print_manychildren.__func__):
|
326 |
+
raise BadHasBlockException()
|
327 |
+
func(self, header, code, True)
|
328 |
+
else:
|
329 |
+
func(self, header, code)
|
330 |
+
elif has_block:
|
331 |
+
raise BadHasBlockException()
|
332 |
+
elif self.is_renpy_for(code):
|
333 |
+
self.print_for(header, code)
|
334 |
+
elif self.is_renpy_if(code):
|
335 |
+
self.print_if(header, code)
|
336 |
+
else:
|
337 |
+
self.print_python(header, code)
|
338 |
+
# Helper printing functions
|
339 |
+
|
340 |
+
def print_args(self, node):
|
341 |
+
if node.args:
|
342 |
+
self.write(" " + " ".join([simple_expression_guard(
|
343 |
+
self.to_source(i)) for i in node.args]))
|
344 |
+
|
345 |
+
# Node printing functions
|
346 |
+
|
347 |
+
def print_python(self, header, code):
|
348 |
+
# This function handles any statement which is a block but couldn't logically be
|
349 |
+
# Translated to a screen statement.
|
350 |
+
#
|
351 |
+
# Ren'Py's line numbers are really, really buggy. Here's a summary:
|
352 |
+
# If we're not directly under the root screen, and a keyword for our
|
353 |
+
# parent follows us, then all of our line numbers will be equal to the
|
354 |
+
# line number of that keyword.
|
355 |
+
# If we're not directly under the root screen, and no keywords for our
|
356 |
+
# parent follow us, then header.lineno is the line number of whatever
|
357 |
+
# it is that preceded us (which is completely useless).
|
358 |
+
# If we're directly under the root "screen", then header.lineno is the
|
359 |
+
# line that "$" or "python:" appeared on.
|
360 |
+
# If we're not a child followed by a keyword, and "$" was used, then
|
361 |
+
# code[0].lineno is the line that the code actually starts on, but if
|
362 |
+
# "python:" was used, then all of code's line numbers will be 1 greater
|
363 |
+
# than the line each one should be.
|
364 |
+
source = self.to_source(ast.Module(body=code,
|
365 |
+
lineno=code[0].lineno,
|
366 |
+
col_offset=0)).rstrip().lstrip('\n')
|
367 |
+
lines = source.splitlines()
|
368 |
+
if len(split_logical_lines(source)) == 1 and (
|
369 |
+
(not self.is_root and code[0].lineno < self.linenumber + 3) or
|
370 |
+
header.lineno >= code[0].lineno):
|
371 |
+
# This is only one logical line, so it's possible that it was $,
|
372 |
+
# and either it's not in the root (so we don't know what the
|
373 |
+
# original source used), or it is in the root and we know it used $.
|
374 |
+
# Also, if we don't know for sure what was used, but we have enough
|
375 |
+
# room to use a "python" block, then use it instead, since it'll
|
376 |
+
# result in everything taking up one fewer line (since it'll use
|
377 |
+
# one more, but start two sooner).
|
378 |
+
self.advance_to_line(code[0].lineno)
|
379 |
+
self.indent()
|
380 |
+
self.write("$ %s" % lines[0])
|
381 |
+
self.write_lines(lines[1:])
|
382 |
+
else:
|
383 |
+
# Either this is more than one logical line, so it has to be a
|
384 |
+
# python block, or it was in the root and we can tell that it was
|
385 |
+
# originally a python block.
|
386 |
+
if self.is_root:
|
387 |
+
self.advance_to_line(header.lineno)
|
388 |
+
self.indent()
|
389 |
+
self.write("python:")
|
390 |
+
self.advance_to_line(code[0].lineno - 1)
|
391 |
+
with self.increase_indent():
|
392 |
+
self.write_lines(lines)
|
393 |
+
|
394 |
+
def is_renpy_if(self, nodes):
|
395 |
+
return len(nodes) == 1 and isinstance(nodes[0], ast.If) and (
|
396 |
+
nodes[0].body and self.parse_header(nodes[0].body[0])) and (
|
397 |
+
not nodes[0].orelse or self.is_renpy_if(nodes[0].orelse) or
|
398 |
+
self.parse_header(nodes[0].orelse[0]))
|
399 |
+
|
400 |
+
def is_renpy_for(self, nodes):
|
401 |
+
return (len(nodes) == 2 and isinstance(nodes[0], ast.Assign) and
|
402 |
+
len(nodes[0].targets) == 1 and
|
403 |
+
isinstance(nodes[0].targets[0], ast.Name) and
|
404 |
+
re.match(r"_[0-9]+$", nodes[0].targets[0].id) and
|
405 |
+
isinstance(nodes[0].value, ast.Num) and nodes[0].value.n == 0 and
|
406 |
+
isinstance(nodes[1], ast.For) and not nodes[1].orelse and
|
407 |
+
nodes[1].body and self.parse_header(nodes[1].body[0]) and
|
408 |
+
isinstance(nodes[1].body[-1], ast.AugAssign) and
|
409 |
+
isinstance(nodes[1].body[-1].op, ast.Add) and
|
410 |
+
isinstance(nodes[1].body[-1].target, ast.Name) and
|
411 |
+
re.match(r"_[0-9]+$", nodes[1].body[-1].target.id) and
|
412 |
+
isinstance(nodes[1].body[-1].value, ast.Num) and
|
413 |
+
nodes[1].body[-1].value.n == 1)
|
414 |
+
|
415 |
+
def strip_parens(self, text):
|
416 |
+
if text and text[0] == '(' and text[-1] == ')':
|
417 |
+
return text[1:-1]
|
418 |
+
else:
|
419 |
+
return text
|
420 |
+
|
421 |
+
def print_if(self, header, code):
|
422 |
+
# Here we handle the if statement. It might be valid python but we can check for this by
|
423 |
+
# checking for the header that should normally occur within the if statement.
|
424 |
+
# The if statement parser might also generate a second header if there's more than one screen
|
425 |
+
# statement enclosed in the if/elif/else statements. We'll take care of that too.
|
426 |
+
self.advance_to_line(self.get_first_line(code))
|
427 |
+
self.indent()
|
428 |
+
self.write("if %s:" % self.strip_parens(self.to_source(code[0].test)))
|
429 |
+
if (len(code[0].body) >= 2 and self.parse_header(code[0].body[0]) and
|
430 |
+
self.parse_header(code[0].body[1])):
|
431 |
+
body = code[0].body[1:]
|
432 |
+
else:
|
433 |
+
body = code[0].body
|
434 |
+
with self.not_root():
|
435 |
+
self.print_nodes(body, 1)
|
436 |
+
if code[0].orelse:
|
437 |
+
if self.is_renpy_if(code[0].orelse):
|
438 |
+
self.advance_to_line(code[0].orelse[0].test.lineno)
|
439 |
+
self.indent()
|
440 |
+
self.write("el") # beginning of "elif"
|
441 |
+
self.skip_indent_until_write = True
|
442 |
+
self.print_if(header, code[0].orelse)
|
443 |
+
else:
|
444 |
+
self.indent()
|
445 |
+
self.write("else:")
|
446 |
+
if (len(code[0].orelse) >= 2 and
|
447 |
+
self.parse_header(code[0].orelse[0]) and
|
448 |
+
self.parse_header(code[0].orelse[1])):
|
449 |
+
orelse = code[0].orelse[1:]
|
450 |
+
else:
|
451 |
+
orelse = code[0].orelse
|
452 |
+
self.print_nodes(orelse, 1)
|
453 |
+
|
454 |
+
def print_for(self, header, code):
|
455 |
+
# Here we handle the for statement. Note that the for statement generates some extra python code to
|
456 |
+
# Keep track of it's header indices. The first one is ignored by the statement parser,
|
457 |
+
# the second line is just ingored here.
|
458 |
+
line = code[1]
|
459 |
+
self.advance_to_line(self.get_first_line(code))
|
460 |
+
self.indent()
|
461 |
+
self.write("for %s in %s:" % (
|
462 |
+
self.strip_parens(self.to_source(line.target)),
|
463 |
+
self.to_source(line.iter)))
|
464 |
+
if (len(line.body) >= 3 and self.parse_header(line.body[0]) and
|
465 |
+
self.parse_header(line.body[1])):
|
466 |
+
body = line.body[1:]
|
467 |
+
else:
|
468 |
+
body = line.body
|
469 |
+
with self.not_root():
|
470 |
+
self.print_nodes(body[:-1], 1)
|
471 |
+
|
472 |
+
@dispatch(('renpy', 'use_screen'))
|
473 |
+
def print_use(self, header, code):
|
474 |
+
# This function handles the use statement, which translates into a python expression "renpy.use_screen".
|
475 |
+
# It would technically be possible for this to be a python statement, but the odds of this are very small.
|
476 |
+
# renpy itself will insert some kwargs, we'll delete those and then parse the command here.
|
477 |
+
if (len(code) != 1 or not code[0].value.args or
|
478 |
+
not isinstance(code[0].value.args[0], ast.Str)):
|
479 |
+
return self.print_python(header, code)
|
480 |
+
args, kwargs, exargs, exkwargs = self.parse_args(code[0])
|
481 |
+
kwargs = [(key, value) for key, value in kwargs if not
|
482 |
+
(key == '_scope' or key == '_name')]
|
483 |
+
|
484 |
+
self.advance_to_line(self.get_first_line(code))
|
485 |
+
self.indent()
|
486 |
+
self.write("use %s" % code[0].value.args[0].s)
|
487 |
+
args.pop(0)
|
488 |
+
|
489 |
+
arglist = []
|
490 |
+
if args or kwargs or exargs or exkwargs:
|
491 |
+
self.write("(")
|
492 |
+
arglist.extend(args)
|
493 |
+
arglist.extend("%s=%s" % i for i in kwargs)
|
494 |
+
if exargs:
|
495 |
+
arglist.append("*%s" % exargs)
|
496 |
+
if exkwargs:
|
497 |
+
arglist.append("**%s" % exkwargs)
|
498 |
+
self.write(", ".join(arglist))
|
499 |
+
self.write(")")
|
500 |
+
|
501 |
+
@dispatch(('_scope', 'setdefault'))
|
502 |
+
def print_default(self, header, code):
|
503 |
+
if (len(code) != 1 or code[0].value.keywords or code[0].value.kwargs or
|
504 |
+
len(code[0].value.args) != 2 or code[0].value.starargs or
|
505 |
+
not isinstance(code[0].value.args[0], ast.Str)):
|
506 |
+
return self.print_python(header, code)
|
507 |
+
self.advance_to_line(self.get_first_line(code))
|
508 |
+
self.indent()
|
509 |
+
self.write("default %s = %s" %
|
510 |
+
(code[0].value.args[0].s, self.to_source(code[0].value.args[1])))
|
511 |
+
|
512 |
+
# These never have a ui.close() at the end
|
513 |
+
@dispatch(('ui', 'add'))
|
514 |
+
@dispatch(('ui', 'imagebutton'))
|
515 |
+
@dispatch(('ui', 'input'))
|
516 |
+
@dispatch(('ui', 'key'))
|
517 |
+
@dispatch(('ui', 'label'))
|
518 |
+
@dispatch(('ui', 'text'))
|
519 |
+
@dispatch(('ui', 'null'))
|
520 |
+
@dispatch(('ui', 'mousearea'))
|
521 |
+
@dispatch(('ui', 'textbutton'))
|
522 |
+
@dispatch(('ui', 'timer'))
|
523 |
+
@dispatch(('ui', 'bar'))
|
524 |
+
@dispatch(('ui', 'vbar'))
|
525 |
+
@dispatch(('ui', 'hotbar'))
|
526 |
+
@dispatch(('ui', 'on'))
|
527 |
+
@dispatch(('ui', 'image'))
|
528 |
+
def print_nochild(self, header, code):
|
529 |
+
if len(code) != 1:
|
530 |
+
self.print_python(header, code)
|
531 |
+
return
|
532 |
+
line = code[0]
|
533 |
+
self.advance_to_line(self.get_first_line(code))
|
534 |
+
self.indent()
|
535 |
+
self.write(line.value.func.attr)
|
536 |
+
self.print_args(line.value)
|
537 |
+
with self.not_root():
|
538 |
+
self.print_buggy_keywords_and_nodes(
|
539 |
+
self.make_printable_keywords(line.value.keywords,
|
540 |
+
line.value.lineno),
|
541 |
+
None, False, False)
|
542 |
+
|
543 |
+
# These functions themselves don't have a ui.close() at the end, but
|
544 |
+
# they're always immediately followed by one that does (usually
|
545 |
+
# ui.child_or_fixed(), but also possibly one set with "has")
|
546 |
+
@dispatch(('ui', 'button'))
|
547 |
+
@dispatch(('ui', 'frame'))
|
548 |
+
@dispatch(('ui', 'transform'))
|
549 |
+
@dispatch(('ui', 'viewport'))
|
550 |
+
@dispatch(('ui', 'window'))
|
551 |
+
@dispatch(('ui', 'drag'))
|
552 |
+
@dispatch(('ui', 'hotspot_with_child'))
|
553 |
+
def print_onechild(self, header, code, has_block=False):
|
554 |
+
# We expect to have at least ourself, one child, and ui.close()
|
555 |
+
if len(code) < 3 or self.get_dispatch_key(code[-1]) != ('ui', 'close'):
|
556 |
+
if has_block:
|
557 |
+
raise BadHasBlockException()
|
558 |
+
self.print_python(header, code)
|
559 |
+
return
|
560 |
+
line = code[0]
|
561 |
+
name = line.value.func.attr
|
562 |
+
if name == 'hotspot_with_child':
|
563 |
+
name = 'hotspot'
|
564 |
+
if self.get_dispatch_key(code[1]) != ('ui', 'child_or_fixed'):
|
565 |
+
# Handle the case where a "has" statement was used
|
566 |
+
if has_block:
|
567 |
+
# Ren'Py lets users nest "has" blocks for some reason, and it
|
568 |
+
# puts the ui.close() statement in the wrong place when they do.
|
569 |
+
# Since we checked for ui.close() being in the right place
|
570 |
+
# before, the only way we could ever get here is if a user added
|
571 |
+
# one inside a python block at the end. If this happens, turn
|
572 |
+
# the whole outer block into Python instead of screencode.
|
573 |
+
raise BadHasBlockException()
|
574 |
+
if not self.parse_header(code[1]):
|
575 |
+
self.print_python(header, code)
|
576 |
+
return
|
577 |
+
block = code[1:]
|
578 |
+
state = self.save_state()
|
579 |
+
try:
|
580 |
+
self.advance_to_line(self.get_first_line(code))
|
581 |
+
self.indent()
|
582 |
+
self.write(name)
|
583 |
+
self.print_args(line.value)
|
584 |
+
with self.not_root():
|
585 |
+
self.print_buggy_keywords_and_nodes(
|
586 |
+
self.make_printable_keywords(line.value.keywords,
|
587 |
+
line.value.lineno),
|
588 |
+
None, True, False)
|
589 |
+
with self.increase_indent():
|
590 |
+
if len(block) > 1 and isinstance(block[1], ast.Expr):
|
591 |
+
# If this isn't true, we'll get a BadHasBlockException
|
592 |
+
# later anyway. This check is just to keep it from being
|
593 |
+
# an exception that we can't handle.
|
594 |
+
self.advance_to_line(block[1].value.lineno)
|
595 |
+
self.indent()
|
596 |
+
self.write("has ")
|
597 |
+
self.skip_indent_until_write = True
|
598 |
+
self.print_nodes(block, 1, True)
|
599 |
+
except BadHasBlockException as e:
|
600 |
+
self.rollback_state(state)
|
601 |
+
self.print_python(header, code)
|
602 |
+
else:
|
603 |
+
self.commit_state(state)
|
604 |
+
else:
|
605 |
+
# Remove ourself, ui.child_or_fixed(), and ui.close()
|
606 |
+
block = code[2:-1]
|
607 |
+
if block and not self.parse_header(block[0]):
|
608 |
+
if has_block:
|
609 |
+
raise BadHasBlockException()
|
610 |
+
self.print_python(header, code)
|
611 |
+
return
|
612 |
+
if not has_block:
|
613 |
+
self.advance_to_line(self.get_first_line(code))
|
614 |
+
self.indent()
|
615 |
+
self.write(name)
|
616 |
+
self.print_args(line.value)
|
617 |
+
with self.not_root():
|
618 |
+
self.print_buggy_keywords_and_nodes(
|
619 |
+
self.make_printable_keywords(line.value.keywords,
|
620 |
+
line.value.lineno),
|
621 |
+
block, False, has_block)
|
622 |
+
|
623 |
+
# These always have a ui.close() at the end
|
624 |
+
@dispatch(('ui', 'fixed'))
|
625 |
+
@dispatch(('ui', 'grid'))
|
626 |
+
@dispatch(('ui', 'hbox'))
|
627 |
+
@dispatch(('ui', 'side'))
|
628 |
+
@dispatch(('ui', 'vbox'))
|
629 |
+
@dispatch(('ui', 'imagemap'))
|
630 |
+
@dispatch(('ui', 'draggroup'))
|
631 |
+
def print_manychildren(self, header, code, has_block=False):
|
632 |
+
if (self.get_dispatch_key(code[-1]) != ('ui', 'close') or
|
633 |
+
(len(code) != 2 and not self.parse_header(code[1]))):
|
634 |
+
if has_block:
|
635 |
+
raise BadHasBlockException()
|
636 |
+
self.print_python(header, code)
|
637 |
+
return
|
638 |
+
line = code[0]
|
639 |
+
block = code[1:-1]
|
640 |
+
if not has_block:
|
641 |
+
self.advance_to_line(self.get_first_line(code))
|
642 |
+
self.indent()
|
643 |
+
self.write(line.value.func.attr)
|
644 |
+
self.print_args(line.value)
|
645 |
+
with self.not_root():
|
646 |
+
self.print_buggy_keywords_and_nodes(
|
647 |
+
self.make_printable_keywords(line.value.keywords,
|
648 |
+
line.value.lineno),
|
649 |
+
block, False, has_block)
|
650 |
+
|
651 |
+
# Parsing functions
|
652 |
+
|
653 |
+
def parse_header(self, header):
|
654 |
+
# Given a Python AST node, returns the parent ID if the node represents
|
655 |
+
# a header, or None otherwise.
|
656 |
+
if (isinstance(header, ast.Assign) and len(header.targets) == 1 and
|
657 |
+
isinstance(header.targets[0], ast.Name) and
|
658 |
+
re.match(r"_[0-9]+$", header.targets[0].id) and
|
659 |
+
isinstance(header.value, ast.Tuple) and
|
660 |
+
len(header.value.elts) == 2 and
|
661 |
+
isinstance(header.value.elts[0], ast.Name)):
|
662 |
+
parent_id = header.value.elts[0].id
|
663 |
+
index = header.value.elts[1]
|
664 |
+
if re.match(r"_([0-9]+|name)$", parent_id) and (
|
665 |
+
isinstance(index, ast.Num) or
|
666 |
+
(isinstance(index, ast.Name) and
|
667 |
+
re.match(r"_[0-9]+$", index.id))):
|
668 |
+
return parent_id
|
669 |
+
return None
|
670 |
+
|
671 |
+
def parse_args(self, node):
|
672 |
+
return ([self.to_source(i) for i in node.value.args],
|
673 |
+
[(i.arg, self.to_source(i.value)) for i in node.value.keywords],
|
674 |
+
node.value.starargs and self.to_source(node.value.starargs),
|
675 |
+
node.value.kwargs and self.to_source(node.value.kwargs))
|
676 |
+
|
677 |
+
class BadHasBlockException(Exception):
|
678 |
+
pass
|
renpy/rpycdec/rpycdecdata/decompiler/screendecompiler.pyo
ADDED
Binary file (24.3 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/sl2decompiler.py
ADDED
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2014 CensoredUsername
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
from __future__ import unicode_literals
|
22 |
+
import sys
|
23 |
+
from operator import itemgetter
|
24 |
+
|
25 |
+
from util import DecompilerBase, First, reconstruct_paraminfo, \
|
26 |
+
reconstruct_arginfo, split_logical_lines, Dispatcher
|
27 |
+
|
28 |
+
from renpy import ui, sl2
|
29 |
+
from renpy.ast import PyExpr
|
30 |
+
from renpy.text import text
|
31 |
+
from renpy.sl2 import sldisplayables as sld
|
32 |
+
from renpy.display import layout, behavior, im, motion, dragdrop
|
33 |
+
|
34 |
+
# Main API
|
35 |
+
|
36 |
+
def pprint(out_file, ast, print_atl_callback, indent_level=0, linenumber=1,
|
37 |
+
skip_indent_until_write=False, printlock=None, tag_outside_block=False):
|
38 |
+
return SL2Decompiler(print_atl_callback, out_file, printlock=printlock, tag_outside_block=tag_outside_block).dump(
|
39 |
+
ast, indent_level, linenumber, skip_indent_until_write)
|
40 |
+
|
41 |
+
# Implementation
|
42 |
+
|
43 |
+
class SL2Decompiler(DecompilerBase):
|
44 |
+
"""
|
45 |
+
An object which handles the decompilation of renpy screen language 2 screens to a given stream
|
46 |
+
"""
|
47 |
+
|
48 |
+
def __init__(self, print_atl_callback, out_file=None, indentation = ' ', printlock=None, tag_outside_block=False):
|
49 |
+
super(SL2Decompiler, self).__init__(out_file, indentation, printlock)
|
50 |
+
self.print_atl_callback = print_atl_callback
|
51 |
+
self.tag_outside_block = tag_outside_block
|
52 |
+
|
53 |
+
# This dictionary is a mapping of Class: unbound_method, which is used to determine
|
54 |
+
# what method to call for which slast class
|
55 |
+
dispatch = Dispatcher()
|
56 |
+
|
57 |
+
def print_node(self, ast):
|
58 |
+
self.advance_to_line(ast.location[1])
|
59 |
+
self.dispatch.get(type(ast), type(self).print_unknown)(self, ast)
|
60 |
+
|
61 |
+
@dispatch(sl2.slast.SLScreen)
|
62 |
+
def print_screen(self, ast):
|
63 |
+
|
64 |
+
# Print the screen statement and create the block
|
65 |
+
self.indent()
|
66 |
+
self.write("screen %s" % ast.name)
|
67 |
+
# If we have parameters, print them.
|
68 |
+
if ast.parameters:
|
69 |
+
self.write(reconstruct_paraminfo(ast.parameters))
|
70 |
+
|
71 |
+
# If we're decompiling screencode, print it. Else, insert a pass statement
|
72 |
+
self.print_keywords_and_children(ast.keyword,
|
73 |
+
ast.children, ast.location[1], tag=ast.tag, atl_transform=getattr(ast, 'atl_transform', None))
|
74 |
+
|
75 |
+
@dispatch(sl2.slast.SLIf)
|
76 |
+
def print_if(self, ast):
|
77 |
+
# if and showif share a lot of the same infrastructure
|
78 |
+
self._print_if(ast, "if")
|
79 |
+
|
80 |
+
@dispatch(sl2.slast.SLShowIf)
|
81 |
+
def print_showif(self, ast):
|
82 |
+
# so for if and showif we just call an underlying function with an extra argument
|
83 |
+
self._print_if(ast, "showif")
|
84 |
+
|
85 |
+
def _print_if(self, ast, keyword):
|
86 |
+
# the first condition is named if or showif, the rest elif
|
87 |
+
keyword = First(keyword, "elif")
|
88 |
+
for condition, block in ast.entries:
|
89 |
+
self.advance_to_line(block.location[1])
|
90 |
+
self.indent()
|
91 |
+
# if condition is None, this is the else clause
|
92 |
+
if condition is None:
|
93 |
+
self.write("else:")
|
94 |
+
else:
|
95 |
+
self.write("%s %s:" % (keyword(), condition))
|
96 |
+
|
97 |
+
# Every condition has a block of type slast.SLBlock
|
98 |
+
if block.keyword or block.children or getattr(block, 'atl_transform', None):
|
99 |
+
self.print_block(block)
|
100 |
+
else:
|
101 |
+
with self.increase_indent():
|
102 |
+
self.indent()
|
103 |
+
self.write("pass")
|
104 |
+
|
105 |
+
@dispatch(sl2.slast.SLBlock)
|
106 |
+
def print_block(self, ast):
|
107 |
+
# A block contains possible keyword arguments and a list of child nodes
|
108 |
+
# this is the reason if doesn't keep a list of children but special Blocks
|
109 |
+
self.print_keywords_and_children(ast.keyword, ast.children, None, atl_transform=getattr(ast, 'atl_transform', None))
|
110 |
+
|
111 |
+
@dispatch(sl2.slast.SLFor)
|
112 |
+
def print_for(self, ast):
|
113 |
+
# Since tuple unpickling is hard, renpy just gives up and inserts a
|
114 |
+
# $ a,b,c = _sl2_i after the for statement if any tuple unpacking was
|
115 |
+
# attempted in the for statement. Detect this and ignore this slast.SLPython entry
|
116 |
+
if ast.variable == "_sl2_i":
|
117 |
+
variable = ast.children[0].code.source[:-9]
|
118 |
+
children = ast.children[1:]
|
119 |
+
else:
|
120 |
+
variable = ast.variable.strip() + " "
|
121 |
+
children = ast.children
|
122 |
+
|
123 |
+
self.indent()
|
124 |
+
if hasattr(ast, "index_expression") and ast.index_expression is not None:
|
125 |
+
self.write("for %sindex %s in %s:" % (variable, ast.index_expression, ast.expression))
|
126 |
+
|
127 |
+
else:
|
128 |
+
self.write("for %sin %s:" % (variable, ast.expression))
|
129 |
+
|
130 |
+
# Interestingly, for doesn't contain a block, but just a list of child nodes
|
131 |
+
self.print_nodes(children, 1)
|
132 |
+
|
133 |
+
@dispatch(sl2.slast.SLPython)
|
134 |
+
def print_python(self, ast):
|
135 |
+
self.indent()
|
136 |
+
|
137 |
+
# Extract the source code from the slast.SLPython object. If it starts with a
|
138 |
+
# newline, print it as a python block, else, print it as a $ statement
|
139 |
+
code = ast.code.source
|
140 |
+
if code.startswith("\n"):
|
141 |
+
code = code[1:]
|
142 |
+
self.write("python:")
|
143 |
+
with self.increase_indent():
|
144 |
+
self.write_lines(split_logical_lines(code))
|
145 |
+
else:
|
146 |
+
self.write("$ %s" % code)
|
147 |
+
|
148 |
+
@dispatch(sl2.slast.SLPass)
|
149 |
+
def print_pass(self, ast):
|
150 |
+
# A pass statement
|
151 |
+
self.indent()
|
152 |
+
self.write("pass")
|
153 |
+
|
154 |
+
@dispatch(sl2.slast.SLUse)
|
155 |
+
def print_use(self, ast):
|
156 |
+
# A use statement requires reconstructing the arguments it wants to pass
|
157 |
+
self.indent()
|
158 |
+
self.write("use ")
|
159 |
+
args = reconstruct_arginfo(ast.args)
|
160 |
+
if isinstance(ast.target, PyExpr):
|
161 |
+
self.write("expression %s" % ast.target)
|
162 |
+
if args:
|
163 |
+
self.write(" pass ")
|
164 |
+
else:
|
165 |
+
self.write("%s" % ast.target)
|
166 |
+
|
167 |
+
self.write("%s" % reconstruct_arginfo(ast.args))
|
168 |
+
if hasattr(ast, 'id') and ast.id is not None:
|
169 |
+
self.write(" id %s" % ast.id)
|
170 |
+
|
171 |
+
if hasattr(ast, 'block') and ast.block:
|
172 |
+
self.write(":")
|
173 |
+
self.print_block(ast.block)
|
174 |
+
|
175 |
+
@dispatch(sl2.slast.SLTransclude)
|
176 |
+
def print_transclude(self, ast):
|
177 |
+
self.indent()
|
178 |
+
self.write("transclude")
|
179 |
+
|
180 |
+
@dispatch(sl2.slast.SLDefault)
|
181 |
+
def print_default(self, ast):
|
182 |
+
# A default statement
|
183 |
+
self.indent()
|
184 |
+
self.write("default %s = %s" % (ast.variable, ast.expression))
|
185 |
+
|
186 |
+
@dispatch(sl2.slast.SLDisplayable)
|
187 |
+
def print_displayable(self, ast, has_block=False):
|
188 |
+
# slast.SLDisplayable represents a variety of statements. We can figure out
|
189 |
+
# what statement it represents by analyzing the called displayable and style
|
190 |
+
# attributes.
|
191 |
+
key = (ast.displayable, ast.style)
|
192 |
+
nameAndChildren = self.displayable_names.get(key)
|
193 |
+
if nameAndChildren is None:
|
194 |
+
# This is either a displayable we don't know about, or a user-defined displayable
|
195 |
+
|
196 |
+
# workaround: assume the name of the displayable matches the given style
|
197 |
+
# this is rather often the case. However, as it may be wrong we have to
|
198 |
+
# print a debug message
|
199 |
+
nameAndChildren = (ast.style, 'many')
|
200 |
+
self.print_debug(
|
201 |
+
"""Warning: Encountered a user-defined displayable of type '{}'.
|
202 |
+
Unfortunately, the name of user-defined displayables is not recorded in the compiled file.
|
203 |
+
For now the style name '{}' will be substituted.
|
204 |
+
To check if this is correct, find the corresponding renpy.register_sl_displayable call.""".format(
|
205 |
+
ast.displayable, ast.style
|
206 |
+
)
|
207 |
+
)
|
208 |
+
(name, children) = nameAndChildren
|
209 |
+
self.indent()
|
210 |
+
self.write(name)
|
211 |
+
if ast.positional:
|
212 |
+
self.write(" " + " ".join(ast.positional))
|
213 |
+
if hasattr(ast, 'variable'):
|
214 |
+
variable = ast.variable
|
215 |
+
else:
|
216 |
+
variable = None
|
217 |
+
atl_transform = getattr(ast, 'atl_transform', None)
|
218 |
+
# The AST contains no indication of whether or not "has" blocks
|
219 |
+
# were used. We'll use one any time it's possible (except for
|
220 |
+
# directly nesting them, or if they wouldn't contain any children),
|
221 |
+
# since it results in cleaner code.
|
222 |
+
if (not has_block and children == 1 and len(ast.children) == 1 and
|
223 |
+
isinstance(ast.children[0], sl2.slast.SLDisplayable) and
|
224 |
+
ast.children[0].children and (not ast.keyword or
|
225 |
+
ast.children[0].location[1] > ast.keyword[-1][1].linenumber) and
|
226 |
+
(atl_transform is None or ast.children[0].location[1] > atl_transform.loc[1])):
|
227 |
+
self.print_keywords_and_children(ast.keyword, [],
|
228 |
+
ast.location[1], needs_colon=True, variable=variable, atl_transform=atl_transform)
|
229 |
+
self.advance_to_line(ast.children[0].location[1])
|
230 |
+
with self.increase_indent():
|
231 |
+
self.indent()
|
232 |
+
self.write("has ")
|
233 |
+
self.skip_indent_until_write = True
|
234 |
+
self.print_displayable(ast.children[0], True)
|
235 |
+
else:
|
236 |
+
self.print_keywords_and_children(ast.keyword, ast.children,
|
237 |
+
ast.location[1], has_block=has_block, variable=variable, atl_transform=atl_transform)
|
238 |
+
|
239 |
+
displayable_names = {
|
240 |
+
(behavior.OnEvent, None): ("on", 0),
|
241 |
+
(behavior.OnEvent, 0): ("on", 0),
|
242 |
+
(behavior.MouseArea, 0): ("mousearea", 0),
|
243 |
+
(behavior.MouseArea, None): ("mousearea", 0),
|
244 |
+
(ui._add, None): ("add", 0),
|
245 |
+
(sld.sl2add, None): ("add", 0),
|
246 |
+
(ui._hotbar, "hotbar"): ("hotbar", 0),
|
247 |
+
(sld.sl2vbar, None): ("vbar", 0),
|
248 |
+
(sld.sl2bar, None): ("bar", 0),
|
249 |
+
(ui._label, "label"): ("label", 0),
|
250 |
+
(ui._textbutton, 0): ("textbutton", 0),
|
251 |
+
(ui._textbutton, "button"): ("textbutton", 0),
|
252 |
+
(ui._imagebutton, "image_button"): ("imagebutton", 0),
|
253 |
+
(im.image, "default"): ("image", 0),
|
254 |
+
(behavior.Input, "input"): ("input", 0),
|
255 |
+
(behavior.Timer, "default"): ("timer", 0),
|
256 |
+
(ui._key, None): ("key", 0),
|
257 |
+
(text.Text, "text"): ("text", 0),
|
258 |
+
(layout.Null, "default"): ("null", 0),
|
259 |
+
(dragdrop.Drag, None): ("drag", 1),
|
260 |
+
(dragdrop.Drag, "drag"): ("drag", 1),
|
261 |
+
(motion.Transform, "transform"): ("transform", 1),
|
262 |
+
(ui._hotspot, "hotspot"): ("hotspot", 1),
|
263 |
+
(sld.sl2viewport, "viewport"): ("viewport", 1),
|
264 |
+
(behavior.Button, "button"): ("button", 1),
|
265 |
+
(layout.Window, "frame"): ("frame", 1),
|
266 |
+
(layout.Window, "window"): ("window", 1),
|
267 |
+
(dragdrop.DragGroup, None): ("draggroup", 'many'),
|
268 |
+
(ui._imagemap, "imagemap"): ("imagemap", 'many'),
|
269 |
+
(layout.Side, "side"): ("side", 'many'),
|
270 |
+
(layout.Grid, "grid"): ("grid", 'many'),
|
271 |
+
(sld.sl2vpgrid, "vpgrid"): ("vpgrid", 'many'),
|
272 |
+
(layout.MultiBox, "fixed"): ("fixed", 'many'),
|
273 |
+
(layout.MultiBox, "vbox"): ("vbox", 'many'),
|
274 |
+
(layout.MultiBox, "hbox"): ("hbox", 'many')
|
275 |
+
}
|
276 |
+
|
277 |
+
def print_keywords_and_children(self, keywords, children, lineno, needs_colon=False, has_block=False, tag=None, variable=None, atl_transform=None):
|
278 |
+
# This function prints the keyword arguments and child nodes
|
279 |
+
# Used in a displayable screen statement
|
280 |
+
|
281 |
+
# If lineno is None, we're already inside of a block.
|
282 |
+
# Otherwise, we're on the line that could start a block.
|
283 |
+
wrote_colon = False
|
284 |
+
keywords_by_line = []
|
285 |
+
current_line = (lineno, [])
|
286 |
+
keywords_somewhere = [] # These can go anywhere inside the block that there's room.
|
287 |
+
if variable is not None:
|
288 |
+
if current_line[0] is None:
|
289 |
+
keywords_somewhere.extend(("as", variable))
|
290 |
+
else:
|
291 |
+
current_line[1].extend(("as", variable))
|
292 |
+
if tag is not None:
|
293 |
+
if current_line[0] is None or not self.tag_outside_block:
|
294 |
+
keywords_somewhere.extend(("tag", tag))
|
295 |
+
else:
|
296 |
+
current_line[1].extend(("tag", tag))
|
297 |
+
for key, value in keywords:
|
298 |
+
if value is None:
|
299 |
+
value = ""
|
300 |
+
if current_line[0] is None:
|
301 |
+
keywords_by_line.append(current_line)
|
302 |
+
current_line = (0, [])
|
303 |
+
elif current_line[0] is None or value.linenumber > current_line[0]:
|
304 |
+
keywords_by_line.append(current_line)
|
305 |
+
current_line = (value.linenumber, [])
|
306 |
+
current_line[1].extend((key, value))
|
307 |
+
if keywords_by_line:
|
308 |
+
# Easy case: we have at least one line inside the block that already has keywords.
|
309 |
+
# Just put the ones from keywords_somewhere with them.
|
310 |
+
current_line[1].extend(keywords_somewhere)
|
311 |
+
keywords_somewhere = []
|
312 |
+
keywords_by_line.append(current_line)
|
313 |
+
last_keyword_line = keywords_by_line[-1][0]
|
314 |
+
children_with_keywords = []
|
315 |
+
children_after_keywords = []
|
316 |
+
for i in children:
|
317 |
+
if i.location[1] > last_keyword_line:
|
318 |
+
children_after_keywords.append(i)
|
319 |
+
else:
|
320 |
+
children_with_keywords.append((i.location[1], i))
|
321 |
+
# the keywords in keywords_by_line[0] go on the line that starts the
|
322 |
+
# block, not in it
|
323 |
+
block_contents = sorted(keywords_by_line[1:] + children_with_keywords,
|
324 |
+
key=itemgetter(0))
|
325 |
+
if keywords_by_line[0][1]: # this never happens if lineno was None
|
326 |
+
self.write(" %s" % ' '.join(keywords_by_line[0][1]))
|
327 |
+
if keywords_somewhere: # this never happens if there's anything in block_contents
|
328 |
+
# Hard case: we need to put a keyword somewhere inside the block, but we have no idea which line to put it on.
|
329 |
+
if lineno is not None:
|
330 |
+
self.write(":")
|
331 |
+
wrote_colon = True
|
332 |
+
for index, child in enumerate(children_after_keywords):
|
333 |
+
if child.location[1] > self.linenumber + 1:
|
334 |
+
# We have at least one blank line before the next child. Put the keywords here.
|
335 |
+
with self.increase_indent():
|
336 |
+
self.indent()
|
337 |
+
self.write(' '.join(keywords_somewhere))
|
338 |
+
self.print_nodes(children_after_keywords[index:], 0 if has_block else 1)
|
339 |
+
break
|
340 |
+
with self.increase_indent():
|
341 |
+
# Even if we're in a "has" block, we need to indent this child since there will be a keyword line after it.
|
342 |
+
self.print_node(child)
|
343 |
+
else:
|
344 |
+
# No blank lines before any children, so just put the remaining keywords at the end.
|
345 |
+
with self.increase_indent():
|
346 |
+
self.indent()
|
347 |
+
self.write(' '.join(keywords_somewhere))
|
348 |
+
else:
|
349 |
+
if block_contents or (not has_block and children_after_keywords):
|
350 |
+
if lineno is not None:
|
351 |
+
self.write(":")
|
352 |
+
wrote_colon = True
|
353 |
+
with self.increase_indent():
|
354 |
+
for i in block_contents:
|
355 |
+
if isinstance(i[1], list):
|
356 |
+
self.advance_to_line(i[0])
|
357 |
+
self.indent()
|
358 |
+
self.write(' '.join(i[1]))
|
359 |
+
else:
|
360 |
+
self.print_node(i[1])
|
361 |
+
elif needs_colon:
|
362 |
+
self.write(":")
|
363 |
+
wrote_colon = True
|
364 |
+
self.print_nodes(children_after_keywords, 0 if has_block else 1)
|
365 |
+
if atl_transform is not None:
|
366 |
+
# "at transform:", possibly preceded by other keywords, and followed by an ATL block
|
367 |
+
# TODO this doesn't always go at the end. Use line numbers to figure out where it goes
|
368 |
+
if not wrote_colon and lineno is not None:
|
369 |
+
self.write(":")
|
370 |
+
wrote_colon = True
|
371 |
+
with self.increase_indent():
|
372 |
+
self.indent()
|
373 |
+
self.write("at transform:")
|
374 |
+
self.linenumber = self.print_atl_callback(self.linenumber, self.indent_level, atl_transform)
|
renpy/rpycdec/rpycdecdata/decompiler/sl2decompiler.pyo
ADDED
Binary file (14.2 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/testcasedecompiler.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2016 Jackmcbarn
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
from __future__ import unicode_literals
|
22 |
+
from util import DecompilerBase, split_logical_lines, Dispatcher, string_escape
|
23 |
+
from renpy.test import testast
|
24 |
+
|
25 |
+
# Main API
|
26 |
+
|
27 |
+
def pprint(out_file, ast, indent_level=0, linenumber=1,
|
28 |
+
skip_indent_until_write=False, printlock=None):
|
29 |
+
return TestcaseDecompiler(out_file, printlock=printlock).dump(
|
30 |
+
ast, indent_level, linenumber, skip_indent_until_write)
|
31 |
+
|
32 |
+
# Implementation
|
33 |
+
|
34 |
+
class TestcaseDecompiler(DecompilerBase):
|
35 |
+
"""
|
36 |
+
An object which handles the decompilation of renpy testcase statements
|
37 |
+
"""
|
38 |
+
|
39 |
+
# This dictionary is a mapping of Class: unbound_method, which is used to determine
|
40 |
+
# what method to call for which testast class
|
41 |
+
dispatch = Dispatcher()
|
42 |
+
|
43 |
+
def print_node(self, ast):
|
44 |
+
if hasattr(ast, 'linenumber'):
|
45 |
+
self.advance_to_line(ast.linenumber)
|
46 |
+
self.dispatch.get(type(ast), type(self).print_unknown)(self, ast)
|
47 |
+
|
48 |
+
@dispatch(testast.Python)
|
49 |
+
def print_python(self, ast):
|
50 |
+
self.indent()
|
51 |
+
code = ast.code.source
|
52 |
+
if code[0] == '\n':
|
53 |
+
self.write("python:")
|
54 |
+
with self.increase_indent():
|
55 |
+
self.write_lines(split_logical_lines(code[1:]))
|
56 |
+
else:
|
57 |
+
self.write("$ %s" % code)
|
58 |
+
|
59 |
+
@dispatch(testast.Assert)
|
60 |
+
def print_assert(self, ast):
|
61 |
+
self.indent()
|
62 |
+
self.write('assert %s' % ast.expr)
|
63 |
+
|
64 |
+
@dispatch(testast.Jump)
|
65 |
+
def print_jump(self, ast):
|
66 |
+
self.indent()
|
67 |
+
self.write('jump %s' % ast.target)
|
68 |
+
|
69 |
+
@dispatch(testast.Call)
|
70 |
+
def print_call(self, ast):
|
71 |
+
self.indent()
|
72 |
+
self.write('call %s' % ast.target)
|
73 |
+
|
74 |
+
@dispatch(testast.Action)
|
75 |
+
def print_action(self, ast):
|
76 |
+
self.indent()
|
77 |
+
self.write('run %s' % ast.expr)
|
78 |
+
|
79 |
+
@dispatch(testast.Pause)
|
80 |
+
def print_pause(self, ast):
|
81 |
+
self.indent()
|
82 |
+
self.write('pause %s' % ast.expr)
|
83 |
+
|
84 |
+
@dispatch(testast.Label)
|
85 |
+
def print_label(self, ast):
|
86 |
+
self.indent()
|
87 |
+
self.write('label %s' % ast.name)
|
88 |
+
|
89 |
+
@dispatch(testast.Type)
|
90 |
+
def print_type(self, ast):
|
91 |
+
self.indent()
|
92 |
+
if len(ast.keys[0]) == 1:
|
93 |
+
self.write('type "%s"' % string_escape(''.join(ast.keys)))
|
94 |
+
else:
|
95 |
+
self.write('type %s' % ast.keys[0])
|
96 |
+
if ast.pattern is not None:
|
97 |
+
self.write(' pattern "%s"' % string_escape(ast.pattern))
|
98 |
+
if hasattr(ast, 'position') and ast.position is not None:
|
99 |
+
self.write(' pos %s' % ast.position)
|
100 |
+
|
101 |
+
@dispatch(testast.Drag)
|
102 |
+
def print_drag(self, ast):
|
103 |
+
self.indent()
|
104 |
+
self.write('drag %s' % ast.points)
|
105 |
+
if ast.button != 1:
|
106 |
+
self.write(' button %d' % ast.button)
|
107 |
+
if ast.pattern is not None:
|
108 |
+
self.write(' pattern "%s"' % string_escape(ast.pattern))
|
109 |
+
if ast.steps != 10:
|
110 |
+
self.write(' steps %d' % ast.steps)
|
111 |
+
|
112 |
+
@dispatch(testast.Move)
|
113 |
+
def print_move(self, ast):
|
114 |
+
self.indent()
|
115 |
+
self.write('move %s' % ast.position)
|
116 |
+
if ast.pattern is not None:
|
117 |
+
self.write(' pattern "%s"' % string_escape(ast.pattern))
|
118 |
+
|
119 |
+
@dispatch(testast.Click)
|
120 |
+
def print_click(self, ast):
|
121 |
+
self.indent()
|
122 |
+
if ast.pattern is not None:
|
123 |
+
self.write('"%s"' % string_escape(ast.pattern))
|
124 |
+
else:
|
125 |
+
self.write('click')
|
126 |
+
if hasattr(ast, 'button') and ast.button != 1:
|
127 |
+
self.write(' button %d' % ast.button)
|
128 |
+
if hasattr(ast, 'position') and ast.position is not None:
|
129 |
+
self.write(' pos %s' % ast.position)
|
130 |
+
if hasattr(ast, 'always') and ast.always:
|
131 |
+
self.write(' always')
|
132 |
+
|
133 |
+
@dispatch(testast.Until)
|
134 |
+
def print_until(self, ast):
|
135 |
+
if hasattr(ast.right, 'linenumber'):
|
136 |
+
# We don't have our own line number, and it's not guaranteed that left has a line number.
|
137 |
+
# Go to right's line number now since we can't go to it after we print left.
|
138 |
+
self.advance_to_line(ast.right.linenumber)
|
139 |
+
self.print_node(ast.left)
|
140 |
+
self.write(' until ')
|
141 |
+
self.skip_indent_until_write = True
|
142 |
+
self.print_node(ast.right)
|
renpy/rpycdec/rpycdecdata/decompiler/testcasedecompiler.pyo
ADDED
Binary file (7.46 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/translate.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2016 Jackmcbarn
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
from util import say_get_code
|
22 |
+
import renpy
|
23 |
+
|
24 |
+
import hashlib
|
25 |
+
import re
|
26 |
+
from copy import copy
|
27 |
+
|
28 |
+
class Translator(object):
|
29 |
+
def __init__(self, language, saving_translations=False):
|
30 |
+
self.language = language
|
31 |
+
self.saving_translations = saving_translations
|
32 |
+
self.strings = {}
|
33 |
+
self.dialogue = {}
|
34 |
+
self.identifiers = set()
|
35 |
+
self.alternate = None
|
36 |
+
|
37 |
+
# Adapted from Ren'Py's Restructurer.unique_identifier
|
38 |
+
def unique_identifier(self, label, digest):
|
39 |
+
if label is None:
|
40 |
+
base = digest
|
41 |
+
else:
|
42 |
+
base = label.replace(".", "_") + "_" + digest
|
43 |
+
|
44 |
+
i = 0
|
45 |
+
suffix = ""
|
46 |
+
|
47 |
+
while True:
|
48 |
+
|
49 |
+
identifier = base + suffix
|
50 |
+
|
51 |
+
if identifier not in self.identifiers:
|
52 |
+
break
|
53 |
+
|
54 |
+
i += 1
|
55 |
+
suffix = "_{0}".format(i)
|
56 |
+
|
57 |
+
return identifier
|
58 |
+
|
59 |
+
# Adapted from Ren'Py's Restructurer.create_translate
|
60 |
+
def create_translate(self, block):
|
61 |
+
if self.saving_translations:
|
62 |
+
return [] # Doesn't matter, since we're throwing this away in this case
|
63 |
+
|
64 |
+
md5 = hashlib.md5()
|
65 |
+
|
66 |
+
for i in block:
|
67 |
+
if isinstance(i, renpy.ast.Say):
|
68 |
+
code = say_get_code(i)
|
69 |
+
elif isinstance(i, renpy.ast.UserStatement):
|
70 |
+
code = i.line
|
71 |
+
else:
|
72 |
+
raise Exception("Don't know how to get canonical code for a %s" % str(type(i)))
|
73 |
+
md5.update(code.encode("utf-8") + b"\r\n")
|
74 |
+
|
75 |
+
digest = md5.hexdigest()[:8]
|
76 |
+
|
77 |
+
identifier = self.unique_identifier(self.label, digest)
|
78 |
+
self.identifiers.add(identifier)
|
79 |
+
|
80 |
+
if self.alternate is not None:
|
81 |
+
alternate = self.unique_identifier(self.alternate, digest)
|
82 |
+
self.identifiers.add(alternate)
|
83 |
+
else:
|
84 |
+
alternate = None
|
85 |
+
|
86 |
+
translated_block = self.dialogue.get(identifier)
|
87 |
+
if (translated_block is None) and alternate:
|
88 |
+
translated_block = self.dialogue.get(alternate)
|
89 |
+
if translated_block is None:
|
90 |
+
return block
|
91 |
+
|
92 |
+
new_block = []
|
93 |
+
old_linenumber = block[0].linenumber
|
94 |
+
for ast in translated_block:
|
95 |
+
new_ast = copy(ast)
|
96 |
+
new_ast.linenumber = old_linenumber
|
97 |
+
new_block.append(new_ast)
|
98 |
+
return new_block
|
99 |
+
|
100 |
+
def walk(self, ast, f):
|
101 |
+
if isinstance(ast, (renpy.ast.Init, renpy.ast.Label, renpy.ast.While, renpy.ast.Translate, renpy.ast.TranslateBlock)):
|
102 |
+
f(ast.block)
|
103 |
+
elif isinstance(ast, renpy.ast.Menu):
|
104 |
+
for i in ast.items:
|
105 |
+
if i[2] is not None:
|
106 |
+
f(i[2])
|
107 |
+
elif isinstance(ast, renpy.ast.If):
|
108 |
+
for i in ast.entries:
|
109 |
+
f(i[1])
|
110 |
+
|
111 |
+
# Adapted from Ren'Py's Restructurer.callback
|
112 |
+
def translate_dialogue(self, children):
|
113 |
+
new_children = [ ]
|
114 |
+
group = [ ]
|
115 |
+
|
116 |
+
for i in children:
|
117 |
+
|
118 |
+
if isinstance(i, renpy.ast.Label):
|
119 |
+
if not (hasattr(i, 'hide') and i.hide):
|
120 |
+
if i.name.startswith("_"):
|
121 |
+
self.alternate = i.name
|
122 |
+
else:
|
123 |
+
self.label = i.name
|
124 |
+
self.alternate = None
|
125 |
+
|
126 |
+
if self.saving_translations and isinstance(i, renpy.ast.TranslateString) and i.language == self.language:
|
127 |
+
self.strings[i.old] = i.new
|
128 |
+
|
129 |
+
if not isinstance(i, renpy.ast.Translate):
|
130 |
+
self.walk(i, self.translate_dialogue)
|
131 |
+
elif self.saving_translations and i.language == self.language:
|
132 |
+
self.dialogue[i.identifier] = i.block
|
133 |
+
if hasattr(i, 'alternate') and i.alternate is not None:
|
134 |
+
self.dialogue[i.alternate] = i.block
|
135 |
+
|
136 |
+
if isinstance(i, renpy.ast.Say):
|
137 |
+
group.append(i)
|
138 |
+
tl = self.create_translate(group)
|
139 |
+
new_children.extend(tl)
|
140 |
+
group = [ ]
|
141 |
+
|
142 |
+
elif hasattr(i, 'translatable') and i.translatable:
|
143 |
+
group.append(i)
|
144 |
+
|
145 |
+
else:
|
146 |
+
if group:
|
147 |
+
tl = self.create_translate(group)
|
148 |
+
new_children.extend(tl)
|
149 |
+
group = [ ]
|
150 |
+
|
151 |
+
new_children.append(i)
|
152 |
+
|
153 |
+
if group:
|
154 |
+
nodes = self.create_translate(group)
|
155 |
+
new_children.extend(nodes)
|
156 |
+
group = [ ]
|
157 |
+
|
158 |
+
children[:] = new_children
|
renpy/rpycdec/rpycdecdata/decompiler/translate.pyo
ADDED
Binary file (4.72 kB). View file
|
|
renpy/rpycdec/rpycdecdata/decompiler/util.py
ADDED
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import unicode_literals
|
2 |
+
import sys
|
3 |
+
import re
|
4 |
+
from StringIO import StringIO
|
5 |
+
from contextlib import contextmanager
|
6 |
+
|
7 |
+
class DecompilerBase(object):
|
8 |
+
def __init__(self, out_file=None, indentation=' ', printlock=None):
|
9 |
+
self.out_file = out_file or sys.stdout
|
10 |
+
self.indentation = indentation
|
11 |
+
self.skip_indent_until_write = False
|
12 |
+
self.printlock = printlock
|
13 |
+
|
14 |
+
self.linenumber = 0
|
15 |
+
|
16 |
+
self.block_stack = []
|
17 |
+
self.index_stack = []
|
18 |
+
self.blank_line_queue = []
|
19 |
+
|
20 |
+
def dump(self, ast, indent_level=0, linenumber=1, skip_indent_until_write=False):
|
21 |
+
"""
|
22 |
+
Write the decompiled representation of `ast` into the opened file given in the constructor
|
23 |
+
"""
|
24 |
+
self.indent_level = indent_level
|
25 |
+
self.linenumber = linenumber
|
26 |
+
self.skip_indent_until_write = skip_indent_until_write
|
27 |
+
if not isinstance(ast, (tuple, list)):
|
28 |
+
ast = [ast]
|
29 |
+
self.print_nodes(ast)
|
30 |
+
return self.linenumber
|
31 |
+
|
32 |
+
@contextmanager
|
33 |
+
def increase_indent(self, amount=1):
|
34 |
+
self.indent_level += amount
|
35 |
+
try:
|
36 |
+
yield
|
37 |
+
finally:
|
38 |
+
self.indent_level -= amount
|
39 |
+
|
40 |
+
def write(self, string):
|
41 |
+
"""
|
42 |
+
Shorthand method for writing `string` to the file
|
43 |
+
"""
|
44 |
+
string = unicode(string)
|
45 |
+
self.linenumber += string.count('\n')
|
46 |
+
self.skip_indent_until_write = False
|
47 |
+
self.out_file.write(string)
|
48 |
+
|
49 |
+
def write_lines(self, lines):
|
50 |
+
"""
|
51 |
+
Write each line in lines to the file without writing whitespace-only lines
|
52 |
+
"""
|
53 |
+
for line in lines:
|
54 |
+
if line == '':
|
55 |
+
self.write('\n')
|
56 |
+
else:
|
57 |
+
self.indent()
|
58 |
+
self.write(line)
|
59 |
+
|
60 |
+
def save_state(self):
|
61 |
+
"""
|
62 |
+
Save our current state.
|
63 |
+
"""
|
64 |
+
state = (self.out_file, self.skip_indent_until_write, self.linenumber,
|
65 |
+
self.block_stack, self.index_stack, self.indent_level, self.blank_line_queue)
|
66 |
+
self.out_file = StringIO()
|
67 |
+
return state
|
68 |
+
|
69 |
+
def commit_state(self, state):
|
70 |
+
"""
|
71 |
+
Commit changes since a saved state.
|
72 |
+
"""
|
73 |
+
out_file = state[0]
|
74 |
+
out_file.write(self.out_file.getvalue())
|
75 |
+
self.out_file = out_file
|
76 |
+
|
77 |
+
def rollback_state(self, state):
|
78 |
+
"""
|
79 |
+
Roll back to a saved state.
|
80 |
+
"""
|
81 |
+
(self.out_file, self.skip_indent_until_write, self.linenumber,
|
82 |
+
self.block_stack, self.index_stack, self.indent_level, self.blank_line_queue) = state
|
83 |
+
|
84 |
+
def advance_to_line(self, linenumber):
|
85 |
+
# If there was anything that we wanted to do as soon as we found a blank line,
|
86 |
+
# try to do it now.
|
87 |
+
self.blank_line_queue = filter(lambda m: m(linenumber), self.blank_line_queue)
|
88 |
+
if self.linenumber < linenumber:
|
89 |
+
# Stop one line short, since the call to indent() will advance the last line.
|
90 |
+
# Note that if self.linenumber == linenumber - 1, this will write the empty string.
|
91 |
+
# This is to make sure that skip_indent_until_write is cleared in that case.
|
92 |
+
self.write("\n" * (linenumber - self.linenumber - 1))
|
93 |
+
|
94 |
+
def do_when_blank_line(self, m):
|
95 |
+
"""
|
96 |
+
Do something the next time we find a blank line. m should be a method that takes one
|
97 |
+
parameter (the line we're advancing to), and returns whether or not it needs to run
|
98 |
+
again.
|
99 |
+
"""
|
100 |
+
self.blank_line_queue.append(m)
|
101 |
+
|
102 |
+
def indent(self):
|
103 |
+
"""
|
104 |
+
Shorthand method for pushing a newline and indenting to the proper indent level
|
105 |
+
Setting skip_indent_until_write causes calls to this method to be ignored until something
|
106 |
+
calls the write method
|
107 |
+
"""
|
108 |
+
if not self.skip_indent_until_write:
|
109 |
+
self.write('\n' + self.indentation * self.indent_level)
|
110 |
+
|
111 |
+
def print_nodes(self, ast, extra_indent=0):
|
112 |
+
# This node is a list of nodes
|
113 |
+
# Print every node
|
114 |
+
with self.increase_indent(extra_indent):
|
115 |
+
self.block_stack.append(ast)
|
116 |
+
self.index_stack.append(0)
|
117 |
+
|
118 |
+
for i, node in enumerate(ast):
|
119 |
+
self.index_stack[-1] = i
|
120 |
+
self.print_node(node)
|
121 |
+
|
122 |
+
self.block_stack.pop()
|
123 |
+
self.index_stack.pop()
|
124 |
+
|
125 |
+
@property
|
126 |
+
def block(self):
|
127 |
+
return self.block_stack[-1]
|
128 |
+
|
129 |
+
@property
|
130 |
+
def index(self):
|
131 |
+
return self.index_stack[-1]
|
132 |
+
|
133 |
+
@property
|
134 |
+
def parent(self):
|
135 |
+
if len(self.block_stack) < 2:
|
136 |
+
return None
|
137 |
+
return self.block_stack[-2][self.index_stack[-2]]
|
138 |
+
|
139 |
+
def print_debug(self, message):
|
140 |
+
if self.printlock:
|
141 |
+
self.printlock.acquire()
|
142 |
+
try:
|
143 |
+
print(message)
|
144 |
+
finally:
|
145 |
+
if self.printlock:
|
146 |
+
self.printlock.release()
|
147 |
+
|
148 |
+
def write_failure(self, message):
|
149 |
+
self.print_debug(message)
|
150 |
+
self.indent()
|
151 |
+
self.write("pass # <<<COULD NOT DECOMPILE: %s>>>" % message)
|
152 |
+
|
153 |
+
def print_unknown(self, ast):
|
154 |
+
# If we encounter a placeholder note, print a warning and insert a placeholder
|
155 |
+
self.write_failure("Unknown AST node: %s" % str(type(ast)))
|
156 |
+
|
157 |
+
def print_node(self, ast):
|
158 |
+
raise NotImplementedError()
|
159 |
+
|
160 |
+
class First(object):
|
161 |
+
# An often used pattern is that on the first item
|
162 |
+
# of a loop something special has to be done. This class
|
163 |
+
# provides an easy object which on the first access
|
164 |
+
# will return True, but any subsequent accesses False
|
165 |
+
def __init__(self, yes_value=True, no_value=False):
|
166 |
+
self.yes_value = yes_value
|
167 |
+
self.no_value = no_value
|
168 |
+
self.first = True
|
169 |
+
|
170 |
+
def __call__(self):
|
171 |
+
if self.first:
|
172 |
+
self.first = False
|
173 |
+
return self.yes_value
|
174 |
+
else:
|
175 |
+
return self.no_value
|
176 |
+
|
177 |
+
def reconstruct_paraminfo(paraminfo):
|
178 |
+
if paraminfo is None:
|
179 |
+
return ""
|
180 |
+
|
181 |
+
rv = ["("]
|
182 |
+
|
183 |
+
sep = First("", ", ")
|
184 |
+
positional = [i for i in paraminfo.parameters if i[0] in paraminfo.positional]
|
185 |
+
nameonly = [i for i in paraminfo.parameters if i not in positional]
|
186 |
+
for parameter in positional:
|
187 |
+
rv.append(sep())
|
188 |
+
rv.append(parameter[0])
|
189 |
+
if parameter[1] is not None:
|
190 |
+
rv.append("=%s" % parameter[1])
|
191 |
+
if paraminfo.extrapos:
|
192 |
+
rv.append(sep())
|
193 |
+
rv.append("*%s" % paraminfo.extrapos)
|
194 |
+
if nameonly:
|
195 |
+
if not paraminfo.extrapos:
|
196 |
+
rv.append(sep())
|
197 |
+
rv.append("*")
|
198 |
+
for parameter in nameonly:
|
199 |
+
rv.append(sep())
|
200 |
+
rv.append(parameter[0])
|
201 |
+
if parameter[1] is not None:
|
202 |
+
rv.append("=%s" % parameter[1])
|
203 |
+
if paraminfo.extrakw:
|
204 |
+
rv.append(sep())
|
205 |
+
rv.append("**%s" % paraminfo.extrakw)
|
206 |
+
|
207 |
+
rv.append(")")
|
208 |
+
|
209 |
+
return "".join(rv)
|
210 |
+
|
211 |
+
def reconstruct_arginfo(arginfo):
|
212 |
+
if arginfo is None:
|
213 |
+
return ""
|
214 |
+
|
215 |
+
rv = ["("]
|
216 |
+
sep = First("", ", ")
|
217 |
+
for (name, val) in arginfo.arguments:
|
218 |
+
rv.append(sep())
|
219 |
+
if name is not None:
|
220 |
+
rv.append("%s=" % name)
|
221 |
+
rv.append(val)
|
222 |
+
if arginfo.extrapos:
|
223 |
+
rv.append(sep())
|
224 |
+
rv.append("*%s" % arginfo.extrapos)
|
225 |
+
if arginfo.extrakw:
|
226 |
+
rv.append(sep())
|
227 |
+
rv.append("**%s" % arginfo.extrakw)
|
228 |
+
rv.append(")")
|
229 |
+
|
230 |
+
return "".join(rv)
|
231 |
+
|
232 |
+
def string_escape(s): # TODO see if this needs to work like encode_say_string elsewhere
|
233 |
+
s = s.replace('\\', '\\\\')
|
234 |
+
s = s.replace('"', '\\"')
|
235 |
+
s = s.replace('\n', '\\n')
|
236 |
+
s = s.replace('\t', '\\t')
|
237 |
+
return s
|
238 |
+
|
239 |
+
# keywords used by ren'py's parser
|
240 |
+
KEYWORDS = set(['$', 'as', 'at', 'behind', 'call', 'expression', 'hide',
|
241 |
+
'if', 'in', 'image', 'init', 'jump', 'menu', 'onlayer',
|
242 |
+
'python', 'return', 'scene', 'set', 'show', 'with',
|
243 |
+
'while', 'zorder', 'transform'])
|
244 |
+
|
245 |
+
word_regexp = '[a-zA-Z_\u00a0-\ufffd][0-9a-zA-Z_\u00a0-\ufffd]*'
|
246 |
+
|
247 |
+
def simple_expression_guard(s):
|
248 |
+
# Some things we deal with are supposed to be parsed by
|
249 |
+
# ren'py's Lexer.simple_expression but actually cannot
|
250 |
+
# be parsed by it. figure out if this is the case
|
251 |
+
# a slightly more naive approach woudl be to check
|
252 |
+
# for spaces in it and surround it with () if necessary
|
253 |
+
# but we're not naive
|
254 |
+
s = s.strip()
|
255 |
+
|
256 |
+
if Lexer(s).simple_expression():
|
257 |
+
return s
|
258 |
+
else:
|
259 |
+
return "(%s)" % s
|
260 |
+
|
261 |
+
def split_logical_lines(s):
|
262 |
+
return Lexer(s).split_logical_lines()
|
263 |
+
|
264 |
+
class Lexer(object):
|
265 |
+
# special lexer for simple_expressions the ren'py way
|
266 |
+
# false negatives aren't dangerous. but false positives are
|
267 |
+
def __init__(self, string):
|
268 |
+
self.pos = 0
|
269 |
+
self.length = len(string)
|
270 |
+
self.string = string
|
271 |
+
|
272 |
+
def re(self, regexp):
|
273 |
+
# see if regexp matches at self.string[self.pos].
|
274 |
+
# if it does, increment self.pos
|
275 |
+
if self.length == self.pos:
|
276 |
+
return None
|
277 |
+
|
278 |
+
match = re.compile(regexp, re.DOTALL).match(self.string, self.pos)
|
279 |
+
if not match:
|
280 |
+
return None
|
281 |
+
|
282 |
+
self.pos = match.end()
|
283 |
+
return match.group(0)
|
284 |
+
|
285 |
+
def eol(self):
|
286 |
+
# eat the next whitespace and check for the end of this simple_expression
|
287 |
+
self.re(r"(\s+|\\\n)+")
|
288 |
+
return self.pos >= self.length
|
289 |
+
|
290 |
+
def match(self, regexp):
|
291 |
+
# strip whitespace and match regexp
|
292 |
+
self.re(r"(\s+|\\\n)+")
|
293 |
+
return self.re(regexp)
|
294 |
+
|
295 |
+
def python_string(self, clear_whitespace=True):
|
296 |
+
# parse strings the ren'py way (don't parse docstrings, no b/r in front allowed)
|
297 |
+
# edit: now parses docstrings correctly. There was a degenerate case where '''string'string''' would
|
298 |
+
# result in issues
|
299 |
+
if clear_whitespace:
|
300 |
+
return self.match(r"""(u?(?P<a>"(?:"")?|'(?:'')?).*?(?<=[^\\])(?:\\\\)*(?P=a))""")
|
301 |
+
else:
|
302 |
+
return self.re(r"""(u?(?P<a>"(?:"")?|'(?:'')?).*?(?<=[^\\])(?:\\\\)*(?P=a))""")
|
303 |
+
|
304 |
+
|
305 |
+
def container(self):
|
306 |
+
# parses something enclosed by [], () or {}'s. keyword something
|
307 |
+
containers = {"{": "}", "[": "]", "(": ")"}
|
308 |
+
if self.eol():
|
309 |
+
return None
|
310 |
+
|
311 |
+
c = self.string[self.pos]
|
312 |
+
if c not in containers:
|
313 |
+
return None
|
314 |
+
self.pos += 1
|
315 |
+
|
316 |
+
c = containers[c]
|
317 |
+
|
318 |
+
while not self.eol():
|
319 |
+
if c == self.string[self.pos]:
|
320 |
+
self.pos += 1
|
321 |
+
return True
|
322 |
+
|
323 |
+
if self.python_string() or self.container():
|
324 |
+
continue
|
325 |
+
|
326 |
+
self.pos += 1
|
327 |
+
|
328 |
+
return None
|
329 |
+
|
330 |
+
def number(self):
|
331 |
+
# parses a number, float or int (but not forced long)
|
332 |
+
return self.match(r'(\+|\-)?(\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?')
|
333 |
+
|
334 |
+
def word(self):
|
335 |
+
# parses a word
|
336 |
+
return self.match(word_regexp)
|
337 |
+
|
338 |
+
def name(self):
|
339 |
+
# parses a word unless it's in KEYWORDS.
|
340 |
+
pos = self.pos
|
341 |
+
word = self.word()
|
342 |
+
|
343 |
+
if word in KEYWORDS:
|
344 |
+
self.pos = pos
|
345 |
+
return None
|
346 |
+
|
347 |
+
return word
|
348 |
+
|
349 |
+
def simple_expression(self):
|
350 |
+
# test if the start string was a simple expression
|
351 |
+
start = self.pos
|
352 |
+
|
353 |
+
# check if there's anything in here acctually
|
354 |
+
if self.eol():
|
355 |
+
return False
|
356 |
+
|
357 |
+
# parse anything which can be called or have attributes requested
|
358 |
+
if not(self.python_string() or
|
359 |
+
self.number() or
|
360 |
+
self.container() or
|
361 |
+
self.name()):
|
362 |
+
return False
|
363 |
+
|
364 |
+
while not self.eol():
|
365 |
+
|
366 |
+
# if the previous was followed by a dot, there should be a word after it
|
367 |
+
if self.match(r'\.'):
|
368 |
+
if not self.name():
|
369 |
+
# ren'py errors here. I just stop caring
|
370 |
+
return False
|
371 |
+
|
372 |
+
continue
|
373 |
+
|
374 |
+
# parses slices, function calls, and postfix {}
|
375 |
+
if self.container():
|
376 |
+
continue
|
377 |
+
|
378 |
+
break
|
379 |
+
|
380 |
+
# are we at the end of the simple expression?
|
381 |
+
return self.eol()
|
382 |
+
|
383 |
+
def split_logical_lines(self):
|
384 |
+
# split a sequence in logical lines
|
385 |
+
# this behaves similarly to .splitlines() which will ignore
|
386 |
+
# a trailing \n
|
387 |
+
lines = []
|
388 |
+
|
389 |
+
contained = 0
|
390 |
+
|
391 |
+
startpos = self.pos
|
392 |
+
|
393 |
+
while self.pos < self.length:
|
394 |
+
c = self.string[self.pos]
|
395 |
+
|
396 |
+
if c == '\n' and not contained and (not self.pos or self.string[self.pos - 1] != '\\'):
|
397 |
+
lines.append(self.string[startpos:self.pos])
|
398 |
+
# the '\n' is not included in the emitted line
|
399 |
+
self.pos += 1
|
400 |
+
startpos = self.pos
|
401 |
+
continue
|
402 |
+
|
403 |
+
if c in ('(', '[', '{'):
|
404 |
+
contained += 1
|
405 |
+
self.pos += 1
|
406 |
+
continue
|
407 |
+
|
408 |
+
if c in (')', ']', '}') and contained:
|
409 |
+
contained -= 1
|
410 |
+
self.pos += 1
|
411 |
+
continue
|
412 |
+
|
413 |
+
if c == '#':
|
414 |
+
self.re("[^\n]*")
|
415 |
+
continue
|
416 |
+
|
417 |
+
if self.python_string(False):
|
418 |
+
continue
|
419 |
+
|
420 |
+
self.re(r'\w+| +|.') # consume a word, whitespace or one symbol
|
421 |
+
|
422 |
+
if self.pos != startpos:
|
423 |
+
lines.append(self.string[startpos:])
|
424 |
+
return lines
|
425 |
+
|
426 |
+
# Versions of Ren'Py prior to 6.17 put trailing whitespace on the end of
|
427 |
+
# simple_expressions. This class attempts to preserve the amount of
|
428 |
+
# whitespace if possible.
|
429 |
+
class WordConcatenator(object):
|
430 |
+
def __init__(self, needs_space, reorderable=False):
|
431 |
+
self.words = []
|
432 |
+
self.needs_space = needs_space
|
433 |
+
self.reorderable = reorderable
|
434 |
+
|
435 |
+
def append(self, *args):
|
436 |
+
self.words.extend(filter(None, args))
|
437 |
+
|
438 |
+
def join(self):
|
439 |
+
if not self.words:
|
440 |
+
return ''
|
441 |
+
if self.reorderable and self.words[-1][-1] == ' ':
|
442 |
+
for i in xrange(len(self.words) - 1, -1, -1):
|
443 |
+
if self.words[i][-1] != ' ':
|
444 |
+
self.words.append(self.words.pop(i))
|
445 |
+
break
|
446 |
+
last_word = self.words[-1]
|
447 |
+
self.words = map(lambda x: x[:-1] if x[-1] == ' ' else x, self.words[:-1])
|
448 |
+
self.words.append(last_word)
|
449 |
+
rv = (' ' if self.needs_space else '') + ' '.join(self.words)
|
450 |
+
self.needs_space = rv[-1] != ' '
|
451 |
+
return rv
|
452 |
+
|
453 |
+
# Dict subclass for aesthetic dispatching. use @Dispatcher(data) to dispatch
|
454 |
+
class Dispatcher(dict):
|
455 |
+
def __call__(self, name):
|
456 |
+
def closure(func):
|
457 |
+
self[name] = func
|
458 |
+
return func
|
459 |
+
return closure
|
460 |
+
|
461 |
+
# ren'py string handling
|
462 |
+
def encode_say_string(s):
|
463 |
+
"""
|
464 |
+
Encodes a string in the format used by Ren'Py say statements.
|
465 |
+
"""
|
466 |
+
|
467 |
+
s = s.replace("\\", "\\\\")
|
468 |
+
s = s.replace("\n", "\\n")
|
469 |
+
s = s.replace("\"", "\\\"")
|
470 |
+
s = re.sub(r'(?<= ) ', '\\ ', s)
|
471 |
+
|
472 |
+
return "\"" + s + "\""
|
473 |
+
|
474 |
+
# Adapted from Ren'Py's Say.get_code
|
475 |
+
def say_get_code(ast, inmenu=False):
|
476 |
+
rv = [ ]
|
477 |
+
|
478 |
+
if ast.who:
|
479 |
+
rv.append(ast.who)
|
480 |
+
|
481 |
+
if hasattr(ast, 'attributes') and ast.attributes is not None:
|
482 |
+
rv.extend(ast.attributes)
|
483 |
+
|
484 |
+
if hasattr(ast, 'temporary_attributes') and ast.temporary_attributes is not None:
|
485 |
+
rv.append("@")
|
486 |
+
rv.extend(ast.temporary_attributes)
|
487 |
+
|
488 |
+
# no dialogue_filter applies to us
|
489 |
+
|
490 |
+
rv.append(encode_say_string(ast.what))
|
491 |
+
|
492 |
+
if not ast.interact and not inmenu:
|
493 |
+
rv.append("nointeract")
|
494 |
+
|
495 |
+
if ast.with_:
|
496 |
+
rv.append("with")
|
497 |
+
rv.append(ast.with_)
|
498 |
+
|
499 |
+
if hasattr(ast, 'arguments') and ast.arguments is not None:
|
500 |
+
rv.append(reconstruct_arginfo(ast.arguments))
|
501 |
+
|
502 |
+
return " ".join(rv)
|
renpy/rpycdec/rpycdecdata/decompiler/util.pyo
ADDED
Binary file (21.8 kB). View file
|
|
renpy/rpycdec/rpycdecdata/deobfuscate.py
ADDED
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2021 CensoredUsername
|
2 |
+
#
|
3 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
4 |
+
# of this software and associated documentation files (the "Software"), to deal
|
5 |
+
# in the Software without restriction, including without limitation the rights
|
6 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7 |
+
# copies of the Software, and to permit persons to whom the Software is
|
8 |
+
# furnished to do so, subject to the following conditions:
|
9 |
+
#
|
10 |
+
# The above copyright notice and this permission notice shall be included in
|
11 |
+
# all copies or substantial portions of the Software.
|
12 |
+
#
|
13 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19 |
+
# SOFTWARE.
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
# This file contains documented strategies used against known obfuscation techniques and some machinery
|
24 |
+
# to test them against.
|
25 |
+
|
26 |
+
# Architecture is pretty simple. There's at least two steps in unpacking the rpyc format.
|
27 |
+
# RPYC2 is an archive format that can contain multiple streams (referred to as slots)
|
28 |
+
# The first step is extracting the slot from it, which is done by one of the extractors.
|
29 |
+
# These all give a blob that's either still zlib-compressed or just the raw slot
|
30 |
+
# (some methods rely on the zlib compression to figure out the slot length)
|
31 |
+
# Then, there's 0 or more steps of decrypting the data in that slot. This ends up often
|
32 |
+
# being layers of base64, string-escape, hex-encoding, zlib-compression, etc.
|
33 |
+
# We handle this by just trying these by checking if they fit.
|
34 |
+
|
35 |
+
import os
|
36 |
+
import zlib
|
37 |
+
import struct
|
38 |
+
import base64
|
39 |
+
from collections import Counter
|
40 |
+
from decompiler import magic
|
41 |
+
import unrpyc
|
42 |
+
|
43 |
+
|
44 |
+
# Extractors are simple functions of (fobj, slotno) -> bytes
|
45 |
+
# They raise ValueError if they fail
|
46 |
+
EXTRACTORS = []
|
47 |
+
def extractor(f):
|
48 |
+
EXTRACTORS.append(f)
|
49 |
+
return f
|
50 |
+
|
51 |
+
# Decryptors are simple functions of (bytes, Counter) ->bytes
|
52 |
+
# They return None if they fail. If they return their input they're also considered to have failed.
|
53 |
+
DECRYPTORS = []
|
54 |
+
def decryptor(f):
|
55 |
+
DECRYPTORS.append(f)
|
56 |
+
return f
|
57 |
+
|
58 |
+
|
59 |
+
# Add game-specific custom extraction / decryption logic here
|
60 |
+
|
61 |
+
# End of custom extraction/decryption logic
|
62 |
+
|
63 |
+
|
64 |
+
@extractor
|
65 |
+
def extract_slot_rpyc(f, slot):
|
66 |
+
"""
|
67 |
+
Slot extractor for a file that's in the actual rpyc format
|
68 |
+
"""
|
69 |
+
f.seek(0)
|
70 |
+
data = f.read()
|
71 |
+
if data[:10] != "RENPY RPYC":
|
72 |
+
raise ValueError("Incorrect Header")
|
73 |
+
|
74 |
+
position = 10
|
75 |
+
slots = {}
|
76 |
+
|
77 |
+
while position + 12 <= len(data):
|
78 |
+
slotid, start, length = struct.unpack("<III", data[position : position + 12])
|
79 |
+
if (slotid, start, length) == (0, 0, 0):
|
80 |
+
break
|
81 |
+
|
82 |
+
if start + length >= len(data):
|
83 |
+
raise ValueError("Broken slot entry")
|
84 |
+
|
85 |
+
slots[slotid] = (start, length)
|
86 |
+
position += 12
|
87 |
+
else:
|
88 |
+
raise ValueError("Broken slot header structure")
|
89 |
+
|
90 |
+
if slot not in slots:
|
91 |
+
raise ValueError("Unknown slot id")
|
92 |
+
|
93 |
+
start, length = slots[slot]
|
94 |
+
return data[start : start + length]
|
95 |
+
|
96 |
+
@extractor
|
97 |
+
def extract_slot_legacy(f, slot):
|
98 |
+
"""
|
99 |
+
Slot extractor for the legacy format
|
100 |
+
"""
|
101 |
+
if slot != 1:
|
102 |
+
raise ValueError("Legacy format only supports 1 slot")
|
103 |
+
|
104 |
+
f.seek(0)
|
105 |
+
data = f.read()
|
106 |
+
|
107 |
+
try:
|
108 |
+
data = zlib.decompress(data)
|
109 |
+
except zlib.error:
|
110 |
+
raise ValueError("Legacy format did not contain a zlib blob")
|
111 |
+
|
112 |
+
return data
|
113 |
+
|
114 |
+
@extractor
|
115 |
+
def extract_slot_headerscan(f, slot):
|
116 |
+
"""
|
117 |
+
Slot extractor for things that changed the magic and so moved the header around.
|
118 |
+
"""
|
119 |
+
f.seek(0)
|
120 |
+
data = f.read()
|
121 |
+
|
122 |
+
position = 0
|
123 |
+
while position + 36 < len(data):
|
124 |
+
a,b,c,d,e,f,g,h,i = struct.unpack("<IIIIIIIII", data[position : position + 36])
|
125 |
+
if a == 1 and d == 2 and g == 0 and b + c == e:
|
126 |
+
break;
|
127 |
+
position += 1
|
128 |
+
|
129 |
+
else:
|
130 |
+
raise ValueError("Couldn't find a header")
|
131 |
+
|
132 |
+
slots = {}
|
133 |
+
while position + 12 <= len(data):
|
134 |
+
slotid, start, length = struct.unpack("<III", data[position : position + 12])
|
135 |
+
if (slotid, start, length) == (0, 0, 0):
|
136 |
+
break
|
137 |
+
|
138 |
+
if start + length >= len(data):
|
139 |
+
raise ValueError("Broken slot entry")
|
140 |
+
|
141 |
+
slots[slotid] = (start, length)
|
142 |
+
position += 12
|
143 |
+
else:
|
144 |
+
raise ValueError("Broken slot header structure")
|
145 |
+
|
146 |
+
if slot not in slots:
|
147 |
+
raise ValueError("Unknown slot id")
|
148 |
+
|
149 |
+
start, length = slots[slot]
|
150 |
+
return data[start : start + length]
|
151 |
+
|
152 |
+
@extractor
|
153 |
+
def extract_slot_zlibscan(f, slot):
|
154 |
+
"""
|
155 |
+
Slot extractor for things that fucked with the header structure to the point where it's easier
|
156 |
+
to just not bother with it and instead we just look for valid zlib chunks directly.
|
157 |
+
"""
|
158 |
+
f.seek(0)
|
159 |
+
data = f.read()
|
160 |
+
|
161 |
+
start_positions = []
|
162 |
+
|
163 |
+
for i in range(len(data) - 1):
|
164 |
+
if data[i] != "\x78":
|
165 |
+
continue
|
166 |
+
|
167 |
+
if (ord(data[i]) * 256 + ord(data[i + 1])) % 31 != 0:
|
168 |
+
continue
|
169 |
+
|
170 |
+
start_positions.append(i)
|
171 |
+
|
172 |
+
chunks = []
|
173 |
+
for position in start_positions:
|
174 |
+
try:
|
175 |
+
chunk = zlib.decompress(data[position:])
|
176 |
+
except zlib.error:
|
177 |
+
continue
|
178 |
+
chunks.append(chunk)
|
179 |
+
|
180 |
+
if slot > len(chunks):
|
181 |
+
raise ValueError("Zlibscan did not find enough chunks")
|
182 |
+
|
183 |
+
return chunks[slot - 1]
|
184 |
+
|
185 |
+
|
186 |
+
@decryptor
|
187 |
+
def decrypt_zlib(data, count):
|
188 |
+
try:
|
189 |
+
return zlib.decompress(data)
|
190 |
+
except zlib.error:
|
191 |
+
return None
|
192 |
+
|
193 |
+
@decryptor
|
194 |
+
def decrypt_hex(data, count):
|
195 |
+
if not all(i in "abcdefABCDEF0123456789" for i in count.keys()):
|
196 |
+
return None
|
197 |
+
try:
|
198 |
+
return data.decode("hex")
|
199 |
+
except Exception:
|
200 |
+
return None
|
201 |
+
|
202 |
+
@decryptor
|
203 |
+
def decrypt_base64(data, count):
|
204 |
+
if not all(i in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=\n" for i in count.keys()):
|
205 |
+
return None
|
206 |
+
try:
|
207 |
+
return base64.b64decode(data)
|
208 |
+
except Exception:
|
209 |
+
return None
|
210 |
+
|
211 |
+
@decryptor
|
212 |
+
def decrypt_string_escape(data, count):
|
213 |
+
if not all(ord(i) >= 0x20 and ord(i) < 0x80 for i in count.keys()):
|
214 |
+
return None
|
215 |
+
try:
|
216 |
+
newdata = data.decode("string-escape")
|
217 |
+
except Exception:
|
218 |
+
return None
|
219 |
+
if newdata == data:
|
220 |
+
return None
|
221 |
+
return newdata
|
222 |
+
|
223 |
+
|
224 |
+
def assert_is_normal_rpyc(f):
|
225 |
+
"""
|
226 |
+
Analyze the structure of a single rpyc file object for correctness.
|
227 |
+
Does not actually say anything about the _contents_ of that section, just that we were able
|
228 |
+
to slice it out of there.
|
229 |
+
|
230 |
+
If succesful, returns the uncompressed contents of the first storage slot.
|
231 |
+
"""
|
232 |
+
|
233 |
+
diagnosis = []
|
234 |
+
|
235 |
+
f.seek(0)
|
236 |
+
header = f.read(1024)
|
237 |
+
f.seek(0)
|
238 |
+
|
239 |
+
if header_data[:10] != "RENPY RPC2":
|
240 |
+
# either legacy, or someone messed with the header
|
241 |
+
|
242 |
+
# assuming legacy, see if this thing is a valid zlib blob
|
243 |
+
raw_data = f.read()
|
244 |
+
f.seek(0)
|
245 |
+
|
246 |
+
try:
|
247 |
+
uncompressed = zlib.decompress(raw_data)
|
248 |
+
except zlib.error:
|
249 |
+
raise ValueError("Did not find RENPY RPC2 header, but interpretation as legacy file failed")
|
250 |
+
|
251 |
+
return uncompressed
|
252 |
+
|
253 |
+
|
254 |
+
else:
|
255 |
+
if len(header) < 46:
|
256 |
+
# 10 bytes header + 4 * 9 bytes content table
|
257 |
+
return ValueError("File too short")
|
258 |
+
|
259 |
+
a,b,c,d,e,f,g,h,i = struct.unpack("<IIIIIIIII", raw_contents[header + 10 : header + 46])
|
260 |
+
|
261 |
+
# does the header format match default ren'py generated files?
|
262 |
+
if not (a == 1 and b == 46 and d == 2 and (g, h, i) == (0, 0, 0) and b + c == e):
|
263 |
+
return ValueError("Header data is abnormal, did the format gain extra fields?")
|
264 |
+
|
265 |
+
f.seek(b)
|
266 |
+
raw_data = f.read(c)
|
267 |
+
f.seek(0)
|
268 |
+
if len(raw_data) != c:
|
269 |
+
return ValueError("Header data is incompatible with file length")
|
270 |
+
|
271 |
+
try:
|
272 |
+
uncompressed = zlib.decompress(raw_data)
|
273 |
+
except zlib.error:
|
274 |
+
return ValueError("Slot 1 did not contain a zlib blob")
|
275 |
+
|
276 |
+
if not uncompressed.endswith("."):
|
277 |
+
return ValueError("Slot 1 did not contain a simple pickle")
|
278 |
+
|
279 |
+
return uncompressed
|
280 |
+
|
281 |
+
|
282 |
+
def read_ast(f):
|
283 |
+
diagnosis = ["Attempting to deobfuscate file:"]
|
284 |
+
|
285 |
+
raw_datas = set()
|
286 |
+
|
287 |
+
for extractor in EXTRACTORS:
|
288 |
+
try:
|
289 |
+
data = extractor(f, 1)
|
290 |
+
except ValueError as e:
|
291 |
+
diagnosis.append("strategy %s failed: %s" % (extractor.__name__, e.message))
|
292 |
+
else:
|
293 |
+
diagnosis.append("strategy %s success" % extractor.__name__)
|
294 |
+
raw_datas.add(data)
|
295 |
+
|
296 |
+
if not raw_datas:
|
297 |
+
diagnosis.append("All strategies failed. Unable to extract data")
|
298 |
+
raise ValueError("\n".join(diagnosis))
|
299 |
+
|
300 |
+
if len(raw_datas) != 1:
|
301 |
+
diagnosis.append("Strategies produced different results. Trying all options")
|
302 |
+
|
303 |
+
data = None
|
304 |
+
for raw_data in raw_datas:
|
305 |
+
try:
|
306 |
+
data, stmts, d = try_decrypt_section(raw_data)
|
307 |
+
except ValueError as e:
|
308 |
+
diagnosis.append(e.message)
|
309 |
+
else:
|
310 |
+
diagnosis.extend(d)
|
311 |
+
with unrpyc.printlock:
|
312 |
+
print("\n".join(diagnosis))
|
313 |
+
return stmts
|
314 |
+
|
315 |
+
diagnosis.append("All strategies failed. Unable to deobfuscate data")
|
316 |
+
raise ValueError("\n".join(diagnosis))
|
317 |
+
|
318 |
+
|
319 |
+
def try_decrypt_section(raw_data):
|
320 |
+
diagnosis = []
|
321 |
+
|
322 |
+
layers = 0
|
323 |
+
while layers < 10:
|
324 |
+
# can we load it yet?
|
325 |
+
try:
|
326 |
+
data, stmts = magic.safe_loads(raw_data, unrpyc.class_factory, {"_ast", "collections"})
|
327 |
+
except Exception:
|
328 |
+
pass
|
329 |
+
else:
|
330 |
+
return data, stmts, diagnosis
|
331 |
+
|
332 |
+
layers += 1
|
333 |
+
count = Counter(raw_data)
|
334 |
+
|
335 |
+
for decryptor in DECRYPTORS:
|
336 |
+
newdata = decryptor(raw_data, count)
|
337 |
+
if newdata is None:
|
338 |
+
continue
|
339 |
+
else:
|
340 |
+
raw_data = newdata
|
341 |
+
diagnosis.append("performed a round of %s" % decryptor.__name__)
|
342 |
+
break
|
343 |
+
else:
|
344 |
+
break
|
345 |
+
|
346 |
+
diagnosis.append("Did not know how to decrypt data.")
|
347 |
+
raise ValueError("\n".join(diagnosis))
|
renpy/rpycdec/rpycdecdata/deobfuscate.pyo
ADDED
Binary file (10.7 kB). View file
|
|
renpy/rpycdec/rpycdecdata/unrpyc.py
ADDED
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python2
|
2 |
+
|
3 |
+
# Copyright (c) 2012 Yuri K. Schlesner
|
4 |
+
#
|
5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
7 |
+
# in the Software without restriction, including without limitation the rights
|
8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
10 |
+
# furnished to do so, subject to the following conditions:
|
11 |
+
#
|
12 |
+
# The above copyright notice and this permission notice shall be included in
|
13 |
+
# all copies or substantial portions of the Software.
|
14 |
+
#
|
15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
# SOFTWARE.
|
22 |
+
|
23 |
+
import argparse
|
24 |
+
import os
|
25 |
+
from os import path, walk
|
26 |
+
import codecs
|
27 |
+
import glob
|
28 |
+
import itertools
|
29 |
+
import traceback
|
30 |
+
import struct
|
31 |
+
from operator import itemgetter
|
32 |
+
import sys
|
33 |
+
sys.path.append(os.path.join(sys.path[0], '../'))
|
34 |
+
import decompiler
|
35 |
+
from decompiler import magic, astdump, translate
|
36 |
+
|
37 |
+
# special definitions for special classes
|
38 |
+
|
39 |
+
class PyExpr(magic.FakeStrict, unicode):
|
40 |
+
__module__ = "renpy.ast"
|
41 |
+
def __new__(cls, s, filename, linenumber):
|
42 |
+
self = unicode.__new__(cls, s)
|
43 |
+
self.filename = filename
|
44 |
+
self.linenumber = linenumber
|
45 |
+
return self
|
46 |
+
|
47 |
+
def __getnewargs__(self):
|
48 |
+
return unicode(self), self.filename, self.linenumber
|
49 |
+
|
50 |
+
class PyCode(magic.FakeStrict):
|
51 |
+
__module__ = "renpy.ast"
|
52 |
+
def __setstate__(self, state):
|
53 |
+
(_, self.source, self.location, self.mode) = state
|
54 |
+
self.bytecode = None
|
55 |
+
|
56 |
+
class RevertableList(magic.FakeStrict, list):
|
57 |
+
__module__ = "renpy.python"
|
58 |
+
def __new__(cls):
|
59 |
+
return list.__new__(cls)
|
60 |
+
|
61 |
+
class RevertableDict(magic.FakeStrict, dict):
|
62 |
+
__module__ = "renpy.python"
|
63 |
+
def __new__(cls):
|
64 |
+
return dict.__new__(cls)
|
65 |
+
|
66 |
+
class RevertableSet(magic.FakeStrict, set):
|
67 |
+
__module__ = "renpy.python"
|
68 |
+
def __new__(cls):
|
69 |
+
return set.__new__(cls)
|
70 |
+
|
71 |
+
def __setstate__(self, state):
|
72 |
+
if isinstance(state, tuple):
|
73 |
+
self.update(state[0].keys())
|
74 |
+
else:
|
75 |
+
self.update(state)
|
76 |
+
|
77 |
+
class Sentinel(magic.FakeStrict, object):
|
78 |
+
__module__ = "renpy.object"
|
79 |
+
def __new__(cls, name):
|
80 |
+
obj = object.__new__(cls)
|
81 |
+
obj.name = name
|
82 |
+
return obj
|
83 |
+
|
84 |
+
class_factory = magic.FakeClassFactory((PyExpr, PyCode, RevertableList, RevertableDict, RevertableSet, Sentinel), magic.FakeStrict)
|
85 |
+
|
86 |
+
# needs class_factory
|
87 |
+
import deobfuscate
|
88 |
+
|
89 |
+
# API
|
90 |
+
|
91 |
+
def read_ast_from_file(in_file):
|
92 |
+
# .rpyc files are just zlib compressed pickles of a tuple of some data and the actual AST of the file
|
93 |
+
raw_contents = in_file.read()
|
94 |
+
if raw_contents.startswith("RENPY RPC2"):
|
95 |
+
# parse the archive structure
|
96 |
+
position = 10
|
97 |
+
chunks = {}
|
98 |
+
while True:
|
99 |
+
slot, start, length = struct.unpack("III", raw_contents[position: position + 12])
|
100 |
+
if slot == 0:
|
101 |
+
break
|
102 |
+
position += 12
|
103 |
+
|
104 |
+
chunks[slot] = raw_contents[start: start + length]
|
105 |
+
|
106 |
+
raw_contents = chunks[1]
|
107 |
+
|
108 |
+
raw_contents = raw_contents.decode('zlib')
|
109 |
+
data, stmts = magic.safe_loads(raw_contents, class_factory, {"_ast", "collections"})
|
110 |
+
return stmts
|
111 |
+
|
112 |
+
|
113 |
+
def decompile_rpyc(input_filename, overwrite=False, dump=False, decompile_python=False,
|
114 |
+
comparable=False, no_pyexpr=False, translator=None, tag_outside_block=False,
|
115 |
+
init_offset=False, try_harder=False):
|
116 |
+
# Output filename is input filename but with .rpy extension
|
117 |
+
filepath, ext = path.splitext(input_filename)
|
118 |
+
if dump:
|
119 |
+
out_filename = filepath + ".txt"
|
120 |
+
elif ext == ".rpymc":
|
121 |
+
out_filename = filepath + ".rpym"
|
122 |
+
else:
|
123 |
+
out_filename = filepath + ".rpy"
|
124 |
+
|
125 |
+
print("Decompiling %s to %s..." % (input_filename, out_filename))
|
126 |
+
|
127 |
+
if not overwrite and path.exists(out_filename):
|
128 |
+
print("Output file already exists. Pass --clobber to overwrite.")
|
129 |
+
return False # Don't stop decompiling if one file already exists
|
130 |
+
|
131 |
+
with open(input_filename, 'rb') as in_file:
|
132 |
+
if try_harder:
|
133 |
+
ast = deobfuscate.read_ast(in_file)
|
134 |
+
else:
|
135 |
+
ast = read_ast_from_file(in_file)
|
136 |
+
|
137 |
+
with codecs.open(out_filename, 'w', encoding='utf-8') as out_file:
|
138 |
+
if dump:
|
139 |
+
astdump.pprint(out_file, ast, decompile_python=decompile_python, comparable=comparable,
|
140 |
+
no_pyexpr=no_pyexpr)
|
141 |
+
else:
|
142 |
+
decompiler.pprint(out_file, ast, decompile_python=decompile_python, printlock=False,
|
143 |
+
translator=translator, tag_outside_block=tag_outside_block,
|
144 |
+
init_offset=init_offset)
|
145 |
+
return True
|
146 |
+
|
147 |
+
def extract_translations(input_filename, language):
|
148 |
+
print("Extracting translations from %s..." % input_filename)
|
149 |
+
|
150 |
+
with open(input_filename, 'rb') as in_file:
|
151 |
+
ast = read_ast_from_file(in_file)
|
152 |
+
|
153 |
+
translator = translate.Translator(language, True)
|
154 |
+
translator.translate_dialogue(ast)
|
155 |
+
# we pickle and unpickle this manually because the regular unpickler will choke on it
|
156 |
+
return magic.safe_dumps(translator.dialogue), translator.strings
|
157 |
+
|
158 |
+
def worker(t):
|
159 |
+
(args, filename, filesize) = t
|
160 |
+
try:
|
161 |
+
if args.write_translation_file:
|
162 |
+
return extract_translations(filename, args.language)
|
163 |
+
else:
|
164 |
+
if args.translation_file is not None:
|
165 |
+
translator = translate.Translator(None)
|
166 |
+
translator.language, translator.dialogue, translator.strings = magic.loads(args.translations, class_factory)
|
167 |
+
else:
|
168 |
+
translator = None
|
169 |
+
return decompile_rpyc(filename, args.clobber, args.dump, decompile_python=args.decompile_python,
|
170 |
+
no_pyexpr=args.no_pyexpr, comparable=args.comparable, translator=translator,
|
171 |
+
tag_outside_block=args.tag_outside_block, init_offset=args.init_offset, try_harder=args.try_harder)
|
172 |
+
except Exception as e:
|
173 |
+
print("Error while decompiling %s:" % filename)
|
174 |
+
print(traceback.format_exc())
|
175 |
+
return False
|
176 |
+
|
177 |
+
def main():
|
178 |
+
# python27 unrpyc.py [-c] [-d] [--python-screens|--ast-screens|--no-screens] file [file ...]
|
179 |
+
parser = argparse.ArgumentParser(description="Decompile .rpyc/.rpymc files")
|
180 |
+
|
181 |
+
parser.add_argument('-c', '--clobber', dest='clobber', action='store_true',
|
182 |
+
help="overwrites existing output files")
|
183 |
+
|
184 |
+
parser.add_argument('-d', '--dump', dest='dump', action='store_true',
|
185 |
+
help="instead of decompiling, pretty print the ast to a file")
|
186 |
+
|
187 |
+
parser.add_argument('-p', '--processes', dest='processes', action='store', default=1,
|
188 |
+
help="use the specified number of processes to decompile")
|
189 |
+
|
190 |
+
parser.add_argument('-t', '--translation-file', dest='translation_file', action='store', default=None,
|
191 |
+
help="use the specified file to translate during decompilation")
|
192 |
+
|
193 |
+
parser.add_argument('-T', '--write-translation-file', dest='write_translation_file', action='store', default=None,
|
194 |
+
help="store translations in the specified file instead of decompiling")
|
195 |
+
|
196 |
+
parser.add_argument('-l', '--language', dest='language', action='store', default='english',
|
197 |
+
help="if writing a translation file, the language of the translations to write")
|
198 |
+
|
199 |
+
parser.add_argument('--sl1-as-python', dest='decompile_python', action='store_true',
|
200 |
+
help="Only dumping and for decompiling screen language 1 screens. "
|
201 |
+
"Convert SL1 Python AST to Python code instead of dumping it or converting it to screenlang.")
|
202 |
+
|
203 |
+
parser.add_argument('--comparable', dest='comparable', action='store_true',
|
204 |
+
help="Only for dumping, remove several false differences when comparing dumps. "
|
205 |
+
"This suppresses attributes that are different even when the code is identical, such as file modification times. ")
|
206 |
+
|
207 |
+
parser.add_argument('--no-pyexpr', dest='no_pyexpr', action='store_true',
|
208 |
+
help="Only for dumping, disable special handling of PyExpr objects, instead printing them as strings. "
|
209 |
+
"This is useful when comparing dumps from different versions of Ren'Py. "
|
210 |
+
"It should only be used if necessary, since it will cause loss of information such as line numbers.")
|
211 |
+
|
212 |
+
parser.add_argument('--tag-outside-block', dest='tag_outside_block', action='store_true',
|
213 |
+
help="Always put SL2 'tag's on the same line as 'screen' rather than inside the block. "
|
214 |
+
"This will break compiling with Ren'Py 7.3 and above, but is needed to get correct line numbers "
|
215 |
+
"from some files compiled with older Ren'Py versions.")
|
216 |
+
|
217 |
+
parser.add_argument('--init-offset', dest='init_offset', action='store_true',
|
218 |
+
help="Attempt to guess when init offset statements were used and insert them. "
|
219 |
+
"This is always safe to enable if the game's Ren'Py version supports init offset statements, "
|
220 |
+
"and the generated code is exactly equivalent, only less cluttered.")
|
221 |
+
|
222 |
+
parser.add_argument('file', type=str, nargs='+',
|
223 |
+
help="The filenames to decompile. "
|
224 |
+
"All .rpyc files in any directories passed or their subdirectories will also be decompiled.")
|
225 |
+
|
226 |
+
parser.add_argument('--try-harder', dest="try_harder", action="store_true",
|
227 |
+
help="Tries some workarounds against common obfuscation methods. This is a lot slower.")
|
228 |
+
|
229 |
+
args = parser.parse_args()
|
230 |
+
|
231 |
+
if args.write_translation_file and not args.clobber and path.exists(args.write_translation_file):
|
232 |
+
# Fail early to avoid wasting time going through the files
|
233 |
+
print("Output translation file already exists. Pass --clobber to overwrite.")
|
234 |
+
return
|
235 |
+
|
236 |
+
if args.translation_file:
|
237 |
+
with open(args.translation_file, 'rb') as in_file:
|
238 |
+
args.translations = in_file.read()
|
239 |
+
|
240 |
+
# Expand wildcards
|
241 |
+
def glob_or_complain(s):
|
242 |
+
retval = glob.glob(s)
|
243 |
+
if not retval:
|
244 |
+
print("File not found: " + s)
|
245 |
+
return retval
|
246 |
+
filesAndDirs = map(glob_or_complain, args.file)
|
247 |
+
# Concatenate lists
|
248 |
+
filesAndDirs = list(itertools.chain(*filesAndDirs))
|
249 |
+
|
250 |
+
# Recursively add .rpyc files from any directories passed
|
251 |
+
files = []
|
252 |
+
for i in filesAndDirs:
|
253 |
+
if path.isdir(i):
|
254 |
+
for dirpath, dirnames, filenames in walk(i):
|
255 |
+
files.extend(path.join(dirpath, j) for j in filenames if len(j) >= 5 and j.endswith(('.rpyc', '.rpymc')))
|
256 |
+
else:
|
257 |
+
files.append(i)
|
258 |
+
|
259 |
+
# Check if we actually have files. Don't worry about
|
260 |
+
# no parameters passed, since ArgumentParser catches that
|
261 |
+
if len(files) == 0:
|
262 |
+
print("No script files to decompile.")
|
263 |
+
return
|
264 |
+
|
265 |
+
files = map(lambda x: (args, x, path.getsize(x)), files)
|
266 |
+
processes = int(args.processes)
|
267 |
+
|
268 |
+
# Decompile in the order Ren'Py loads in
|
269 |
+
files.sort(key=itemgetter(1))
|
270 |
+
results = map(worker, files)
|
271 |
+
|
272 |
+
if args.write_translation_file:
|
273 |
+
print("Writing translations to %s..." % args.write_translation_file)
|
274 |
+
translated_dialogue = {}
|
275 |
+
translated_strings = {}
|
276 |
+
good = 0
|
277 |
+
bad = 0
|
278 |
+
for result in results:
|
279 |
+
if not result:
|
280 |
+
bad += 1
|
281 |
+
continue
|
282 |
+
good += 1
|
283 |
+
translated_dialogue.update(magic.loads(result[0], class_factory))
|
284 |
+
translated_strings.update(result[1])
|
285 |
+
with open(args.write_translation_file, 'wb') as out_file:
|
286 |
+
magic.safe_dump((args.language, translated_dialogue, translated_strings), out_file)
|
287 |
+
|
288 |
+
else:
|
289 |
+
# Check per file if everything went well and report back
|
290 |
+
good = results.count(True)
|
291 |
+
bad = results.count(False)
|
292 |
+
|
293 |
+
if bad == 0:
|
294 |
+
print("Decompilation of %d script file%s successful" % (good, 's' if good>1 else ''))
|
295 |
+
elif good == 0:
|
296 |
+
print("Decompilation of %d file%s failed" % (bad, 's' if bad>1 else ''))
|
297 |
+
else:
|
298 |
+
print("Decompilation of %d file%s successful, but decompilation of %d file%s failed" % (good, 's' if good>1 else '', bad, 's' if bad>1 else ''))
|
299 |
+
|
300 |
+
if __name__ == '__main__':
|
301 |
+
main()
|
renpy/rpycdec/rpycdecdata/unrpyc.pyo
ADDED
Binary file (14 kB). View file
|
|