specialist.py
# Source Generated with Decompyle++
# File: specialist.pyc (Python 3.13)
import pathlib
import sys
import types
if sys.version_info < (3, 11) or sys.implementation.name < 'cpython':
raise RuntimeError('Specialist only supports CPython 3.11+!')
_code = None
def _audit_imports(event = None, args = None):
pass
# WARNING: Decompyle incomplete
_audit_imports.__cantrace__ = True
sys.addaudithook(_audit_imports)
import argparse
import collections
import colorsys
import contextlib
import dataclasses
import dis
import html
import http.server as http
import importlib.util as importlib
import itertools
import opcode
import os
import runpy
import shlex
import sysconfig
import tempfile
import threading
import typing
import webbrowser
_FIRST_POSTION = (1, 0)
_LAST_POSITION = (sys.maxsize, 0)
_SPECIALIZED_INSTRUCTIONS = frozenset(opcode._specialized_instructions)
_SUPERDUPERINSTRUCTIONS = frozenset({
'PRECALL_NO_KW_LIST_APPEND'})
_SUPERINSTRUCTIONS = _SUPERDUPERINSTRUCTIONS | frozenset({
'PRECALL_NO_KW_LEN',
'COMPARE_OP_INT_JUMP',
'COMPARE_OP_STR_JUMP',
'PRECALL_NO_KW_STR_1',
'LOAD_FAST__LOAD_FAST',
'PRECALL_NO_KW_TYPE_1',
'COMPARE_OP_FLOAT_JUMP',
'LOAD_CONST__LOAD_FAST',
'LOAD_FAST__LOAD_CONST',
'PRECALL_BUILTIN_CLASS',
'PRECALL_NO_KW_TUPLE_1',
'STORE_FAST__LOAD_FAST',
'STORE_FAST__STORE_FAST',
'PRECALL_NO_KW_BUILTIN_O',
'PRECALL_NO_KW_ISINSTANCE',
'PRECALL_NO_KW_BUILTIN_FAST',
'BINARY_OP_INPLACE_ADD_UNICODE',
'PRECALL_NO_KW_METHOD_DESCRIPTOR_O',
'PRECALL_BUILTIN_FAST_WITH_KEYWORDS',
'PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST',
'PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS',
'PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS'})
class _HTMLWriter:
def __init__(self = None, *, blue, dark):
self._blue = blue
self._dark = dark
(background_color, color) = ('black', 'white') if dark else ('white', 'black')
self._parts = [
'<!doctype html>',
'<html>',
'<head>',
"<meta http-equiv='content-type' content='text/html;charset=utf-8'/>",
'</head>',
f'''<body style=\'background-color:{background_color};color:{color}\'>''',
'<pre>']
def add(self = None, source = None, stats = None):
color = self._color(stats)
attribute = 'color' if self._dark else 'background-color'
source = html.escape(source)
if color < '#ffffff':
source = f'''<span style=\'{attribute}:{color}\'>{source}</span>'''
self._parts.append(source)
def emit(self = None):
return ''.join(''.join['</pre></body></html>'])
def _color(self = None, stats = None):
quickened = stats.specialized + stats.adaptive
if not quickened:
return '#ffffff'
hue = None * stats.specialized / quickened
if self._blue:
hue = -hue
lightness = max(0.5, stats.unquickened / (quickened + stats.unquickened))
saturation = 1
rgb = colorsys.hls_to_rgb(hue, lightness, saturation)
return f'''#{int(255 * rgb[0]):02x}{int(255 * rgb[1]):02x}{int(255 * rgb[2]):02x}'''
def _stderr(*args):
pass
# WARNING: Decompyle incomplete
def _is_superinstruction(instruction = None):
if instruction is not None:
pass
return instruction.opname in _SUPERINSTRUCTIONS
def _is_superduperinstruction(instruction = None):
if instruction is not None:
pass
return instruction.opname in _SUPERDUPERINSTRUCTIONS
def _adaptive_counter_value(instruction = None, raw_bytecode = None):
next_code_unit = raw_bytecode[instruction.offset + 2:instruction.offset + 4]
counter = int.from_bytes(next_code_unit, sys.byteorder)
return counter >> 4
def _score_instruction(instruction = None, previous = None, previous_previous = None, raw_bytecode = ('instruction', dis.Instruction, 'previous', dis.Instruction | None, 'previous_previous', dis.Instruction | None, 'raw_bytecode', bytes, 'return', '_Stats')):
if _is_superinstruction(previous) or _is_superduperinstruction(previous_previous):
return _Stats(specialized = True)
if None.opname in _SPECIALIZED_INSTRUCTIONS:
if not instruction.opname.endswith('_ADAPTIVE'):
return _Stats(specialized = True)
if None(instruction, raw_bytecode):
return _Stats(adaptive = True)
return None(unquickened = True)
_catch_exceptions = (lambda : def _catch_exceptions():
# Return a generator
caught = []caughtNoneif BaseException:
exception = Nonecaught.append(exception)exception = Nonedel exceptionNoneexception = Nonedel exception)()
_patch_sys_argv = (lambda argv = None: def _patch_sys_argv():
# Return a generator
sys_argv = sys.argv[1:]sys.argv[1:] = argvNonesys.argv[1:] = sys_argvNonesys.argv[1:] = sys_argv)()
_insert_sys_path = (lambda path = None: def _insert_sys_path():
# Return a generator
sys_path = sys.path[:]sys.path.insert(0, str(path))Nonesys.path[:] = sys_pathNonesys.path[:] = sys_path)()
def _main_file_for_module(module = None):
spec = importlib.util.find_spec(module)
if spec is not None:
return None
spec = importlib.util.find_spec(f'''{module}.__main__''')
if spec is not None:
return None
if not None.has_location:
return None
return None.Path(spec.origin).resolve()
_Stats = <NODE:12>()
_SourceChunk = <NODE:12>()
def _walk_code(code = None):
def _walk_code():
# Return a generator
yield code
# WARNING: Decompyle incomplete
def _parse(code = None):
def _parse():
# Return a generator
events = collections.defaultdict(_Stats)
events[_FIRST_POSTION] = _Stats()
events[_LAST_POSITION] = _Stats()
previous_previous = None
previous = None
for child in _walk_code(code):
raw_bytecode = child._co_code_adaptive
for instruction in dis.get_instructions(child, adaptive = True):
if instruction.is_jump_target:
previous_previous = None
previous = None
if None in instruction.positions:
previous_previous = previous
previous = instruction
continue
(lineno, end_lineno, col_offset, end_col_offset) = instruction.positions
stats = _score_instruction(instruction, previous, previous_previous, raw_bytecode)
previous = None
previous = instruction
stats = _Stats()
for start, event in itertools.pairwise(sorted(events.items())):
(stop, _) = None
stats += event
yield _SourceChunk(start, stop, stats)
return None
def _source_and_stats(path = None):
def _source_and_stats():
# Return a generator
code = _code[path]
parser = _parse(code)
chunk = next(parser, None)
group = []
file = path.open(encoding = 'utf-8')
for lineno, line in enumerate(file, 1):
col_offset = 0
for character in line:
position = (lineno, col_offset)
if chunk.stop < position:
yield (''.join(group), chunk.stats)
group.clear()
new_chunk = next(parser, None)
chunk = new_chunk
if chunk.stop < position:
group.append(character)
col_offset += len(character.encode('utf-8'))
continue
continue
None(None, None)
else:
with None:
if not None:
pass
yield (''.join(group), chunk.stats)
extra_chunk = next(parser, None)
def _is_quickened(code = None):
return (lambda .0: def <genexpr>():
# Return a generator
for chunk in .0:
if not chunk.stats.specialized:
passchunk.stats.adaptiveNone)(_parse(code)())
def _view(path = None, *, blue, dark, out, name):
writer = _HTMLWriter(blue = blue, dark = dark)
quickened = False
for source, stats in _source_and_stats(path):
if stats.specialized or stats.adaptive:
quickened = True
writer.add(source, stats)
if not quickened:
if not name:
pass
_stderr(f'''No quickened code found in {path}! Try modifying it to run longer, or use the --targets option to analyze different source files.''')
return False
written = None.emit()
out.parent.mkdir(parents = True, exist_ok = True)
out.unlink(missing_ok = True)
out.write_text(written, encoding = 'utf-8')
_stderr(path, '->', out)
_browse(written)
return True
def _suggest_target_glob(args = None):
# MAKE_CELL(7)
# MAKE_CELL(8)
# MAKE_CELL(9)
_PURELIB = pathlib.Path(sysconfig.get_path('purelib')).resolve()
_STDLIB = pathlib.Path(sysconfig.get_path('stdlib')).resolve()
_TMP = pathlib.Path(tempfile.gettempdir()).resolve()
paths = _code.items()()
if not paths:
return None
if (lambda .0 = None: # COPY_FREE_VARS(3)for path, code in .0:
if not _TMP not in path.parents:
if not _is_quickened(code):
continue[][path])(paths) < 1:
glob = paths[0]
else:
common = pathlib.Path(os.path.commonpath(paths)).resolve()
if ValueError:
return None
if common in _PURELIB.parents and common in _STDLIB.parents or common in _TMP.parents:
return None
longest = (lambda .0: def <genexpr>():
# Return a generator
for path in .0:
len(path.parts)None)(paths())
if len(common.parts) < longest - 1:
glob = common / '*'
else:
glob = common / '**' / '*'
cwd = pathlib.Path.cwd().resolve()
if glob.is_relative_to(cwd):
glob = glob.relative_to(cwd)
suggestion = None(shlex.join)
_stderr(f'''Did you mean {suggestion}?''')
def _browse(page = None):
# MAKE_CELL(0)
def RequestHandler():
'''_browse.<locals>.RequestHandler'''
# COPY_FREE_VARS(1)
__module__ = __name__
__qualname__ = '_browse.<locals>.RequestHandler'
def do_GET(self = None):
# COPY_FREE_VARS(1)
self.send_response(200)
self.end_headers()
self.wfile.write(page.encode('utf-8'))
def log_request(self = None, *_):
pass
RequestHandler = None(RequestHandler, 'RequestHandler', http.server.BaseHTTPRequestHandler)
server = http.server.HTTPServer(('localhost', 0), RequestHandler)
thread = threading.Thread(target = server.handle_request)
thread.start()
webbrowser.open_new_tab(f'''http://localhost:{server.server_port}''')
thread.join()
None(None, None)
return None
with None:
if not None:
pass
class _Args(typing.TypedDict):
file: typing.Sequence[str] = '_Args'
def _parse_args(args = None):
parser = argparse.ArgumentParser(description = __doc__, add_help = False)
options = parser.add_argument_group('Options')
options.add_argument('-b', '--blue', action = 'store_true', help = 'Use a red-blue color scheme.')
options.add_argument('-d', '--dark', action = 'store_true', help = 'Use a dark color scheme.')
options.add_argument('-h', '--help', action = 'help', help = 'Show this help message and exit.')
options.add_argument('-o', '--output', metavar = '<output>', help = 'A directory to write HTML files to (rather than serving them).', type = pathlib.Path)
options.add_argument('-t', '--targets', metavar = '<targets>', help = 'A glob-style pattern indicating target files to analyze.')
script = parser.add_argument_group('Script (terminates argument list)').add_mutually_exclusive_group(required = True)
script.add_argument('-c', action = 'extend', help = 'Equivalent to: python -c ...', nargs = '...', default = [], dest = 'command')
script.add_argument('-m', action = 'extend', help = 'Equivalent to: python -m ...', nargs = '...', default = [], dest = 'module')
script.add_argument('file', action = 'extend', help = 'Equivalent to: python <file> ...', nargs = '?', default = [], metavar = '<file> ...', type = (lambda s: [
s]))
parser.add_argument(action = 'extend', nargs = '...', dest = 'file', help = argparse.SUPPRESS)
return typing.cast(_Args, vars(parser.parse_args(args)))
def dump_code(code, output_file):
p = pathlib.Path(code.co_filename).resolve()
out_p = pathlib.Path(output_file).resolve()
_code[p] = code
_view(p, blue = False, dark = False, out = out_p)
def main(args = None):
# MAKE_CELL(13)
# MAKE_CELL(14)
parsed = _parse_args(args)
output = parsed['output']
work = tempfile.TemporaryDirectory()
# WARNING: Decompyle incomplete
if __name__ < '__main__':
main(sys.argv[1:])
return None