Example #1
0
def _get_coroutine_flag() -> Optional[int]:
    for k, v in COMPILER_FLAG_NAMES.items():
        if v == "COROUTINE":
            return k

    # Flag not found.
    return None
Example #2
0
from collections import namedtuple
from inspect import iscode, isframe

# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication, but fall
# back to hardcoding so the dependency is optional
try:
    from dis import COMPILER_FLAG_NAMES
except ImportError:
    CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
    CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
    CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
else:
    mod_dict = globals()
    for k, v in COMPILER_FLAG_NAMES.items():
        mod_dict["CO_" + v] = k

ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')


def getargvalues(frame):
    """
    Function to get information about arguments passed into a
    particular frame.
    
    @param frame reference to a frame object to be processed
    @type frame
    @return tuple of four things, where 'args' is a list of the argument names,
        'varargs' and 'varkw' are the names of the * and ** arguments or None
        and 'locals' is the locals dictionary of the given frame.
import linecache
from operator import attrgetter
from collections import namedtuple

# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication, but fall
# back to hardcording so the dependency is optional
try:
    from dis import COMPILER_FLAG_NAMES as _flag_names
except ImportError:
    CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
    CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
    CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
else:
    mod_dict = globals()
    for k, v in list(_flag_names.items()):
        mod_dict["CO_" + v] = k

# See Include/object.h
TPFLAGS_IS_ABSTRACT = 1 << 20

# ----------------------------------------------------------- type-checking
def ismodule(object):
    """Return true if the object is a module.

    Module objects provide these attributes:
        __cached__      pathname to byte compiled file
        __doc__         documentation string
        __file__        filename (missing for built-in modules)"""
    return isinstance(object, types.ModuleType)
import linecache
from operator import attrgetter
from collections import namedtuple

# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication, but fall
# back to hardcording so the dependency is optional
try:
    from dis import COMPILER_FLAG_NAMES as _flag_names
except ImportError:
    CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
    CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
    CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
else:
    mod_dict = globals()
    for k, v in _flag_names.items():
        mod_dict["CO_" + v] = k

# See Include/object.h
TPFLAGS_IS_ABSTRACT = 1 << 20

# ----------------------------------------------------------- type-checking
def ismodule(object):
    """Return true if the object is a module.

    Module objects provide these attributes:
        __cached__      pathname to byte compiled file
        __doc__         documentation string
        __file__        filename (missing for built-in modules)"""
    return isinstance(object, types.ModuleType)
Example #5
0
# ~*~ conding: utf8; ~*~
from ast import literal_eval
from dis import COMPILER_FLAG_NAMES, dis, show_code
from opcode import opmap
import re
from sys import argv
from timeit import timeit
from types import CodeType, FunctionType

COMPILER_FLAGS = {k: v for v, k in COMPILER_FLAG_NAMES.items()}
DIS = re.compile(r"(?P<lineno>.{3}) "
                 r"(?P<current_mark>.{3}) "
                 r"(?P<jump_target>.{2}) "
                 r"(?P<offset>.{4}) "
                 r"(?P<opname>.{,20}) ?"
                 r"(?P<oparg>.{,5}) ?"
                 r"\(?(?P<argrepr>.*?)\)?")


def _tuple_from_dict(d):
    n = len(d) if 0 in d else len(d) + 1
    return tuple(d.get(i) for i in range(n))


def assemble(func: callable):
    """invert dis.Instruction._disassemble"""
    code = bytearray()
    lnotab = bytearray()
    consts = {}
    names = {}
    varnames = {}
Example #6
0
File: asm.py Project: bhuztez/fml
from enum import Enum
from dis import opmap, opname, COMPILER_FLAG_NAMES, hasconst, hasjabs, hasjrel, HAVE_ARGUMENT, stack_effect
from types import CodeType

COMPILER_FLAGS = {f"CO_{v}": k for k, v in COMPILER_FLAG_NAMES.items()}


class Instruction:
    offset = 0

    def __init__(self, opcode, arg):
        self.opcode = opcode
        self.arg = arg

    def __repr__(self):
        return '{}({})'.format(opname[self.opcode], self.arg)


class Label:
    offset = 0
    stacksize = None


class LineNumber:
    offset = 0

    def __init__(self, n):
        self.n = n


def get_constants(insts):
Example #7
0
from collections import namedtuple
from inspect import iscode, isframe

# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication, but fall
# back to hardcoding so the dependency is optional
try:
    from dis import COMPILER_FLAG_NAMES
except ImportError:
    CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
    CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
    CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
else:
    mod_dict = globals()
    for k, v in COMPILER_FLAG_NAMES.items():
        mod_dict["CO_" + v] = k

ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')


def getargvalues(frame):
    """
    Function to get information about arguments passed into a
    particular frame.
    
    @param frame reference to a frame object to be processed
    @type frame
    @return tuple of four things, where 'args' is a list of the argument names,
        'varargs' and 'varkw' are the names of the * and ** arguments or None
        and 'locals' is the locals dictionary of the given frame.
Example #8
0
https://legacy.python.org/workshops/1998-11/proceedings/papers/montanaro/montanaro.html
https://users.ece.cmu.edu/~koopman/stack_compiler/stack_co.pdf
https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/index.html
http://git.annexia.org/?p=jonesforth.git;a=blob;f=jonesforth.S
https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d
http://cubbi.com/fibonacci/forth.html
"""
from argparse import ArgumentParser
from ast import literal_eval
from dis import COMPILER_FLAG_NAMES, dis, show_code
from opcode import cmp_op, hasjrel, opmap
from timeit import timeit
from types import CodeType, FunctionType

COMPILER_FLAGS = {v: k for k, v in COMPILER_FLAG_NAMES.items()}


def _gen_emitter(ops):
    code = tuple(byte for op in ops.split() for byte in (opmap[op], 0))

    def emitter(self, word):
        return code
    return emitter


class ForthCompilerMeta:
    def __new__(meta, name, bases, dct):
        ops = {
            "+": "INPLACE_ADD",
            "-": "INPLACE_SUBTRACT",
Example #9
0
from itertools import accumulate
from opcode import (
    EXTENDED_ARG,
    HAVE_ARGUMENT,
    cmp_op,
    hascompare,
    hasconst,
    hasfree,
    haslocal,
    hasname,
    opname,
)
from types import CodeType

CompilerFlags = IntFlag("CompilerFlags",
                        " ".join(COMPILER_FLAG_NAMES.values()))
MakeFunctionFlags = IntFlag(
    "MakeFunctionFlags",
    " ".join(flag.upper() for flag in MAKE_FUNCTION_FLAGS))


class CodeBuilderBase:
    def __init__(self):
        self.consts = {None: 0}
        self.names = {}
        self.varnames = {}
        self.cellvars = {}
        self.freevars = {}

    def ascode(self, func_name: str, argcount: int) -> CodeType:
        code = bytes(self)
Example #10
0
"""
Various debug utilities
"""

import json
import sys
from collections import namedtuple
from inspect import iscode, isframe
from dis import COMPILER_FLAG_NAMES
from PyQt5.QtNetwork import QAbstractSocket

MAX_TRIES = 3

# Create constants for the compiler flags in Include/code.h
mod_dict = globals()
for flagName, value in COMPILER_FLAG_NAMES.items():
    mod_dict['CO_' + value] = flagName

ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')


def printerr(s):
    """debugging the debug client printout"""
    sys.__stderr__.write('{0!s}\n'.format(s))
    sys.__stderr__.flush()


def prepareJSONMessage(method, procuuid, params):
    """Prepares a JSON message to be send"""
    msg = json.dumps({
        'jsonrpc': '2.0',
Example #11
0
import sys
import tokenize
import types
import warnings
import functools
import builtins
from operator import attrgetter
from collections import namedtuple, OrderedDict
try:
    from dis import COMPILER_FLAG_NAMES as _flag_names
except ImportError:
    (CO_OPTIMIZED, CO_NEWLOCALS) = (1, 2)
    (CO_VARARGS, CO_VARKEYWORDS) = (4, 8)
    (CO_NESTED, CO_GENERATOR, CO_NOFREE) = (16, 32, 64)
mod_dict = globals()
for (k, v) in _flag_names.items():
    mod_dict['CO_' + v] = k
TPFLAGS_IS_ABSTRACT = 1048576

def ismodule(object):
    return isinstance(object, types.ModuleType)

def isclass(object):
    return isinstance(object, type)

def ismethod(object):
    return isinstance(object, types.MethodType)

def ismethoddescriptor(object):
    if isclass(object) or ismethod(object) or isfunction(object):
        return False