|
| 1 | +# type: ignore |
| 2 | +import ast |
| 3 | +import string |
| 4 | +from ast import unparse |
| 5 | +from typing import Any, Dict, List |
| 6 | + |
| 7 | +CONSTANTS = ( |
| 8 | + ast.Name, |
| 9 | + ast.Constant, |
| 10 | + ast.Str, |
| 11 | + ast.Num, |
| 12 | + ast.Bytes, |
| 13 | + ast.Ellipsis, |
| 14 | + ast.NameConstant, |
| 15 | + ast.Attribute, |
| 16 | + ast.Subscript, |
| 17 | + ast.Tuple, |
| 18 | +) |
| 19 | + |
| 20 | +__all__ = ( |
| 21 | + "StringSubscriptSimple", |
| 22 | + "GlobalsToVarAccess", |
| 23 | + "InlineConstants", |
| 24 | + "DunderImportRemover", |
| 25 | + "GetattrConstructRemover", |
| 26 | + "BuiltinsAccessRemover", |
| 27 | + "Dehexlify", |
| 28 | + "UselessEval", |
| 29 | + "UselessCompile", |
| 30 | + "ExecTransformer", |
| 31 | + "UselessLambda", |
| 32 | + "LambdaCalls", |
| 33 | + "EmptyIf", |
| 34 | + "RemoveFromBuiltins", |
| 35 | +) |
| 36 | + |
| 37 | +constants: Dict[str, Any] = {} |
| 38 | +lambdas: List[str] = [] |
| 39 | + |
| 40 | + |
| 41 | +class StringSubscriptSimple(ast.NodeTransformer): |
| 42 | + """Transforms Hyperion specific string slicing into a string literal""" |
| 43 | + |
| 44 | + def visit_Subscript(self, node: ast.Subscript): |
| 45 | + if isinstance(node.value, ast.Str) and isinstance(node.slice, ast.Slice): |
| 46 | + code = unparse(node.slice.step) |
| 47 | + if all(s not in code for s in string.ascii_letters): |
| 48 | + |
| 49 | + s = node.value.s[:: eval(unparse(node.slice.step))] |
| 50 | + return ast.Str(s=s) |
| 51 | + return super().generic_visit(node) |
| 52 | + |
| 53 | + |
| 54 | +class GlobalsToVarAccess(ast.NodeTransformer): |
| 55 | + def visit_Subscript(self, node: ast.Subscript) -> Any: |
| 56 | + if ( |
| 57 | + ( |
| 58 | + isinstance(node.value, ast.Call) |
| 59 | + and isinstance(node.value.func, ast.Name) |
| 60 | + and node.value.func.id in ("globals", "locals", "vars") |
| 61 | + ) |
| 62 | + and isinstance(node.slice, ast.Constant) |
| 63 | + and isinstance(node.slice.value, str) |
| 64 | + ): |
| 65 | + return ast.Name(id=node.slice.value, ctx=ast.Load()) |
| 66 | + return super().generic_visit(node) |
| 67 | + |
| 68 | + |
| 69 | +class InlineConstants(ast.NodeTransformer): |
| 70 | + class FindConstants(ast.NodeTransformer): |
| 71 | + def visit_Assign(self, node: ast.Assign) -> Any: |
| 72 | + if isinstance(node.value, CONSTANTS) and isinstance( |
| 73 | + node.targets[0], ast.Name |
| 74 | + ): |
| 75 | + constants[node.targets[0].id] = node.value |
| 76 | + # delete the assignment |
| 77 | + return ast.Module(body=[], type_ignores=[]) |
| 78 | + return super().generic_visit(node) |
| 79 | + |
| 80 | + def visit(self, node: Any) -> Any: |
| 81 | + self.FindConstants().visit(node) |
| 82 | + return super().visit(node) |
| 83 | + |
| 84 | + def visit_Name(self, node: ast.Name) -> Any: |
| 85 | + """Replace the name with the constant if it's in the constants dict""" |
| 86 | + if node.id in constants: |
| 87 | + return constants[node.id] |
| 88 | + return super().generic_visit(node) |
| 89 | + |
| 90 | + |
| 91 | +class DunderImportRemover(ast.NodeTransformer): |
| 92 | + """Just transform all __import__ calls to the name of the module being imported""" |
| 93 | + |
| 94 | + def visit_Call(self, node: ast.Call) -> Any: |
| 95 | + if isinstance(node.func, ast.Name) and node.func.id == "__import__": |
| 96 | + return ast.Name(id=node.args[0].s, ctx=ast.Load()) |
| 97 | + return super().generic_visit(node) |
| 98 | + |
| 99 | + |
| 100 | +class GetattrConstructRemover(ast.NodeTransformer): |
| 101 | + """Hyperion has an interesting way of accessing module attributes.""" |
| 102 | + |
| 103 | + def visit_Call(self, node: ast.Call) -> Any: |
| 104 | + |
| 105 | + if isinstance(node.func, ast.Name) and node.func.id == "getattr": |
| 106 | + return ast.Attribute(value=node.args[0], attr=node.args[1].slice.args[0].s) |
| 107 | + |
| 108 | + return super().generic_visit(node) |
| 109 | + |
| 110 | + |
| 111 | +class BuiltinsAccessRemover(ast.NodeTransformer): |
| 112 | + """Instead of accessing builtins, just use the name directly""" |
| 113 | + |
| 114 | + def visit_Attribute(self, node: ast.Attribute) -> Any: |
| 115 | + if isinstance(node.value, ast.Name) and node.value.id == "builtins": |
| 116 | + return ast.Name(id=node.attr, ctx=ast.Load()) |
| 117 | + return super().generic_visit(node) |
| 118 | + |
| 119 | + |
| 120 | +class Dehexlify(ast.NodeTransformer): |
| 121 | + """Transforms a binascii.unhexlify(b'').decode('utf8') into a string""" |
| 122 | + |
| 123 | + def visit_Call(self, node: ast.Call) -> Any: |
| 124 | + if ( |
| 125 | + isinstance(node.func, ast.Attribute) |
| 126 | + and node.func.attr == "decode" |
| 127 | + and ( |
| 128 | + isinstance(node.func.value, ast.Call) |
| 129 | + and isinstance(node.func.value.func, ast.Attribute) |
| 130 | + and node.func.value.func.attr == "unhexlify" |
| 131 | + ) |
| 132 | + ): |
| 133 | + return ast.Str( |
| 134 | + s=bytes.fromhex(node.func.value.args[0].s.decode()).decode("utf8") |
| 135 | + ) |
| 136 | + return super().generic_visit(node) |
| 137 | + |
| 138 | + |
| 139 | +class UselessEval(ast.NodeTransformer): |
| 140 | + """Eval can just be replaced with the string""" |
| 141 | + |
| 142 | + def visit_Call(self, node: ast.Call) -> Any: |
| 143 | + if ( |
| 144 | + isinstance(node.func, ast.Name) |
| 145 | + and node.func.id == "eval" |
| 146 | + and isinstance(node.args[0], ast.Str) |
| 147 | + ): |
| 148 | + return ast.parse(node.args[0].s).body[0].value |
| 149 | + return super().generic_visit(node) |
| 150 | + |
| 151 | + |
| 152 | +class UselessCompile(ast.NodeTransformer): |
| 153 | + """An call to compile() in Hyperion is usually useless""" |
| 154 | + |
| 155 | + def visit_Call(self, node: ast.Call) -> Any: |
| 156 | + if ( |
| 157 | + isinstance(node.func, ast.Name) |
| 158 | + and node.func.id == "compile" |
| 159 | + and isinstance(node.args[0], ast.Str) |
| 160 | + ): |
| 161 | + return node.args[0] |
| 162 | + return super().generic_visit(node) |
| 163 | + |
| 164 | + |
| 165 | +class ExecTransformer(ast.NodeTransformer): |
| 166 | + """Exec can be just transformed into bare code""" |
| 167 | + |
| 168 | + def visit_Call(self, node: ast.Call) -> Any: |
| 169 | + if ( |
| 170 | + isinstance(node.func, ast.Name) |
| 171 | + and node.func.id == "exec" |
| 172 | + and isinstance(node.args[0], ast.Str) |
| 173 | + ): |
| 174 | + try: |
| 175 | + if result := ast.parse(node.args[0].s).body: |
| 176 | + return result[0] |
| 177 | + except SyntaxError: |
| 178 | + pass |
| 179 | + return super().generic_visit(node) |
| 180 | + |
| 181 | + |
| 182 | +class UselessLambda(ast.NodeTransformer): |
| 183 | + # x = lambda: y() -> x = y |
| 184 | + def visit_Assign(self, node: ast.Assign) -> Any: |
| 185 | + if ( |
| 186 | + isinstance(node.value, ast.Lambda) |
| 187 | + and isinstance(node.value.body, ast.Call) |
| 188 | + and not node.value.body.args # make sure both call and lambda have no argument |
| 189 | + and not node.value.args |
| 190 | + ): |
| 191 | + |
| 192 | + return ast.Assign( |
| 193 | + targets=node.targets, |
| 194 | + value=node.value.body.func, |
| 195 | + lineno=node.lineno, |
| 196 | + col_offset=node.col_offset, |
| 197 | + ) |
| 198 | + |
| 199 | + return super().generic_visit(node) |
| 200 | + |
| 201 | + |
| 202 | +class LambdaSingleArgs(ast.NodeTransformer): |
| 203 | + """Find all lambdas that lambda a: b()""" |
| 204 | + |
| 205 | + def visit_Assign(self, node: ast.Assign) -> Any: |
| 206 | + if ( |
| 207 | + isinstance(node.value, ast.Lambda) |
| 208 | + and isinstance(node.value.body, ast.Call) |
| 209 | + and not node.value.body.args |
| 210 | + and len(node.value.args.args) == 1 |
| 211 | + ): |
| 212 | + lambdas.append(node.targets[0].id) |
| 213 | + constants[node.targets[0].id] = node.value.body.func |
| 214 | + return ast.Module(body=[], type_ignores=[]) |
| 215 | + |
| 216 | + |
| 217 | +class LambdaCalls(ast.NodeTransformer): |
| 218 | + """Transforms calls to an assigned lambda into the lambda itself""" |
| 219 | + |
| 220 | + def visit(self, node: Any) -> Any: |
| 221 | + LambdaSingleArgs().visit(node) |
| 222 | + return super().visit(node) |
| 223 | + |
| 224 | + def visit_Call(self, node: ast.Call) -> Any: |
| 225 | + if isinstance(node.func, ast.Name) and node.func.id in lambdas: |
| 226 | + |
| 227 | + return ast.Call( |
| 228 | + func=constants[node.func.id], |
| 229 | + args=[], |
| 230 | + keywords=[], |
| 231 | + ) |
| 232 | + |
| 233 | + return super().generic_visit(node) |
| 234 | + |
| 235 | + |
| 236 | +class EmptyIf(ast.NodeTransformer): |
| 237 | + """Remove useless if statements""" |
| 238 | + |
| 239 | + def visit_If(self, node: ast.If) -> Any: |
| 240 | + if type(node.test) is ast.Constant and not bool(node.test.value): |
| 241 | + return ast.Module(body=[], type_ignores=[]) |
| 242 | + return super().generic_visit(node) |
| 243 | + |
| 244 | + |
| 245 | +class RemoveFromBuiltins(ast.NodeTransformer): |
| 246 | + """Remove all from builtins import *""" |
| 247 | + |
| 248 | + def visit_ImportFrom(self, node: ast.ImportFrom) -> Any: |
| 249 | + if node.module == "builtins": |
| 250 | + return ast.Module(body=[], type_ignores=[]) |
| 251 | + return super().generic_visit(node) |
0 commit comments