Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
125 kB
diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc68ca9dd8b84c46cc676c96147c2862c2082e3 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,38 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +import sys +import os + +# insert pynalyser"s path into the system. +sys.path.insert(0, os.path.abspath("..")) + +import pynalyser # noqa + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = pynalyser.__name__ +copyright = "2022, 0dminnimda" +author = "0dminnimda" +release = pynalyser.__version__ + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = ["sphinx.ext.autodoc"] + +templates_path = ["_templates"] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = "sphinx_book_theme" +html_title = pynalyser.__name__.capitalize() + +html_static_path = ["_static"] + +html_logo = "_static/logo_icon.svg" diff --git a/pynalyser/__init__.py b/pynalyser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa6ff8d5329626659615137a0ad50f7d41a345a --- /dev/null +++ b/pynalyser/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.1.0" +__name__ = "pynalyser" diff --git a/pynalyser/acr/__init__.py b/pynalyser/acr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..475d2a03efc0391dc867bc03cf449f5b2f70e051 --- /dev/null +++ b/pynalyser/acr/__init__.py @@ -0,0 +1,3 @@ +from .classes import * +from .translation import translate_ast_to_acr +from .utils import dump, NODE, NodeVisitor, ACRCodeTransformer diff --git a/pynalyser/acr/classes.py b/pynalyser/acr/classes.py new file mode 100644 index 0000000000000000000000000000000000000000..e452dd3c59abf868ce93feccd30402a304cc1b56 --- /dev/null +++ b/pynalyser/acr/classes.py @@ -0,0 +1,323 @@ +from typing import List, Optional, Tuple, TypeVar, Union + +import attr + +from .. import ast + +ACR_T = TypeVar("ACR_T") + + +@attr.s +class ACR: + """The base class for each class of abstract representation of the code. + Inherited classes can be dumped by :func:`acr.dump <pynalyser.acr.utils.dump>`, + but for that to work properly inherited class should use `attr.s`. + """ + + _attributes: Tuple[str, ...] = attr.ib(init=False, default=()) + _fields: Tuple[str, ...] = attr.ib(init=False, default=()) + # _nonblock_fields: Tuple[str, ...] = () + # _block_fields: Tuple[str, ...] = attr.ib(init=False, default=()) + + # XXX: abc ? from_ast, to_ast + # @classmethod + # def from_ast(cls: Type[ACR_T], node: ast.AST) -> ACR_T: + # raise NotImplementedError + + # FIXME: this should run only on class creation, so metaclasses? + def __attrs_post_init__(self) -> None: + _fields = list(attr.fields_dict(type(self)).keys()) + + for name in self._attributes: + _fields.remove(name) + _fields.remove("_attributes") + _fields.remove("_fields") + + self._fields = tuple(_fields) + + # _nonblock_fields = [] + # _block_fields = [] currently in Block + + +@attr.s(auto_attribs=True) +class Name(ACR): + name: str + is_symbol: bool = attr.ib(init=False, default=False) + + _attributes: Tuple[str, ...] = attr.ib(init=False, default=("is_symbol",)) + + +@attr.s(auto_attribs=True) +class Asyncable(ACR): + is_async: bool = attr.ib(kw_only=True) + + +CODE = Union[ + # stmt - from scope body + ast.Delete, + ast.Assign, + ast.AugAssign, + ast.AnnAssign, + ast.Import, + ast.ImportFrom, + ast.Nonlocal, + ast.Global, + # Expr - no need for it + ast.Pass, # so blocks only with pass will be fine + ast.Break, + ast.Continue, + + # expr - from breakdown of complex expressions + ast.BoolOp, + ast.NamedExpr, + ast.BinOp, + ast.UnaryOp, + ast.IfExp, + ast.Dict, + ast.Set, + ast.Await, + ast.Yield, + ast.YieldFrom, # Yield(From) can be removed later + ast.Compare, + ast.Call, + ast.JoinedStr, + # FormattedValue should not exist by itself (without JoinedStr) + ast.Constant, + ast.Attribute, + ast.Subscript, + # Starred should not exist by itself (without Call or Assign) + ast.Name, # the only use for that to exit by itself + # is reporting a NameError: name 'xxx' is not defined + ast.List, + ast.Tuple, + # Slice can appear only in Subscript + + # not ast + "Scope", +] + + +CONTROL_FLOW = Union[ # TODO: not finished? + "CodeBlock", + "Block", + + # stmt - from scope body + ast.Return, + ast.Raise, + ast.Assert, + ast.Break, + ast.Continue, + + # expr - from breakdown of complex expressions + # ast.Yield, ast.YieldFrom for now it's in the CODE +] + + +# XXX: ControlFlowSomething? BlockContainer? +class FlowContainer(ACR, List[CONTROL_FLOW]): + def get_code_block(self) -> "CodeBlock": + if len(self): + block = self[-1] + if not isinstance(block, CodeBlock): + block = CodeBlock() + self.append(block) + else: + block = CodeBlock() + self.append(block) + + return block + + def add_code(self, code: CODE) -> None: + """Add code to latest block, if it's is not `CodeBlock` + function will add new `CodeBlock` to `blocks` and add code there""" + + self.get_code_block().append(code) + + +class CodeBlock(ACR, List[CODE]): + """a.k.a. Basic block""" + + pass + + +# @attr.s(auto_attribs=True) +class Block(ACR): + _block_fields: Tuple[str, ...] = () + + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() + _fields = list(self._fields) + _fields.remove("_block_fields") + self._fields = tuple(_fields) + + +@attr.s(auto_attribs=True) +class BodyBlock(Block): + body: FlowContainer = attr.ib(factory=FlowContainer, init=False) + _block_fields: Tuple[str, ...] = attr.ib(init=False, default=("body",)) + + +@attr.s(auto_attribs=True) +class Scope(Name, BodyBlock): + enclosing: bool = attr.ib(init=False, default=False) + + +class Module(Scope): + """`name` is the name of the file that this module belongs to""" + + # path? + # XXX: is_symbol = True? + pass + + +@attr.s(auto_attribs=True) +class ACRWithAttributes(ACR): + lineno: int = attr.ib(kw_only=True) + col_offset: int = attr.ib(kw_only=True) + # TODO: make end_lineno and end_col_offset required fields + # after switching to python-version-independent ast generator + # (it will generate lastest ast for earlsier python versions) + end_lineno: Optional[int] = attr.ib(default=None, kw_only=True) + end_col_offset: Optional[int] = attr.ib(default=None, kw_only=True) + + _attributes: Tuple[str, ...] = attr.ib( + init=False, default=("lineno", "col_offset", "end_lineno", "end_col_offset") + ) + + +@attr.s(auto_attribs=True) +class ScopeWithAttributes(ACRWithAttributes, Scope): + _attributes: Tuple[str, ...] = attr.ib( + init=False, + default=("lineno", "col_offset", "end_lineno", "end_col_offset", "is_symbol"), + ) + + +# we don't care about 'type_ignores' + + +@attr.s(auto_attribs=True) +class Class(ScopeWithAttributes): + bases: List[ast.expr] # parent-classes + keywords: List[ast.keyword] # initially metaclass and kws for it + decorator_list: List[ast.expr] + metaclass: Optional[type] = None # XXX: it's probably not type really + + is_symbol: bool = attr.ib(init=False, default=True) + + +@attr.s(auto_attribs=True) +class Function(ScopeWithAttributes, Asyncable): + args: ast.arguments = attr.ib(factory=ast.arguments) + decorator_list: List[ast.expr] = attr.ib(factory=list) + + is_symbol: bool = attr.ib(init=False, default=True) + enclosing: bool = attr.ib(init=False, default=True) + + +@attr.s(auto_attribs=True) +class Lambda(ScopeWithAttributes, ast.expr): + name: str = attr.ib(default="<lambda>", init=False) + args: ast.arguments = attr.ib(factory=ast.arguments) + + +@attr.s(auto_attribs=True) +class Comprehension(ScopeWithAttributes, ast.expr): + # XXX: shouldn't have `body` from Scope, + # but removing this will bring currently unneeded refactoring + generators: List[ast.comprehension] = attr.ib(kw_only=True) + _block_fields: Tuple[str, ...] = attr.ib(init=False, default=()) + + +@attr.s(auto_attribs=True) +class EltComprehension(Comprehension): + elt: ast.expr + + +@attr.s(auto_attribs=True) +class ListComp(EltComprehension): + name: str = attr.ib(init=False, default="<listcomp>") + + +@attr.s(auto_attribs=True) +class SetComp(EltComprehension): + name: str = attr.ib(init=False, default="<setcomp>") + + +@attr.s(auto_attribs=True) +class GeneratorExp(EltComprehension): + name: str = attr.ib(init=False, default="<genexpr>") + + +@attr.s(auto_attribs=True) +class DictComp(Comprehension): + key: ast.expr + value: ast.expr + name: str = attr.ib(init=False, default="<dictcomp>") + + +@attr.s(auto_attribs=True) +class MatchCase(BodyBlock): + pattern: ast.pattern + guard: Optional[ast.expr] + + +@attr.s(auto_attribs=True) +class Match(ACRWithAttributes, Block): + subject: ast.expr + cases: List[MatchCase] = attr.ib(init=False, factory=list) + _block_fields: Tuple[str, ...] = attr.ib(init=False, default=("cases",)) + + +@attr.s(auto_attribs=True) +class With(ACRWithAttributes, BodyBlock, Asyncable): + items: List[ast.withitem] + + +@attr.s(auto_attribs=True) +class BodyElseBlock(BodyBlock): + orelse: FlowContainer = attr.ib(factory=FlowContainer, init=False) + _block_fields: Tuple[str, ...] = attr.ib(init=False, default=("body", "orelse")) + + +@attr.s(auto_attribs=True) +class If(ACRWithAttributes, BodyElseBlock): + test: ast.expr + + +@attr.s(auto_attribs=True) +class ExceptHandler(ACRWithAttributes, BodyBlock): + type: Optional[ast.expr] + name: Optional[str] + + +@attr.s(auto_attribs=True) +class Try(ACRWithAttributes, BodyElseBlock): + handlers: List[ExceptHandler] = attr.ib(factory=list, init=False) + finalbody: FlowContainer = attr.ib(factory=FlowContainer, init=False) + _block_fields: Tuple[str, ...] = attr.ib( + init=False, default=("body", "handlers", "orelse", "finalbody") + ) + + +@attr.s(auto_attribs=True) +class Loop(ACRWithAttributes, BodyElseBlock): # XXX: do we need this class? + pass + + +@attr.s(auto_attribs=True) +class For(Loop, Asyncable): + target: ast.expr # ? Union[ast.Name, ast.Tuple, ast.List] + iter: ast.expr + + +@attr.s(auto_attribs=True) +class While(Loop): + test: ast.expr + + +# idea: +# class "list" +# def mark(index) -> id +# marked item's index will be tracked +# def get_index(id) -> index diff --git a/pynalyser/acr/translation.py b/pynalyser/acr/translation.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3f5606a1dc630c088d3a17845fb8897dfcac52 --- /dev/null +++ b/pynalyser/acr/translation.py @@ -0,0 +1,411 @@ +from typing import NoReturn, Union + +from .. import ast +from .classes import ( + Block, + Class, + DictComp, + ExceptHandler, + FlowContainer, + For, + Function, + GeneratorExp, + If, + Lambda, + ListComp, + Match, + MatchCase, + Module, + Scope, + SetComp, + Try, + While, + With, +) + +STMT_SCOPE = Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef] + + +# TODO: eliminate this class, it's still a kludge +class ForBlocks(ast.AST): + _fields = ("blocks",) + blocks: FlowContainer + + +# XXX: restrict visit, so if there's no visit_x then raise exception +class Translator(ast.NodeTransformer): + container: FlowContainer + + #### Transformations used only for expr scopes #### + + #### Blocks (all stmt) #### + + # XXX: we can shrink down ast.AST to smaller subset + def handle_block_without_appending(self, block: Block, node: ast.AST) -> None: + + self.generic_visit(block) # type: ignore + + self.handle_fields_of_block(block, node) + + def handle_fields_of_block(self, block: Block, node: ast.AST) -> None: + prev_container = self.container + + for name in block._block_fields: + value = getattr(node, name) + some_container = getattr(block, name) # FIXME: bad name! + if isinstance(some_container, FlowContainer): + self.container = some_container + self.generic_visit(ForBlocks(value[:])) + # self.generic_visit(value) would be cleaner if it worked + setattr(block, name, self.container) + elif isinstance(some_container, list): + # container should never be needed here + for sub_container in value: + func = getattr(self, "my_visit_" + type(sub_container).__name__) + some_container.append(func(sub_container)) + else: + raise TypeError( + "All `_block_fields` should be subclasses " + "of the `list` or `FlowContainer`" + ) + + self.container = prev_container + + def handle_block(self, block: Block, node: ast.AST) -> None: + self.container.append(block) + self.handle_block_without_appending(block, node) + + def visit_match_case(self, node: ast.match_case) -> ast.match_case: + self.handle_block(MatchCase(node.pattern, node.guard), node) # no attributes + return node + + def visit_Match(self, node: ast.Match) -> ast.Match: + self.handle_block( + Match(node.subject, lineno=node.lineno, col_offset=node.col_offset), node + ) + return node + + def visit_With(self, node: ast.With) -> ast.With: + self.handle_block( + With( + node.items, + is_async=False, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + return node + + def visit_AsyncWith(self, node: ast.AsyncWith) -> ast.AsyncWith: + self.handle_block( + With( + node.items, + is_async=True, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + return node + + def visit_If(self, node: ast.If) -> ast.If: + self.handle_block( + If(node.test, lineno=node.lineno, col_offset=node.col_offset), node + ) + return node + + def my_visit_ExceptHandler(self, node: ast.ExceptHandler) -> ExceptHandler: + # should only be called from handle_block_without_appending + acr_handler = ExceptHandler( + node.type, node.name, lineno=node.lineno, col_offset=node.col_offset + ) + self.handle_block_without_appending(acr_handler, node) + return acr_handler + + def visit_Try(self, node: ast.Try) -> ast.Try: + block = Try(lineno=node.lineno, col_offset=node.col_offset) + self.handle_block(block, node) + return node + + def visit_For(self, node: ast.For) -> ast.For: + self.handle_block( + For( + node.target, + node.iter, + is_async=False, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + return node + + def visit_AsyncFor(self, node: ast.AsyncFor) -> ast.AsyncFor: + self.handle_block( + For( + node.target, + node.iter, + is_async=True, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + return node + + def visit_While(self, node: ast.While) -> ast.While: + self.handle_block( + While(node.test, lineno=node.lineno, col_offset=node.col_offset), node + ) + return node + + #### expr scopes #### + + # XXX: we can shrink down node's ast.AST to smaller subset + def handle_scope(self, scope: Scope, node: ast.AST) -> Scope: + self.generic_visit(scope) # type: ignore + self.handle_fields_of_block(scope, node) + return scope + + def visit_Lambda(self, node: ast.Lambda) -> Scope: + lamb = Lambda(node.args, lineno=node.lineno, col_offset=node.col_offset) + node.body = [ast.Expr(node.body)] # type: ignore + return self.handle_scope(lamb, node) + + def visit_ListComp(self, node: ast.ListComp) -> Scope: + return self.handle_scope( + ListComp( + node.elt, + generators=node.generators, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + + def visit_SetComp(self, node: ast.SetComp) -> Scope: + return self.handle_scope( + SetComp( + node.elt, + generators=node.generators, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> Scope: + return self.handle_scope( + GeneratorExp( + node.elt, + generators=node.generators, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + + def visit_DictComp(self, node: ast.DictComp) -> Scope: + return self.handle_scope( + DictComp( + node.key, + node.value, + generators=node.generators, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + + #### stmt scopes #### + + def translate_from_module(self, module: ast.Module, name: str) -> Module: + acr = Module(name) + self.container = acr.body + self.generic_visit(module) + del self.container + return acr + + def visit_Module(self, node: ast.Module) -> NoReturn: + raise NotImplementedError( # XXX: parsing error idk + "Either you just called `visit` on the tree " + "(which starts with `ast.Module`) - use `translate_from_module` " + "or there's more than one `ast.Module` in the tree" + ) + + def handle_stmt_scope(self, scope: Scope, node: STMT_SCOPE) -> None: + self.container.add_code(self.handle_scope(scope, node)) + + def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef: + func = Function( + node.name, + node.args, + node.decorator_list, + is_async=False, + lineno=node.lineno, + col_offset=node.col_offset, + ) + self.handle_stmt_scope(func, node) + return node + + def visit_AsyncFunctionDef( + self, node: ast.AsyncFunctionDef + ) -> ast.AsyncFunctionDef: + + func = Function( + node.name, + node.args, + node.decorator_list, + is_async=True, + lineno=node.lineno, + col_offset=node.col_offset, + ) + self.handle_stmt_scope(func, node) + return node + + def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef: + self.handle_stmt_scope( + Class( + node.name, + node.bases, + node.keywords, + node.decorator_list, + lineno=node.lineno, + col_offset=node.col_offset, + ), + node, + ) + return node + + #### Other contlow flow #### + + def visit_Return(self, node: ast.Return) -> ast.Return: + self.generic_visit(node) + self.container.append(node) + return node + + def visit_Raise(self, node: ast.Raise) -> ast.Raise: + self.generic_visit(node) + self.container.append(node) + return node + + def visit_Assert(self, node: ast.Assert) -> ast.Assert: + self.generic_visit(node) + self.container.append(node) + return node + + def visit_Break(self, node: ast.Break) -> ast.Break: + self.generic_visit(node) + self.container.append(node) + return node + + def visit_Continue(self, node: ast.Continue) -> ast.Continue: + self.generic_visit(node) + self.container.append(node) + return node + + # TODO: handle yield + # def visit_Yield(self, node: ast.Yield) -> ast.Yield: + # self.generic_visit(node) + # self.container.append(node) + # return node + + # TODO: handle yield from + # def visit_YieldFrom(self, node: ast.YieldFrom) -> ast.YieldFrom: + # self.generic_visit(node) + # self.container.append(node) + # return node + + #### Leftover stmt-s #### + + def visit_Delete(self, node: ast.Delete) -> ast.Delete: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_Assign(self, node: ast.Assign) -> ast.Assign: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_AugAssign(self, node: ast.AugAssign) -> ast.AugAssign: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_Import(self, node: ast.Import) -> ast.Import: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_Global(self, node: ast.Global) -> ast.Global: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_Nonlocal(self, node: ast.Nonlocal) -> ast.Nonlocal: + self.generic_visit(node) + self.container.add_code(node) + return node + + def visit_Expr(self, node: ast.Expr) -> ast.Expr: + self.generic_visit(node) + self.container.add_code(node.value) # type: ignore + return node + + def visit_Pass(self, node: ast.Pass) -> ast.Pass: + self.generic_visit(node) + self.container.add_code(node) + return node + + #### Leftover expr-s #### + + # BoolOp + + def visit_NamedExpr(self, node: ast.NamedExpr) -> ast.NamedExpr: + self.generic_visit(node) + self.container.add_code(node) + return node + + # BinOp + # UnaryOp + + # IfExp + # Dict + # Set + + # Await + # Yield + # YieldFrom + + # Compare + # Call + # FormattedValue + # JoinedStr + # Constant + + # Attribute + # Subscript + # Starred + + # Name + + # List + # Tuple + + # Slice + + +def translate_ast_to_acr(tree: ast.Module, name: str) -> Module: + return Translator().translate_from_module(tree, name) diff --git a/pynalyser/acr/utils.py b/pynalyser/acr/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..173d3f14e65572450e515978c3b736dc06a6a0bd --- /dev/null +++ b/pynalyser/acr/utils.py @@ -0,0 +1,273 @@ +from collections import defaultdict +from typing import Any, Collection, List, NamedTuple, Optional, Tuple, TypeVar, Union + +from .. import ast +from .classes import ACR, Block, CodeBlock, FlowContainer, Module, Scope + +# Dumping + + +class Context(NamedTuple): + annotate_fields: bool + include_attributes: bool + indent: Optional[str] + + +def dump( + obj: Union[ACR, ast.AST], + annotate_fields: bool = True, + include_attributes: bool = False, + *, + indent: Optional[Union[str, int]] = None, +) -> str: + if not isinstance(obj, (ACR, ast.AST, list, dict)): + raise TypeError( # XXX: should we force it? + f"expected one of the AST / ACR / list / dict, " "got {type(obj).__name__}" + ) + if indent is not None and not isinstance(indent, str): + indent = " " * indent + return _format(obj, Context(annotate_fields, include_attributes, indent), lvl=0)[0] + + +def _format(obj: Any, ctx: Context, lvl: int) -> Tuple[str, bool]: + if ctx.indent is not None: + lvl += 1 + prefix = "\n" + ctx.indent * lvl + sep = ",\n" + ctx.indent * lvl + else: + prefix = "" + sep = ", " + + if isinstance(obj, list): + args = [] + allsimple = True + + for item in obj: + value, simple = _format(item, ctx, lvl) + allsimple = allsimple and simple + args.append(value) + + value, allsimple = _format_args_with_allsimple(prefix, sep, args, allsimple) + + value = f"[{value}]" + if type(obj) is not list: + value = f"{type(obj).__name__}({value})" + return value, allsimple + + if isinstance(obj, dict): + args = [] + allsimple = True + + for key, value in obj.items(): + # dict key should be "simple" + value, simple = _format(value, ctx, lvl) + allsimple = allsimple and simple + args.append(f"{key!r}: {value}") + + value, allsimple = _format_args_with_allsimple(prefix, sep, args, allsimple) + + value = f"{{{value}}}" + if isinstance(obj, defaultdict): + value = f"{type(obj).__name__}({obj.default_factory}, {value})" + elif type(obj) is not dict: + value = f"{type(obj).__name__}({value})" + + return value, allsimple + + if isinstance(obj, (ACR, ast.AST)): + value, allsimple = _format_args_with_allsimple( + prefix, sep, *_format_ast_or_acr(obj, ctx, lvl) + ) + return f"{type(obj).__name__}({value})", allsimple + + return repr(obj), True + + +def _format_args_with_allsimple( + prefix: str, sep: str, args: Collection[str], allsimple: bool +) -> Tuple[str, bool]: + if allsimple and len(args) <= 3: + return ", ".join(args), not args + return prefix + sep.join(args), False + + +def _format_attr(inst: Any, name: str, ctx: Context, lvl: int) -> Tuple[str, bool]: + return _format(getattr(inst, name, "<Is not an attribute of the object>"), ctx, lvl) + + +def _format_ast_or_acr( + obj: Union[ast.AST, ACR], ctx: Context, lvl: int +) -> Tuple[List[str], bool]: + args = [] + allsimple = True + + for name in obj._fields: + value, simple = _format_attr(obj, name, ctx, lvl) + allsimple = allsimple and simple + if ctx.annotate_fields: + args.append(f"{name}={value}") + else: + args.append(value) + + if ctx.include_attributes and obj._attributes: + for name in obj._attributes: + value, simple = _format_attr(obj, name, ctx, lvl) + allsimple = allsimple and simple + args.append(f"{name}={value}") + + return args, allsimple + + +# Tree traversing + +# Module, Class, Function, Lambda, ListComp, SetComp, GeneratorExp, DictComp +# MatchCase, Match, With, If, ExceptHandler, Try, For, While + +NODE = Union[ACR, ast.AST] + + +class NodeVisitor: + _ast_visitor = ast.NodeVisitor + + scope: Scope + block: Block + + strict: bool = False + auto_generic_visit: bool = True + + def start(self, init_scope_block: Scope) -> Any: + self.scope = self.block = init_scope_block + result = self.visit(init_scope_block) + + del self.scope, self.block + return result + + def acr_generic_visit(self, node: NODE) -> Any: + # handle acr + if isinstance(node, Scope): + previous_scope = self.scope + self.scope = node + + previous_block = self.block + self.block = node + + try: + return self.generic_visit(node) + finally: + self.scope = previous_scope + self.block = previous_block + + if isinstance(node, Block): + previous_block = self.block + self.block = node + + try: + return self.generic_visit(node) + finally: + self.block = previous_block + + return self.generic_visit(node) + + # XXX: this maybe will make things better, idk + # def acr_generic_visit(self, node: NODE) -> Any: + # # handle acr + # if isinstance(node, Scope): + # return self.visit_scope(node) + + # if isinstance(node, Block): + # return self.visit_block(node) + + # return self.generic_visit(node) + + # def visit_scope(self, node: Scope) -> Any: + # previous_scope = self.scope + # self.scope = node + + # try: + # return self.visit_block(node) + # finally: + # self.scope = previous_scope + + # def visit_block(self, node: Block) -> Any: + # previous_block = self.block + # self.block = node + + # try: + # return self.generic_visit(node) + # finally: + # self.block = previous_block + + def visit(self, node: NODE) -> Any: + method = "visit_" + type(node).__name__ + visitor = getattr(self, method, None) + + if visitor is None: + if self.strict: + raise ValueError( + f"There are no '{method}' method. " + "You see this message because you're in strict mode. " + f"See {type(self).__name__}.strict" + ) + + result = self.acr_generic_visit(node) + else: + result = visitor(node) + if self.auto_generic_visit: + self.acr_generic_visit(node) + + return result + + def generic_visit(self, node: NODE) -> Any: + if isinstance(node, ast.AST): + return self._ast_visitor.generic_visit(self, node) # type: ignore + + if isinstance(node, Block): + for name in node._block_fields: + self.visit(getattr(node, name)) + return node + + if isinstance(node, FlowContainer): + for item in node: + self.visit(item) + return node + + if isinstance(node, CodeBlock): + for code in node: + self.visit(code) + return node + + raise RuntimeError(f"Expected ACR or AST, but got {type(node).__name__}") + + +class ACRCodeTransformer(NodeVisitor): + """Allows to change contents of the code (of the CodeBlock)""" + + _ast_visitor = ast.NodeTransformer + + def generic_visit(self, node: NODE) -> Any: + if isinstance(node, ast.AST): + return self._ast_visitor.generic_visit(self, node) # type: ignore + + if isinstance(node, Block): + for name in node._block_fields: + self.visit(getattr(node, name)) + return node + + if isinstance(node, FlowContainer): + for i, item in enumerate(node): + node[i] = self.visit(item) + return node + + if isinstance(node, CodeBlock): + new_code_block: CodeBlock = CodeBlock() + for code in node: + value = self.visit(code) + if value is None: + pass + elif isinstance(value, (ast.AST, ACR)): + new_code_block.append(value) # type: ignore + else: + new_code_block.extend(value) + return new_code_block + + raise RuntimeError(f"Expected ACR or AST, but got {type(node).__name__}") diff --git a/pynalyser/analysers/__init__.py b/pynalyser/analysers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b88b76f4185ba8954a8880d95a701359eed470d0 --- /dev/null +++ b/pynalyser/analysers/__init__.py @@ -0,0 +1,4 @@ +from .definitions import DefinitionAnalyser, SymTabAnalyser +from .scope import ScopeAnalyser +from .tools import Analyser, AnalysisContext, collect_names +from .type_inference import TypeInference diff --git a/pynalyser/analysers/definitions.py b/pynalyser/analysers/definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..77af6c23e40f5cb34b499d30a918d49858c3b079 --- /dev/null +++ b/pynalyser/analysers/definitions.py @@ -0,0 +1,163 @@ +import sys +from typing import Any, List, Optional, Union + +from .. import acr, ast +from ..symbol import ScopeType +from ..types import Arg, Arguments, FunctionType, SymbolTableType +from .tools import Analyser, AnalysisContext, collect_names + + +class SymTabAnalyser(Analyser): + symtab: SymbolTableType + + def analyse(self, ctx: AnalysisContext) -> None: + type_name = SymTabAnalyser.__name__ + if type_name in ctx.results: + # TODO: use custom exception + raise Exception( + f"Key '{type_name}' is already in use" + " for other AnalysisContext.results" + ) + + self.symtab = ctx.results[type_name] = SymbolTableType(name="WholeAnalysis") + super().analyse(ctx) + + def visit(self, node: acr.NODE) -> Any: + if isinstance(node, acr.Scope): + prev = self.symtab + # this symbol is used in self.scope + progress the definition + self.symtab[node.name].next_def() + try: + return super().visit(node) + finally: + self.symtab = prev + return super().visit(node) + + def handle_arg(self, name: str) -> Arg: + symbol = self.symtab[name] + symbol.next_def() + symbol.is_arg = True + + if not symbol.change_scope(ScopeType.LOCAL, fail=False): + raise SyntaxError(f"duplicate argument '{name}' in function definition") + + return Arg(name, symbol.current_symbol) + + def handle_function(self, scope: Union[acr.Lambda, acr.Function]) -> None: + args = Arguments() + symbol = self.symtab[scope.name] + symbol.type = self.symtab = FunctionType(args) + symbol.change_scope(ScopeType.LOCAL) + symbol.holds_symbol_table = True + + if sys.version_info >= (3, 8): + for arg in scope.args.posonlyargs: + args.posargs.append(self.handle_arg(arg.arg)) + + for arg in scope.args.args: + args.args.append(self.handle_arg(arg.arg)) + + for arg in scope.args.kwonlyargs: + args.kwargs.append(self.handle_arg(arg.arg)) + + if scope.args.vararg is not None: + args.stararg = self.handle_arg(scope.args.vararg.arg) + + if scope.args.kwarg is not None: + args.twostararg = self.handle_arg(scope.args.kwarg.arg) + + def handle_scope(self, node: acr.Scope) -> None: + self.symtab[node.name].type = self.symtab = SymbolTableType( + name=type(node).__name__ + ) + + def visit_ListComp(self, node: acr.ListComp) -> None: + self.handle_scope(node) + + def visit_SetComp(self, node: acr.SetComp) -> None: + self.handle_scope(node) + + def visit_GeneratorExp(self, node: acr.GeneratorExp) -> None: + self.handle_scope(node) + + def visit_DictComp(self, node: acr.DictComp) -> None: + self.handle_scope(node) + + def visit_Lambda(self, node: acr.Lambda) -> None: + self.handle_function(node) + + def visit_Function(self, node: acr.Function) -> None: + self.handle_function(node) + + def visit_Class(self, node: acr.Class) -> None: + self.handle_scope(node) + + def visit_Module(self, node: acr.Module) -> None: + self.handle_scope(node) + + +def progress_symbol_defs(symtab: SymbolTableType, node: acr.NODE) -> None: + names: List[str] = [] + only_on_undef = False + + if isinstance(node, (acr.For, ast.AugAssign, ast.AnnAssign, ast.NamedExpr)): + names.extend(collect_names(node.target)) + elif isinstance(node, ast.Assign): + for sub_node in node.targets: + names.extend(collect_names(sub_node)) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + names.extend(alias.asname or alias.name for alias in node.names) + elif isinstance(node, (ast.Global, ast.Nonlocal)): + names.extend(node.names) + only_on_undef = True + elif isinstance(node, ast.Name): + names.append(node.id) + only_on_undef = True + # Delete, With, Match + # Try cleans up after "except e as x" + + for name in names: + symbol = symtab[name] + if only_on_undef and symbol.is_currently_defined: + continue + symbol.next_def() + + +class DefinitionAnalyser(Analyser): + symtab: SymbolTableType + record_defs: bool = False + + def __init__(self, record_defs: Optional[bool] = None) -> None: + if record_defs is not None: + self.record_defs = record_defs + + def analyse(self, ctx: AnalysisContext) -> None: + type_name = SymTabAnalyser.__name__ + if type_name not in ctx.results: + # XXX: use custom exception? + raise KeyError(f"Key '{type_name}' is required by {type(self).__name__}") + + self.symtab = ctx.results[type_name] + self.symtab.reset() + super().analyse(ctx) + + def visit(self, node: acr.NODE) -> Any: + if isinstance(node, acr.Scope): + symbol = self.symtab[node.name] + symbol.next_def() + + symtab = symbol.type + assert isinstance(symtab, SymbolTableType) + + symtab.reset() + + prev = self.symtab + self.symtab = symtab + + try: + return super().visit(node) + finally: + self.symtab = prev + + progress_symbol_defs(self.symtab, node) + return super().visit(node) diff --git a/pynalyser/analysers/pipeline.py b/pynalyser/analysers/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..804e62a1563dc8c35b372d2973d8446f0d9148e5 --- /dev/null +++ b/pynalyser/analysers/pipeline.py @@ -0,0 +1,67 @@ +from typing import Callable, List, Type + +from .definitions import DefinitionAnalyser, SymTabAnalyser +from .scope import ScopeAnalyser +from .tools import Analyser, AnalysisContext +from .type_inference import TypeInference + + +PIPELINE = List[Analyser] +PIPE_FACTORY = Callable[[], PIPELINE] + + +def default_pipe() -> PIPELINE: + """ + The default pipeline factory. Creates the default pipeline. + """ + + assert issubclass(ScopeAnalyser, DefinitionAnalyser), ( + "add DefinitionAnalyser before ScopeAnalyser," + " otherwise it will not work by it's own" + ) + + return [ + SymTabAnalyser(), + ScopeAnalyser(record_defs=True), + TypeInference(), + ] + + +def insert_in_pipeline( + pipeline: PIPELINE, to_be_inserted: Analyser, mode: str, relative_to: Type[Analyser] +): + """ + Create a copy of the pipeline with a new analyzer inserted into + the pipeline after or before an instance of the given class. + + `pipeline = insert_into_pipeline(` + ` pipeline, MyAnalyser(), "after", AnalyserInThePipeline)` + + `mode` can be `'before'` or `'after'` + """ + + if mode not in ("before", "after"): + raise ValueError("insert_in_pipeline() mode must be 'before' or 'after'") + + i = 0 + for i, analyser in enumerate(pipeline): + if isinstance(analyser, relative_to): + break + + if mode == "after": + i += 1 + + return pipeline[:i] + [to_be_inserted] + pipeline[i:] + + +def run_pipeline(ctx: AnalysisContext, factory: PIPE_FACTORY) -> AnalysisContext: + """ + Run each factory analyser on modules in the given context. + The first module is the one with what analysis starts. + (TODO: check that it's still true) It is an entrypoint. + """ + + for analyser in factory(): + analyser.analyse(ctx) + + return ctx diff --git a/pynalyser/analysers/scope.py b/pynalyser/analysers/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..835424f62247c5d082a9b298b02f398f5694154a --- /dev/null +++ b/pynalyser/analysers/scope.py @@ -0,0 +1,80 @@ +from typing import List +from .. import acr, ast +from ..symbol import ScopeType +from .definitions import DefinitionAnalyser +from .tools import collect_names + + +class ScopeAnalyser(DefinitionAnalyser): + def setup_symbols_by_assign(self, *targets: ast.AST) -> None: + names = [] + for sub_node in targets: + names.extend(collect_names(sub_node)) + + for name in names: + symbol_data = self.symtab[name] + + # in the other case it's already defined + symbol_data.change_scope(ScopeType.LOCAL) + symbol_data.imported = False + + def visit_For(self, node: acr.For) -> None: + self.setup_symbols_by_assign(node.target) + + def visit_Assign(self, node: ast.Assign) -> None: + self.setup_symbols_by_assign(*node.targets) + + def visit_AugAssign(self, node: ast.AugAssign) -> None: + pass + + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: + # XXX: should be only one name in the end: + self.setup_symbols_by_assign(node.target) + + def setup_symbols_by_import(self, targets: List[ast.alias]) -> None: + for alias in targets: + name = alias.asname or alias.name # those are never == "" + symbol_data = self.symtab[name] + symbol_data.imported = True + + def visit_Import(self, node: ast.Import) -> None: + self.setup_symbols_by_import(node.names) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + self.setup_symbols_by_import(node.names) + + def visit_Global(self, node: ast.Global) -> None: + for name in node.names: + symbol_data = self.symtab[name] + # generally imports before global should not be allowed, + # but cpython allows it https://tiny.one/global-in-docs + symbol_data.change_scope(ScopeType.GLOBAL) + + def visit_Nonlocal(self, node: ast.Nonlocal) -> None: + for name in node.names: + symbol_data = self.symtab[name] + # generally imports before nonlocal should not be allowed, + # but cpython allows it https://tiny.one/nonlocal-in-docs + symbol_data.change_scope(ScopeType.NONLOCAL) + + def visit_NamedExpr(self, node: ast.NamedExpr) -> None: + names = collect_names(node.target) + assert len(names) == 1 + name, = names + + symbol = self.symtab[name] + if isinstance(self.scope, acr.Comprehension): + # in the other case it's already defined + if not symbol.change_scope(ScopeType.NONLOCAL, fail=False): + raise NotImplementedError( + "NamedExpr should make symbol local for enclosing scope" + ) + else: + # in the other case it's already defined + symbol.change_scope(ScopeType.LOCAL) + + symbol.imported = False + + def visit_Name(self, node: ast.Name) -> None: + # this name have been used in this scope + self.symtab[node.id] diff --git a/pynalyser/analysers/tools.py b/pynalyser/analysers/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b3401b03563e8a621bce4b28fdc8575c19ee06 --- /dev/null +++ b/pynalyser/analysers/tools.py @@ -0,0 +1,56 @@ +from typing import Any, Dict, List, Tuple + +import attr + +from .. import acr, ast + + +@attr.s(auto_attribs=True) +class AnalysisContext: + modules: List[acr.Module] + results: Dict[str, Any] = attr.ib(init=False, factory=dict) + + def unpack(self) -> Tuple[List[acr.Module], Dict[str, Any]]: + return self.modules, self.results + + +class Analyser(acr.NodeVisitor): + context: AnalysisContext + + def analyse(self, ctx: AnalysisContext) -> None: + self.context = ctx + self.start(ctx.modules[0]) + + +class NameCollector(acr.NodeVisitor): + # accounted for: + # Attribute - don't visit fields, XXX: for now + # Subscript - don't visit fields + # Starred - just visit itself + # Name - add name, if we got here + # List - just visit itself + # Tuple - just visit itself + # other nodes AFAIK will not appear here + + _collected_names: List[str] = [] + + def collect_names(self, node: ast.AST) -> List[str]: + self._collected_names.clear() + self.visit(node) + return self._collected_names + + def visit_Attribute(self, node: ast.Attribute) -> None: + pass + + def visit_Subscript(self, node: ast.Subscript) -> None: + pass + + def visit_Name(self, node: ast.Name) -> None: + self._collected_names.append(node.id) + + +__name_collector = NameCollector() + + +def collect_names(node: ast.AST) -> List[str]: + return __name_collector.collect_names(node) diff --git a/pynalyser/analysers/type_inference.py b/pynalyser/analysers/type_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..d44e25a35210883177c2952e5ab72cf788912eb0 --- /dev/null +++ b/pynalyser/analysers/type_inference.py @@ -0,0 +1,166 @@ +from typing import Dict, Union + +from .. import acr, ast +from ..types import ( + AnyType, + BinOpType, + CallType, + CompareOpType, + IntType, + ItemType, + ListType, + PynalyserType, + DataType, + SliceType, + SubscriptType, + SymbolType, + TupleType, + UnionType, + UnknownType, +) +from .definitions import DefinitionAnalyser + +BINOP: Dict[type, str] = { + ast.Add: "add", + ast.Sub: "sub", + ast.MatMult: "matmul", + ast.Mult: "mul", + ast.Div: "truediv", + ast.Mod: "mod", + ast.LShift: "lshift", + ast.RShift: "rshift", + ast.BitOr: "or", + ast.BitXor: "xor", + ast.BitAnd: "and", + ast.FloorDiv: "floordiv", + ast.Pow: "pow", +} + + +CMPOP: Dict[type, str] = { + ast.Eq: "eq", + ast.NotEq: "ne", + ast.Lt: "lt", + ast.LtE: "le", + ast.Gt: "gt", + ast.GtE: "ge", + ast.Is: "is", + ast.IsNot: "is_not", + ast.In: "contains", + ast.NotIn: "contains_not", +} + + +UNOP: Dict[type, str] = { + ast.Invert: "invert", + ast.Not: "not", + ast.UAdd: "pos", + ast.USub: "neg", +} + + +class TypeInference(DefinitionAnalyser): + auto_generic_visit: bool = False + + # Inferable expressions + + def visit_Call(self, node: ast.Call) -> PynalyserType: + return CallType( + self.visit(node.func), + tuple(self.visit(item) for item in node.args), + tuple((item.arg, self.visit(item.value)) for item in node.keywords), + ) + + # def visit_Attribute(self, node: ast.Attribute) -> PynalyserType: + # return AnyType + + def visit_Subscript(self, node: ast.Subscript) -> PynalyserType: + return SubscriptType(self.visit(node.value), self.visit(node.slice)) + + def visit_BinOp(self, node: ast.BinOp) -> PynalyserType: + return BinOpType( + self.visit(node.left), BINOP[type(node.op)], self.visit(node.right) + ) + + def visit_Compare(self, node: ast.Compare) -> PynalyserType: + return CompareOpType( + self.visit(node.left), + [CMPOP[type(op)] for op in node.ops], + [self.visit(item) for item in node.comparators], + ) + + ### Comprehentions ### + + def visit_ListComp(self, node: acr.ListComp) -> PynalyserType: + return ListType(item_type=UnknownType) # TODO: infer item type + + ### Builtin sequences ### + + def visit_List(self, node: ast.List) -> PynalyserType: + return ListType(item_type=UnionType(*map(self.visit, node.elts))) + + def visit_Tuple(self, node: ast.Tuple) -> PynalyserType: + return TupleType(item_type=UnionType(*map(self.visit, node.elts))) + + ### Basic "building blocks" ### + + def visit_Slice(self, node: ast.Slice) -> PynalyserType: + return SliceType() + + def visit_Constant(self, node: ast.Constant) -> PynalyserType: + if isinstance(node.value, int): + return IntType() + return DataType(name=type(node.value).__name__, is_builtin=True) + + def visit_Name(self, node: ast.Name) -> PynalyserType: + return SymbolType(node.id, self.symtab[node.id].current_symbol) + + def infer_acr_expr(self, node: Union[ast.AST, acr.ACR]) -> PynalyserType: + res = self.visit(node) + if isinstance(res, PynalyserType): + return res + return AnyType + + def infer_assignment(self, node: ast.AST, tp: PynalyserType) -> None: + if isinstance(node, ast.Name): + symbol_data = self.symtab[node.id] + if symbol_data.type is UnknownType: + symbol_data.type = tp + else: + symbol_data.type = UnionType(symbol_data.type, tp) + # XXX: ideally we have to create + # new variables-clones for type changes + # anyways it's not handled here + # raise TypeError("symbol's type is already set to {}") + + # in case of list or tuple we can infer number of elements + # elif isinstance(node, ast.Name): + + ### Statements ### + + def visit_Assign(self, node: ast.Assign) -> None: + # XXX: can double storing be abused? 'a = a = []' + tp = self.infer_acr_expr(node.value) + for target in node.targets: + self.infer_assignment(target, tp) + + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: + if node.value is not None: + tp = self.infer_acr_expr(node.value) + self.infer_assignment(node.target, tp) + + def visit_For(self, node: acr.For) -> None: + tp = self.infer_acr_expr(node.iter) + self.infer_assignment(node.target, ItemType(tp)) + self.acr_generic_visit(node) + + def visit_While(self, node: acr.While) -> None: + tp = self.infer_acr_expr(node.test) + self.acr_generic_visit(node) + # can be boolable + # if bool(test) is always True / False, + # then we have infinite loop or + # we can skip loop + + # def visit_Function(self, node: acr.Function) -> None: + # self.scope.symbol_table[node.name] diff --git a/pynalyser/ast/__init__.py b/pynalyser/ast/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91989e1f49fec9b4a02998016c717da13f374d47 --- /dev/null +++ b/pynalyser/ast/__init__.py @@ -0,0 +1,2 @@ +from .portable_ast import * +from .normalize_ast import * diff --git a/pynalyser/ast/normalize_ast.py b/pynalyser/ast/normalize_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..642e8d29e8546be17b3fddebe3af1df78ccb039d --- /dev/null +++ b/pynalyser/ast/normalize_ast.py @@ -0,0 +1,75 @@ +from typing import Dict, Optional, cast +from . import portable_ast as ast + +__all__ = [ + "AstNormalizer", + "normalize_ast", + "normalize_ast_module", +] + + +ATTRIBUTES = ("lineno", "col_offset") +OPTIONAL_ATTRIBUTES = ("end_lineno", "end_col_offset") + + +class AstNormalizer(ast.NodeTransformer): + # we need to set all of the locations, + # that's why ast.copy_location is not used + def get_locations(self, node: ast.AST) -> Dict[str, Optional[int]]: + result: Dict[str, Optional[int]] = {} + + for attr in ATTRIBUTES: + value = getattr(node, attr) + assert isinstance(value, int) + result[attr] = value + + for attr in OPTIONAL_ATTRIBUTES: + value = getattr(node, attr, None) + assert isinstance(value, int) or value is None + result[attr] = value + + return result + + def visit_Num(self, node: ast.Num) -> ast.Constant: + return self.visit(ast.Constant(node.n, kind=None, **self.get_locations(node))) + + def visit_Str(self, node: ast.Str) -> ast.Constant: + # kind=None since this information is not present in the ast.Str + return self.visit(ast.Constant(node.s, kind=None, **self.get_locations(node))) + + def visit_Bytes(self, node: ast.Bytes) -> ast.Constant: + return self.visit(ast.Constant(node.s, kind=None, **self.get_locations(node))) + + def visit_NameConstant(self, node: ast.NameConstant) -> ast.Constant: + return self.visit( + ast.Constant(node.value, kind=None, **self.get_locations(node)) + ) + + def visit_Ellipsis(self, node: ast.Ellipsis) -> ast.Constant: + return self.visit(ast.Constant(..., kind=None, **self.get_locations(node))) + + def visit_Index(self, node: ast.Index) -> ast.AST: + value = node.value # type: ignore [name-defined] + return self.visit(value) + + def visit_ExtSlice(self, node: ast.ExtSlice) -> ast.Tuple: + dims = node.dims # type: ignore [name-defined] + return self.visit(ast.Tuple(dims, ast.Load())) + # **self.get_locations(first node with locations from dims) + + # We are just getting rid of deprecated nodes, + # so we don't need a warning (see: NodeTransformer.visit_Constant) + # Same as NodeTransformer.visit(node) with visit_Constant removed + def visit_Constant(self, node: ast.Constant) -> ast.Constant: + node.kind = getattr(node, "kind", None) + return cast(ast.Constant, self.generic_visit(node)) + + +def normalize_ast(tree: ast.AST) -> ast.AST: + return ast.fix_missing_locations(AstNormalizer().visit(tree)) + + +def normalize_ast_module(module: ast.Module) -> ast.Module: + tree = normalize_ast(module) + assert isinstance(tree, ast.Module) + return tree diff --git a/pynalyser/ast/portable_ast.py b/pynalyser/ast/portable_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..336b7d36c73819a5bbbe6734670d7b8818a72854 --- /dev/null +++ b/pynalyser/ast/portable_ast.py @@ -0,0 +1,44 @@ +import sys +import typing +from ast import * + +# backports +if sys.version_info < (3, 10): + + class pattern(AST): + ... + + class match_case(AST): + pattern: pattern + guard: typing.Optional[expr] + body: typing.List[stmt] + _fields = ("pattern", "guard", "body") + + class Match(stmt): + subject: expr + cases: typing.List[match_case] + _fields = ("subject", "cases") + + +if sys.version_info < (3, 8): + + class NamedExpr(expr): + target: expr + value: Expr + _fields = ("target", "value") + + +# TODO: Create dummy classes for ast.Num, ast.Str, ast.Bytes, +# ast.NameConstant, ast.Ellipsis, ast.Index and ast.ExtSlice +# for the version where they will be removed +# and add them to ast +# (For the purposes of correct type checking and +# maintaining consistent content of the module ast) + +# TODO: build python parser from for the newest version of cpython +# and ship it in a separate package to be python version independent +# or use other python parsers + +# clean up the namespace +# this module is supposed to be imported via the star +del sys, typing diff --git a/pynalyser/inherit_dicts.py b/pynalyser/inherit_dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..2dbfa9137851edbb15a9c48acb5d59423deee7a9 --- /dev/null +++ b/pynalyser/inherit_dicts.py @@ -0,0 +1,34 @@ +from typing import Any, Dict, Mapping, Set, Tuple, cast + + +DICTS = "_dicts_to_inherit" + + +class DictNotFoundError(AttributeError): + message_template = ( + "attribute '{attribute}' was not found in the '{name}' or it's parent," + f" but is included in the '{DICTS}'" + ) + + def __init__(self, attribute: str, name: str) -> None: + super().__init__(self.message_template.format(attribute=attribute, name=name)) + + +class MetaInheritDicts(type): + def __new__(cls, name: str, bases: Tuple[type, ...], body: Dict[str, Any]): + base = cast(Mapping[str, Any], bases[0].__dict__ if bases else {}) + attributes = body[DICTS] = body.get(DICTS, base.get(DICTS, set())) + + for attribute in attributes: + base_value = base.get(attribute, None) + value = body.get(attribute, None) + + if base_value is None and value is None: + raise DictNotFoundError(attribute, name) + body[attribute] = {**(base_value or {}), **(value or {})} + + return super().__new__(cls, name, bases, body) + + +class InheritDicts(metaclass=MetaInheritDicts): + _dicts_to_inherit: Set[str] = set() diff --git a/pynalyser/main.py b/pynalyser/main.py new file mode 100644 index 0000000000000000000000000000000000000000..8cad014f8aa7a492b2fb9d7e90bdf0adf03a4e5e --- /dev/null +++ b/pynalyser/main.py @@ -0,0 +1,36 @@ +import os +from typing import Iterable, List + +from . import ast +from .acr import Module, translate_ast_to_acr +from .analysers.pipeline import PIPE_FACTORY, default_pipe, run_pipeline +from .analysers.tools import AnalysisContext + + +def parse_file(path: str) -> Module: + with open(path, mode="r", encoding="utf-8") as file: + return parse_string( + file.read(), os.path.splitext(os.path.basename(file.name))[0] + ) + + +def parse_string(string: str, filename: str = "<unknown>") -> Module: + return parse_ast(ast.parse(string), filename) + + +def parse_ast(module: ast.Module, filename: str = "<unknown>") -> Module: + return translate_ast_to_acr(ast.normalize_ast_module(module), filename) + + +def analyse_files( + paths: Iterable[str], factory: PIPE_FACTORY = default_pipe +) -> AnalysisContext: + + return analyse_modules([parse_file(p) for p in paths], factory) + + +def analyse_modules( + modules: List[Module], factory: PIPE_FACTORY = default_pipe +) -> AnalysisContext: + + return run_pipeline(AnalysisContext(modules), factory) diff --git a/pynalyser/reports.py b/pynalyser/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f0089c3d5921107ca066d8401fff42743baf73 --- /dev/null +++ b/pynalyser/reports.py @@ -0,0 +1,3 @@ +# None since report() doesn't have to raise an exception +def report(exc: Exception) -> None: + raise exc diff --git a/pynalyser/symbol.py b/pynalyser/symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..b73663ab87ce39e485d3a342d8cee8cfb309b135 --- /dev/null +++ b/pynalyser/symbol.py @@ -0,0 +1,107 @@ +from enum import Flag, auto +from typing import Any, List + +import attr + +from .types import PynalyserType, UnknownType + + +# XXX: maybe ScopeKind? +class ScopeType(Flag): + GLOBAL = auto() # used with global keyword in this scope + NONLOCAL = auto() # used with nonlocal keyword in this scope + LOCAL = auto() # has an assertion in this scope + # GLOBAL | NONLOCAL - not LOCAL + # NONLOCAL | LOCAL - can it happen? + # GLOBAL | LOCAL - can it happen? + UNKNOWN = GLOBAL | NONLOCAL | LOCAL + + +# TODO: rename to Symbol and look at variables that use this class +@attr.s(auto_attribs=True) +class Symbol: + # it seems like symbol's scope doesn't change + # throughout the scope execution + scope: ScopeType = ScopeType.UNKNOWN + + imported: bool = False # TODO: handle this in acr translation + is_arg: bool = False + holds_symbol_table: bool = False + + type: PynalyserType = UnknownType + + # if we change from UNKNOWN to more specific it's fine + # but if we change from specific to other specific than + # probably something went wrong + # is it the responsibility of this class to check this? + def change_scope(self, new_scope: ScopeType, fail: bool = True) -> bool: + # TODO: enable more options: + # from unspecific to specific + # GLOBAL | NONLOCAL, NONLOCAL | LOCAL, GLOBAL | LOCAL + # is ok to go to + # GLOBAL or NONLOCAL, NONLOCAL or LOCAL, GLOBAL or LOCAL + if self.scope is ScopeType.UNKNOWN: + self.scope = new_scope + return True + elif self.scope == new_scope: + return True + else: + if not fail: + return False + + # TODO: change to custom class + raise ValueError(f"changing the `scope` from {self.scope} to {new_scope}") + + +UNDEF = -1 + + +class MultiDefSymbol: + _symbols: List[Symbol] + _i: int + + def __init__(self) -> None: + self._symbols = [] + self.reset() + + @property + def current_symbol(self) -> Symbol: + if not self.is_currently_defined: + raise Exception("You need to first do next_def on MultiDefSymbol") + return self._symbols[self._i] + + def next_def(self) -> None: + self._i += 1 + if len(self._symbols) == self._i: + self._symbols.append(Symbol()) + + def reset(self): + self._i = UNDEF + + @property + def is_currently_defined(self) -> bool: + return self._i != UNDEF + + scope: ScopeType + + imported: bool + is_arg: bool + holds_symbol_table: bool + + type: PynalyserType + + def change_scope(self, new_scope: ScopeType, fail: bool = True) -> bool: + return self.current_symbol.change_scope(new_scope, fail) + + _names = "scope", "imported", "is_arg", "holds_symbol_table", "type" + + def __getattr__(self, name: str) -> Any: + # return getattr(self.current_symbol, name) + if name in self._names: + return getattr(self.current_symbol, name) + super().__getattribute__(name) # no return + + def __setattr__(self, name: str, value: Any) -> None: + if name in self._names: + return setattr(self.current_symbol, name, value) + super().__setattr__(name, value) diff --git a/pynalyser/types/__init__.py b/pynalyser/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb2c76de8d341481cec65b6c966302cf8616c4e8 --- /dev/null +++ b/pynalyser/types/__init__.py @@ -0,0 +1,5 @@ +from .base_types import * +from .op import * +from .reference_types import * +from .structure_types import * +from .symbol_table_types import * diff --git a/pynalyser/types/base_types.py b/pynalyser/types/base_types.py new file mode 100644 index 0000000000000000000000000000000000000000..87c853facdb0c5cb77064b4fcbde0bd149970b18 --- /dev/null +++ b/pynalyser/types/base_types.py @@ -0,0 +1,205 @@ +from typing import Any, Callable, List, Optional, Set, Tuple, Union + +import attr +from typing_extensions import Literal + +from .inheritance import Inheritable +from .op import OpCarrier + + +# @attr.s(auto_attribs=True) +class PynalyserType: + @property + def as_str(self) -> str: + raise NotImplementedError( + f"'as_str' is not implemented in {type(self).__name__}" + ) + + def deref(self, report: bool) -> "DataType": + raise NotImplementedError( + f"'deref' is not implemented in {type(self).__name__}" + ) + + +@attr.s(auto_attribs=True, hash=True, init=False) +class UnionType(PynalyserType): + types: Tuple[PynalyserType, ...] + + def __init__(self, *types: PynalyserType): + # for fancy formatting + # types = tuple(sorted(types, key=lambda x: str(x))) + self.__attrs_init__(types) # type: ignore[attr-defined] + + @property + def as_str(self) -> str: + return f"Union[{', '.join(tp.as_str for tp in self.types)}]" + + def deref(self, report: bool) -> "DataType": + types: Set[DataType] = {type.deref(report) for type in self.types} + + if len(types) == 0: + return UnknownType + if len(types) == 1: + return types.pop() + + # TODO: use mro to calculate common ancestor + return UnknownType + + +NotImplementedLiteral = Literal[NotImplemented] # type: ignore +Return = Union["DataType", NotImplementedLiteral] + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class DataType(PynalyserType, OpCarrier, Inheritable): + name: str = attr.ib(kw_only=True) + is_builtin: bool = attr.ib(kw_only=True) + # XXX: why do we need is_completed? + is_completed: bool = attr.ib(default=False, kw_only=True) + + def deref(self, report: bool) -> "DataType": + return self + + @property + def as_str(self) -> str: + return self.name + + # Methods below are not participating in the actual analysis (OpCarrier.ops does) + # Those are just for fancy user interface + + def _run_op(self, op: str, *args, **kwargs) -> Return: + from .structure_types import NotImplementedType + + value = self._get_op_func(op)(self, *args, **kwargs) + + if value is NotImplementedType: + return NotImplemented + + return value + + # Comparisons + def __lt__(self, value: PynalyserType) -> Return: + return self._run_op("__lt__", value) + + def __le__(self, value: PynalyserType) -> Return: + return self._run_op("__le__", value) + + def __eq__(self, value: PynalyserType) -> Return: # type: ignore[override] + return self._run_op("__eq__", value) + + def __ne__(self, value: PynalyserType) -> Return: # type: ignore[override] + return self._run_op("__ne__", value) + + def __gt__(self, value: PynalyserType) -> Return: + return self._run_op("__gt__", value) + + def __ge__(self, value: PynalyserType) -> Return: + return self._run_op("__ge__", value) + + # Binary operation + def __add__(self, value: PynalyserType) -> Return: + return self._run_op("__add__", value) + + def __sub__(self, value: PynalyserType) -> Return: + return self._run_op("__sub__", value) + + def __mul__(self, value: PynalyserType) -> Return: + return self._run_op("__mul__", value) + + def __matmul__(self, value: PynalyserType) -> Return: + return self._run_op("__matmul__", value) + + def __truediv__(self, value: PynalyserType) -> Return: + return self._run_op("__truediv__", value) + + def __floordiv__(self, value: PynalyserType) -> Return: + return self._run_op("__floordiv__", value) + + def __mod__(self, value: PynalyserType) -> Return: + return self._run_op("__mod__", value) + + def __divmod__(self, value: PynalyserType) -> Return: + return self._run_op("__divmod__", value) + + # XXX: 'Optional' is a hack, it probably should be handled differently + def __pow__( + self, value: PynalyserType, mod: Optional[PynalyserType] = None + ) -> Return: + if mod is None: + return self._run_op("__pow__", value) + return self._run_op("__pow__", self, value, mod) + + def __lshift__(self, value: PynalyserType) -> Return: + return self._run_op("__lshift__", value) + + def __rshift__(self, value: PynalyserType) -> Return: + return self._run_op("__rshift__", value) + + def __and__(self, value: PynalyserType) -> Return: + return self._run_op("__and__", value) + + def __xor__(self, value: PynalyserType) -> Return: + return self._run_op("__xor__", value) + + def __or__(self, value: PynalyserType) -> Return: + return self._run_op("__or__", value) + + # Reversed binary operation + def __radd__(self, value: PynalyserType) -> Return: + return self._run_op("__radd__", value) + + def __rsub__(self, value: PynalyserType) -> Return: + return self._run_op("__rsub__", value) + + def __rmul__(self, value: PynalyserType) -> Return: + return self._run_op("__rmul__", value) + + def __rmatmul__(self, value: PynalyserType) -> Return: + return self._run_op("__rmatmul__", value) + + def __rtruediv__(self, value: PynalyserType) -> Return: + return self._run_op("__rtruediv__", value) + + def __rfloordiv__(self, value: PynalyserType) -> Return: + return self._run_op("__rfloordiv__", value) + + def __rmod__(self, value: PynalyserType) -> Return: + return self._run_op("__rmod__", value) + + def __rdivmod__(self, value: PynalyserType) -> Return: + return self._run_op("__rdivmod__", value) + + # XXX: 'Optional' is a hack, it probably should be handled differently + def __rpow__( + self, value: PynalyserType, mod: Optional[PynalyserType] = None + ) -> Return: + if mod is None: + return self._run_op("__rpow__", value) + return self._run_op("__rpow__", self, value, mod) + + def __rlshift__(self, value: PynalyserType) -> Return: + return self._run_op("__rlshift__", value) + + def __rrshift__(self, value: PynalyserType) -> Return: + return self._run_op("__rrshift__", value) + + def __rand__(self, value: PynalyserType) -> Return: + return self._run_op("__rand__", value) + + def __rxor__(self, value: PynalyserType) -> Return: + return self._run_op("__rxor__", value) + + def __ror__(self, value: PynalyserType) -> Return: + return self._run_op("__ror__", value) + + # Other magic + # def __getitem__(self, value: PynalyserType) -> Return: + # return self._get_op_func("__getitem__")(self, value) + + # def __contains__(self, value: PynalyserType) -> Return: + # return self._get_op_func("__contains__")(self, value) + + +AnyType = DataType(name="object", is_builtin=False) +UnknownType = DataType(name="object", is_builtin=False) +# invariant, cool name huh ;) diff --git a/pynalyser/types/exceptions.py b/pynalyser/types/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..0fe4335cca3cddb8bd6168fdf3676132cd77d636 --- /dev/null +++ b/pynalyser/types/exceptions.py @@ -0,0 +1,69 @@ +from typing import List + + +OP_TO_STR = { + # binop + "add": "+", + "sub": "-", + "matmul": "@", + "mul": "*", + "truediv": "/", + "mod": "%", + "lshift": "<<", + "rshift": ">>", + "or": "|", + "xor": "^", + "and": "&", + "floordiv": "//", + "pow": "**", + # cmpop + "eq": "==", + "ne": "!=", + "lt": "<", + "le": "<=", + "gt": ">", + "ge": ">=", + # unop + "invert": "~", + "pos": "+", + "neg": "-", +} + + +def binary_not_supported(op: str, lhs: str, rhs: str) -> TypeError: + return TypeError( + f"unsupported operand type(s) for {OP_TO_STR[op]}: '{lhs}' and '{rhs}'" + ) + + +def compare_not_supported(op: str, lhs: str, rhs: str) -> TypeError: + return TypeError( + f"'{OP_TO_STR[op]}' not supported between instances of '{lhs}' and '{rhs}'" + ) + + +def unary_not_supported(op: str, type: str) -> TypeError: + return TypeError(f"bad operand type for unary {OP_TO_STR[op]}: '{type}'") + + +def not_iterable(type: str) -> TypeError: + return TypeError(f"argument of type '{type}' is not iterable") + + +def not_subscriptable(type: str) -> TypeError: + return TypeError(f"'{type}' object is not subscriptable") + + +def invalid_mro(bases: List[str]) -> TypeError: + return TypeError( + "Cannot create a consistent method resolution\n" + "order (MRO) for bases " + " ".join(bases) + ) + + +def duplicate_base(base: str) -> TypeError: + return TypeError("duplicate base class " + base) + + +def inheritance_cycle() -> TypeError: + return TypeError("a __bases__ item causes an inheritance cycle") diff --git a/pynalyser/types/inheritance.py b/pynalyser/types/inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..ece9a33400df4e78f87b9cf2b461e0ae17969ec9 --- /dev/null +++ b/pynalyser/types/inheritance.py @@ -0,0 +1,93 @@ +from typing import List, Optional, Tuple, Type, Union + +from .exceptions import duplicate_base, inheritance_cycle, invalid_mro + + +ENTRY = Type["Inheritable"] +TYPE_OR_INSTANCE = Union["Inheritable", ENTRY] +INHERITABLES = Tuple[ENTRY, ...] + + +def find_a_good_head(linearizations: List[List[ENTRY]]) -> Optional[ENTRY]: + for head, *_ in linearizations: + if all(head not in tail for _, *tail in linearizations): + return head + return None + + +def linearization(obj: ENTRY, parents: INHERITABLES) -> INHERITABLES: + parent_linearizations = [list(parent.mro) for parent in parents] + [list(parents)] + linearization: List[ENTRY] = [] + + # probably will take at most set(chain(*parent_linearizations)) iterations + while 1: + parent_linearizations = [lin for lin in parent_linearizations if lin] + if len(parent_linearizations) == 0: + return (obj, *linearization) + + head = find_a_good_head(parent_linearizations) + if head is None: + raise invalid_mro([lin.__name__ for lin in parents]) + + linearization.append(head) + for parent_linearization in parent_linearizations: + if parent_linearization[0] == head: + del parent_linearization[0] + + assert False, "Unreachable" + + +def validate_bases(obj: ENTRY, bases: INHERITABLES) -> None: + visited = set() + + for base in bases: + if base is obj: + raise inheritance_cycle() + + if base not in visited: + visited.add(base) + else: + raise duplicate_base(base.__name__) + + +def set_bases(obj: ENTRY, bases: INHERITABLES) -> None: + validate_bases(obj, bases) + obj.bases = bases + obj.mro = linearization(obj, obj.bases) + + +_internal_counter = 0 + + +def register_inheritance(obj: ENTRY) -> None: + global _internal_counter + _internal_counter += 1 + + obj._type_id = _internal_counter + + +class Inheritable: + mro: INHERITABLES = () + bases: INHERITABLES = () + _type_id: int = 0 + + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + register_inheritance(cls) + + +def is_type(cls: TYPE_OR_INSTANCE, other: TYPE_OR_INSTANCE) -> bool: + return cls._type_id == other._type_id + + +def is_subclass( + cls: TYPE_OR_INSTANCE, + class_or_tuple: Union[TYPE_OR_INSTANCE, Tuple[TYPE_OR_INSTANCE, ...]], +) -> bool: + if isinstance(class_or_tuple, tuple): + return any(is_subclass(cls, tp) for tp in class_or_tuple) + + for base in cls.mro: + if is_type(base, class_or_tuple): + return True + return False diff --git a/pynalyser/types/op.py b/pynalyser/types/op.py new file mode 100644 index 0000000000000000000000000000000000000000..220558ebd78009490373485e9db6dde801326004 --- /dev/null +++ b/pynalyser/types/op.py @@ -0,0 +1,117 @@ +from typing import TYPE_CHECKING, Callable, Dict, NamedTuple, Optional, Set, Tuple, Type + +if TYPE_CHECKING: + from .base_types import PynalyserType, DataType + + +OpFunction = Callable[..., "DataType"] +Signature = Tuple["DataType", ...] + + +class Op(NamedTuple): + function: OpFunction + signature: Signature = tuple() + + def __call__(self, *args: "PynalyserType", **kwargs: "PynalyserType") -> "DataType": + return self.function(*args, **kwargs) + + def __repr__(self) -> str: + return f"Op({self.function.__name__}, {self.signature})" + + @classmethod + def sign(cls, signature: Signature = tuple()): + def wrapper(function: OpFunction): + return cls(function, signature) + + return wrapper + + +DEFAULT_FUNCTIONS = { + "cmp": { + "__lt__", + "__le__", + "__eq__", + "__ne__", + "__gt__", + "__ge__", + }, + "binop": { + "__add__", + "__sub__", + "__mul__", + "__matmul__", + "__truediv__", + "__floordiv__", + "__mod__", + "__divmod__", + "__pow__", + "__lshift__", + "__rshift__", + "__and__", + "__xor__", + "__or__", + }, + "rev_binop": { + "__radd__", + "__rsub__", + "__rmul__", + "__rmatmul__", + "__rtruediv__", + "__rfloordiv__", + "__rmod__", + "__rdivmod__", + "__rpow__", + "__rlshift__", + "__rrshift__", + "__rand__", + "__rxor__", + "__ror__", + }, +} + + +OpDict = Dict[str, Op] + + +class OpCarrier: + ops: OpDict = {} + + def _get_op_func(self, name: str) -> OpFunction: + try: + return self.ops[name].function + except KeyError: + return self._default_op_func + + @staticmethod + def _default_op_func(*args, **kwargs) -> "DataType": + from .structure_types import NotImplementedType + + return NotImplementedType + + +def set_op(cls: Type[OpCarrier], op: Op, name: Optional[str] = None) -> None: + if name is None: + name = op.function.__name__ + cls.ops[name] = op + + +NORMAL = False +REVERSED = True + + +def set_default_ops( + cls: Type[OpCarrier], + op: Op, + reversed: bool = False, + name: Optional[str] = None, + *, + exclude: Optional[Set[str]] = None, +) -> None: + if name is None: + name = op.function.__name__ + name = op.function.__name__.split("_")[-1] + if reversed: + name = "rev_" + name + + exclude = exclude or set() + cls.ops.update(dict.fromkeys(DEFAULT_FUNCTIONS[name] - exclude, op)) diff --git a/pynalyser/types/reference_types.py b/pynalyser/types/reference_types.py new file mode 100644 index 0000000000000000000000000000000000000000..5547a8e262664dfdf9f695caba3ef2a001fefcf9 --- /dev/null +++ b/pynalyser/types/reference_types.py @@ -0,0 +1,321 @@ +from typing import TYPE_CHECKING, List, Optional, Tuple + +import attr + +from .. import reports +from .base_types import (AnyType, DataType, PynalyserType, UnionType, + UnknownType) +from .exceptions import (binary_not_supported, compare_not_supported, + not_iterable, not_subscriptable) +from .inheritance import is_subclass, is_type +from .op import Op, Signature +from .structure_types import (BoolType, IntType, IterableType, + NotImplementedType) + +if TYPE_CHECKING: + from ..symbol import Symbol + + +Calls = List[Tuple[Optional[Op], bool]] + + +@attr.s(auto_attribs=True, auto_detect=True) +class SymbolType(PynalyserType): + name: str + symbol: "Symbol" + + def deref(self, report: bool) -> DataType: + return self.symbol.type.deref(report) + + def __hash__(self) -> int: + return hash((type(self), self.name)) + + +def infer_signature_type(tp: DataType, signature: Signature) -> DataType: + if is_subclass(tp, signature): + return tp + if not tp.is_completed: + return UnionType(*signature).deref(report=False) + return tp + + +def narrow_type( + calls: Calls, lhs: DataType, rhs: DataType +) -> Tuple[DataType, DataType]: + + for method, reflected in calls: + if method is None: + # TODO: we should add the respective dunder method to the type + # method = Op.sign((lhs if reflected else rhs,))(lambda) + continue + else: + signature = method.signature + if reflected: + lhs = infer_signature_type(lhs, signature) + else: + rhs = infer_signature_type(rhs, signature) + + return lhs, rhs + + +@attr.s(auto_attribs=True, hash=True) +class BinOpType(PynalyserType): + lhs: PynalyserType + op: str + rhs: PynalyserType + + @staticmethod + def prepare_calls(lhs: DataType, op: str, rhs: DataType) -> Calls: + forward = f"__{op}__" + reflected = f"__r{op}__" + + lhs_op = lhs.ops.get(forward) + rhs_op = rhs.ops.get(reflected) + + call_lhs = lhs_op, False + call_rhs = rhs_op, True + + if is_type(lhs, rhs): + return [call_lhs] + # will "lhs.ops.get(reflected) is not rhs_op" be not triggered when needed? + elif is_subclass(rhs, lhs) and lhs.ops.get(reflected) is not rhs_op: + return [call_rhs, call_lhs] + else: + return [call_lhs, call_rhs] + + @classmethod + def do_binary_op( + cls, lhs: DataType, op: str, rhs: DataType, report: bool = True + ) -> DataType: + for method, reflected in cls.prepare_calls(lhs, op, rhs): + if method is None: + continue + + if reflected: + value = method(rhs, lhs) + else: + value = method(lhs, rhs) + + if value is not NotImplementedType: + return value + + if report: + reports.report(binary_not_supported(op, lhs.name, rhs.name)) + + return AnyType + + def __attrs_post_init__(self) -> None: + lhs = self.lhs.deref(report=False) + rhs = self.rhs.deref(report=False) + + lhs, rhs = narrow_type(self.prepare_calls(lhs, self.op, rhs), lhs, rhs) + + if isinstance(self.lhs, SymbolType): + self.lhs.symbol.type = lhs + + if isinstance(self.rhs, SymbolType): + self.rhs.symbol.type = rhs + + def deref(self, report: bool) -> DataType: + return self.do_binary_op( + self.lhs.deref(report), self.op, self.rhs.deref(report), report + ) + + +_CMP = ["gt", "ge", "eq", "ne", "lt", "le"] +SWAPPED_CMP = {v1: v2 for v1, v2 in zip(_CMP, _CMP[::-1])} + + +@attr.s(auto_attribs=True, hash=True) +class CompareOpType(PynalyserType): + lhs: PynalyserType + ops: List[str] + comparators: List[PynalyserType] + + @staticmethod + def prepare_calls(lhs: DataType, op: str, rhs: DataType) -> Calls: + if op == "is": + return [] + + if op == "contains": + return [(rhs.ops.get(op), True)] + + # richcompare + f_lhs = lhs.ops.get(f"__{op}__") + f_rhs = rhs.ops.get(f"__{SWAPPED_CMP[op]}__") + + call_lhs = f_lhs, False + call_rhs = f_rhs, True + + if not is_type(lhs, rhs) and is_subclass(rhs, lhs): + return [call_rhs, call_lhs] + else: + return [call_lhs, call_rhs] + + @classmethod + def do_is( + cls, lhs: DataType, op: str, rhs: DataType, report: bool = True + ) -> DataType: + + calls = cls.prepare_calls(lhs, op, rhs) + assert len(calls) == 0, f"calls were prepared for '{op}' operation" + + # lhs.id == rhs.id or something, idk + return BoolType() + + @classmethod + def do_contains( + cls, lhs: DataType, op: str, rhs: DataType, report: bool = True + ) -> DataType: + + for method, reflected in cls.prepare_calls(lhs, op, rhs): + assert reflected, f"'{op}' operation is not reflected" + + if method is None: + continue + + return method(rhs, lhs) + + # TODO: _PySequence_IterSearch(rhs, lhs, PY_ITERSEARCH_CONTAINS) + + if report: + reports.report(not_iterable(rhs.name)) + + return AnyType + + @classmethod + def do_richcompare( + cls, lhs: DataType, op: str, rhs: DataType, report: bool = True + ) -> DataType: + + for method, reflected in cls.prepare_calls(lhs, op, rhs): + if method is None: + continue + + if reflected: + value = method(rhs, lhs) + else: + value = method(lhs, rhs) + + if value is not NotImplementedType: + return value + + # if neither object implements it, + # provide a sensible default for == and != + if op == "eq": + return cls.do_is(lhs, op, rhs) + if op == "ne": + # TODO: use UnaryOpType.do_not (it's special, + # so no problems with excessive calls to dunder/other methods) + return cls.do_is(lhs, op, rhs) + + if report: + reports.report(compare_not_supported(op, lhs.name, rhs.name)) + + return AnyType + + @staticmethod + def process_op(op: str) -> Tuple[str, bool]: + op, _, neg = op.partition("_") + return op, neg == "not" + + @classmethod + def do_compare_op( + cls, lhs: DataType, op: str, rhs: DataType, report: bool = True + ) -> DataType: + + # TODO: the same deal - use UnaryOpType.do_not for negate + op, negate = cls.process_op(op) + + if op == "is": + return cls.do_is(lhs, op, rhs, report) + + if op == "contains": + return cls.do_contains(lhs, op, rhs, report) + + return cls.do_richcompare(lhs, op, rhs, report) + + def deref_comparators(self, report: bool) -> List[DataType]: + return [ + comparator.deref(report) for comparator in [self.lhs] + self.comparators + ] + + def __attrs_post_init__(self) -> None: + # comparators = self.deref_comparators(report=False) + # for lhs, op, rhs in zip(comparators, self.ops, comparators[1:]): + # op = self.process_op(op)[0] + # lhs, rhs = narrow_type(self.prepare_calls(lhs, op, rhs), lhs, rhs) + + lhs = self.lhs.deref(report=False) + rhs = self.comparators[0].deref(report=False) + + op = self.process_op(self.ops[0])[0] + lhs, rhs = narrow_type(self.prepare_calls(lhs, op, rhs), lhs, rhs) + + if isinstance(self.lhs, SymbolType): + self.lhs.symbol.type = lhs + + if isinstance(self.comparators[0], SymbolType): + self.comparators[0].symbol.type = rhs + + def deref(self, report: bool) -> DataType: + comparators = self.deref_comparators(report) + + # TODO: implement and use all() + for lhs, op, rhs in zip(comparators, self.ops, comparators[1:]): + self.do_compare_op(lhs, op, rhs, report) + + return BoolType() + + +@attr.s(auto_attribs=True, hash=True) +class SubscriptType(PynalyserType): + value: PynalyserType + slice: PynalyserType + + def deref(self, report: bool) -> DataType: + value = self.value.deref(report) + method = value.ops.get("__getitem__") + + if method is not None: + return method(value, self.slice.deref(report)) + + if report: + reports.report(not_subscriptable(value.name)) + + return AnyType + + +@attr.s(auto_attribs=True, hash=True) +class ItemType(PynalyserType): + iterable: PynalyserType + + def __attrs_post_init__(self) -> None: + tp = self.iterable.deref(report=False) + if tp is UnknownType: + if isinstance(self.iterable, SymbolType): + self.iterable.symbol.type = IterableType( + item_type=UnknownType, is_builtin=False + ) + # XXX: should we let it be and cause an error? + # else: + # self.iterable = IterableType( + # item_type=UnknownType, is_builtin=False) + + def deref(self, report: bool) -> DataType: + return self.iterable.deref(report).item_type.deref(report) # type: ignore + + +@attr.s(auto_attribs=True, hash=True) +class CallType(PynalyserType): + func: PynalyserType + args: Tuple[PynalyserType, ...] + keywords: Tuple[Tuple[Optional[str], PynalyserType], ...] + + def deref(self, report: bool) -> DataType: + if isinstance(self.func, SymbolType) and self.func.name == "range": + return IterableType( + item_type=IntType(), is_builtin=False + ) # XXX: is_builtin?? + + return AnyType diff --git a/pynalyser/types/structure_types.py b/pynalyser/types/structure_types.py new file mode 100644 index 0000000000000000000000000000000000000000..8ccc9089504024300cb98486d75af289c1a90c5e --- /dev/null +++ b/pynalyser/types/structure_types.py @@ -0,0 +1,192 @@ +import attr + +from .base_types import AnyType, PynalyserType, DataType +from .op import REVERSED, Op, Signature, set_default_ops, set_op +from .inheritance import set_bases + +# TODO: make a base class with __X__ and _sig_X annotated and defaulted +# the default value must be equal to a field not defined in the simulated class +# INFO: docs.python.org/3/reference/datamodel.html#object.__lt__ +# INFO: docs.python.org/3/reference/datamodel.html#emulating-numeric-types + + +signature: Signature + + +NotImplementedType = DataType(name="NotImplementedType", is_builtin=True) + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class IntType(DataType): + name: str = "int" + is_builtin: bool = True + is_completed: bool = True + + +set_bases(IntType, ()) + + +signature = (IntType(),) + + +# also see "long_compare" in cpython github +@Op.sign(signature) +def _int_cmp(this: DataType, value: PynalyserType) -> DataType: + if isinstance(value, IntType): + return BoolType() + return NotImplementedType + + +@Op.sign(signature) +def _int_binop(this: DataType, value: PynalyserType) -> DataType: + if isinstance(value, IntType): + return IntType() + return NotImplementedType + + +@Op.sign(signature) +def _int__truediv__(this: DataType, value: PynalyserType) -> DataType: + if isinstance(value, IntType): + return FloatType() + return NotImplementedType + + +# def __pow__( +# self, value: PynalyserType, mod: Optional[PynalyserType] = None +# ) -> DataType: +# if isinstance(value, IntType): +# if isinstance(mod, IntType) or mod is None: +# # FIXME: this is true only if 'value' is negative +# # otherwise it's int +# return FloatType() +# return NotImplementedType + + +IntType.ops = IntType.ops.copy() +set_default_ops(IntType, _int_cmp) +set_default_ops(IntType, _int_binop, exclude={"__matmul__"}) +set_op(IntType, _int__truediv__, "__truediv__") + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class BoolType(IntType): + name: str = "bool" + is_builtin: bool = True + is_completed: bool = True + + +set_bases(BoolType, (IntType,)) + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class FloatType(DataType): + name: str = "float" + is_builtin: bool = True + is_completed: bool = True + + +set_bases(FloatType, ()) + + +signature = (IntType(), FloatType()) + + +@Op.sign(signature) +def _float_binop(this: DataType, value: PynalyserType) -> DataType: + if isinstance(value, (IntType, FloatType)): + return FloatType() + return NotImplementedType + + +FloatType.ops = FloatType.ops.copy() +set_default_ops(FloatType, _float_binop, exclude={"__pow__", "__matmul__"}) +set_default_ops(FloatType, _float_binop, REVERSED, exclude={"__rpow__", "__rmatmul__"}) + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class SliceType(DataType): + name: str = "slice" + is_builtin: bool = True + is_completed: bool = True + + +set_bases(SliceType, ()) + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class IterableType(DataType): + item_type: PynalyserType + name: str = "Iterable" + + @property + def as_str(self) -> str: + return f"{super().as_str}[{self.item_type.as_str}]" + + +set_bases(IterableType, ()) + + +@attr.s(auto_attribs=True, hash=True, cmp=False) # auto_detect=True) +class SequenceType(IterableType): + pass + + +set_bases(SequenceType, (IterableType,)) + + +# TODO: not finished, see docs.python.org/3/library/collections.abc.html +# see docs.python.org/3/c-api/typeobj.html + + +@Op.sign((IntType(),)) +def _seq__mul__(this: DataType, value: PynalyserType) -> DataType: + if isinstance(value, IntType): + return this + return NotImplementedType + + +@Op.sign((AnyType,)) +def _seq__getitem__(this: PynalyserType, item: PynalyserType) -> DataType: + return AnyType + + +SequenceType.ops = SequenceType.ops.copy() +set_op(SequenceType, _seq__mul__, "__mul__") +set_op(SequenceType, _seq__mul__, "__rmul__") +set_op(SequenceType, _seq__getitem__, "__getitem__") + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class ListType(SequenceType): + name: str = "list" + is_builtin: bool = True + is_completed: bool = True + + +set_bases(ListType, (SequenceType,)) + + +@Op.sign((IntType(), SliceType())) +def _list__getitem__(this: ListType, item: PynalyserType) -> DataType: + if isinstance(item, IntType): + return this.item_type.deref(report=True) + if isinstance(item, SliceType): + return this + return NotImplementedType + + +ListType.ops = ListType.ops.copy() +set_op(ListType, _list__getitem__, "__getitem__") + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class TupleType(SequenceType): + name: str = "tuple" + is_builtin: bool = True + is_completed: bool = True + + +set_bases(TupleType, (SequenceType,)) + + +del signature diff --git a/pynalyser/types/symbol_table_types.py b/pynalyser/types/symbol_table_types.py new file mode 100644 index 0000000000000000000000000000000000000000..3263e9cdff5f3b17c09501aa1452a07742ad121e --- /dev/null +++ b/pynalyser/types/symbol_table_types.py @@ -0,0 +1,67 @@ +# XXX: this is also structure type, maybe merge? + +from typing import TYPE_CHECKING, DefaultDict, Iterable, List, Optional + +import attr + +from .base_types import PynalyserType, DataType, UnknownType + +if TYPE_CHECKING: + from ..symbol import MultiDefSymbol, Symbol + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class SymbolTableType(DefaultDict[str, "MultiDefSymbol"], DataType): + is_builtin: bool = attr.ib(default=True, init=False) + + def __attrs_pre_init__(self): + from ..symbol import MultiDefSymbol + + super().__init__(MultiDefSymbol) # for defaultdict + + def reset(self) -> None: + for symbol in self.values(): + symbol.reset() + + +@attr.s(auto_attribs=True, hash=True, auto_detect=True) +class Arg: + name: str + symbol: "Symbol" + default: Optional[PynalyserType] = None + + def __repr__(self) -> str: + default = "" if self.default is None else " = " + str(self.default) + return f"<{self.name}: {self.symbol.type.as_str}{default}>" + + +@attr.s(auto_attribs=True, hash=True) +class Arguments: + posargs: List[Arg] = attr.ib(factory=list) + args: List[Arg] = attr.ib(factory=list) + stararg: Optional[Arg] = None + kwargs: List[Arg] = attr.ib(factory=list) + twostararg: Optional[Arg] = None + + def iter(self) -> Iterable[Arg]: + yield from self.posargs + yield from self.args + if self.stararg is not None: + yield self.stararg + yield from self.kwargs + if self.twostararg is not None: + yield self.twostararg + + +@attr.s(auto_attribs=True, hash=True, cmp=False) +class FunctionType(SymbolTableType): + args: Arguments + return_type: PynalyserType = UnknownType + + name: str = attr.ib(default="function", init=False) + + def reset(self) -> None: + super().reset() + + for arg in self.args.iter(): + self[arg.name].next_def() diff --git a/tests/_test_acr_translator.py b/tests/_test_acr_translator.py new file mode 100644 index 0000000000000000000000000000000000000000..af9399f335ac68f8c9a1ab008f1a4b2389ee0d2a --- /dev/null +++ b/tests/_test_acr_translator.py @@ -0,0 +1,156 @@ +import ast +import sys +from collections import defaultdict + +from pynalyser.acr import classes as acr + +# from pynalyser.acr import classes as acr +from pynalyser.acr.translation import Translator, translate_ast_to_acr +from pynalyser.acr.utils import dump + +tree = ast.parse( + # """ + # if x: + # a = 69 + 42 + # """) + # ( + # """ + # # if a: + # # if b: + # # c + # # else: + # # d + # # else: + # # if e: + # # f + # # else: + # # g + # # try: + # # 8 + # # except x: + # # 6 + # # chain + # # from itertools import chain as c + # if x: + # a, b[0] = 5, 8 + # else: + # 7 + # # @lambda x: x + # # def t(): + # # pass + # # try: + # # 9 + # # except y: + # # 8 + # # if a: + # # def tt(): + # # if h: + # # 8 + # # 3 + # # else: + # # 7 + # # 9 + # """) + """ +class T: + 7 + +class TT: + def t(): + 8 + +def a(): + 5 + +def b(): + class B: + 0 + +def b(): + def c(): + 2 + +69 +""" +) + +if sys.version_info >= (3, 9): + print(ast.dump(tree, indent=4, include_attributes=True)) + +# print(acr.ScopeWithAttributes("", lineno=0, col_offset=4)._attributes) +# out = acr.Function( +# name='b', +# lineno=12, +# col_offset=0) + +# out.body.append( +# acr.CodeBlock([ +# ast.Constant( +# value=7, +# kind=None, +# lineno=3, +# col_offset=4, +# end_lineno=3, +# end_col_offset=5)])) + +# print(ast.NodeVisitor().visit(out)) + +out = translate_ast_to_acr(tree, "test") +print(dump(out, indent="| ", include_attributes=True)) + +if sys.version_info < (3, 7): + breakpoint = object + +breakpoint + +# acr.dump(f)) # out.scopes["a"][0])) +# f = out.blocks[0].body[0].value.get_scope(out) +quit() + +# import attr + +# @attr.s(auto_attribs=True) +# class T: +# i: int + +# t = T(5) +# print(attrs.asdict(t), +# attrs.fields_dict(T), +# attrs.fields(T)) +# del t.i +# print(attrs.asdict(t)) + + +[ + ast.Expr( + value=ast.BinOp( + left=ast.Name(id="a", ctx=ast.Load()), + op=ast.Add(), + right=ast.Name(id="b", ctx=ast.Load()), + ) + ) +] + + +def test_Module(): + tree = ast.Module(body=[], type_ignores=[]) + name = "test" + acr_module = translate_ast_to_acr(tree, name) + assert type(acr_module) == acr.Module + assert acr_module.name == name + assert acr_module.body == [] + + +def test_Expr(): + tree = ast.Module( + body=[ast.Expr(value=ast.Name(id="a", ctx=ast.Load()))], type_ignores=[] + ) + acr_module = translate_ast_to_acr(tree, "test") + # TODO + breakpoint + + +if __name__ == "__main__": + import pytest + + pytest.main([__file__]) diff --git a/tests/test_inherit_dicts.py b/tests/test_inherit_dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ebdf584134e53e991a8ee2287f6bf339b4149b --- /dev/null +++ b/tests/test_inherit_dicts.py @@ -0,0 +1,167 @@ +import pytest +from pynalyser.inherit_dicts import ( + DICTS, + DictNotFoundError, + InheritDicts, + MetaInheritDicts, +) + +from utils import do_test + + +def all_attrs(obj): + return {name: getattr(obj, name) for name in dir(obj) if not name.startswith("__")} + + +def test_empty(): + class Cls1(metaclass=MetaInheritDicts): + pass + + assert all_attrs(Cls1()) == {DICTS: set()} + + class Cls2(metaclass=MetaInheritDicts): + _dicts_to_inherit = set() + + assert all_attrs(Cls2()) == {DICTS: set()} + + class Cls3(InheritDicts): + pass + + assert all_attrs(Cls3()) == {DICTS: set()} + + class Cls4(InheritDicts): + _dicts_to_inherit = set() + + assert all_attrs(Cls4()) == {DICTS: set()} + + +def test_one_dict(): + class Parent(InheritDicts): + _dicts_to_inherit = {"a"} + a = {1: 2} + + assert all_attrs(Parent()) == {DICTS: {"a"}, "a": {1: 2}} + + class Child(Parent): + a = {3: 4} + + assert all_attrs(Child()) == {DICTS: {"a"}, "a": {1: 2, 3: 4}} + + class Child2(Child): + a = {1: 5} + + assert all_attrs(Child2()) == {DICTS: {"a"}, "a": {1: 5, 3: 4}} + + +def test_two_dicts(): + class Parent(InheritDicts): + _dicts_to_inherit = {"a", "b"} + a = {1: 2} + b = {10: 11} + + assert all_attrs(Parent()) == {DICTS: {"a", "b"}, "a": {1: 2}, "b": {10: 11}} + + class Child(Parent): + b = {12: 13} + + assert all_attrs(Child()) == {DICTS: {"a", "b"}, "a": {1: 2}, "b": {10: 11, 12: 13}} + + class Child2(Child): + a = {1: 5} + + assert all_attrs(Child2()) == { + DICTS: {"a", "b"}, + "a": {1: 5}, + "b": {10: 11, 12: 13}, + } + + class Child3(Child2): + a = {3: 4} + b = {12: 0} + + assert all_attrs(Child3()) == { + DICTS: {"a", "b"}, + "a": {1: 5, 3: 4}, + "b": {10: 11, 12: 0}, + } + + +def test_removal(): + class Parent(InheritDicts): + _dicts_to_inherit = {"a"} + a = {1: 2} + + assert all_attrs(Parent()) == {DICTS: {"a"}, "a": {1: 2}} + + class Child(Parent): + _dicts_to_inherit = set() + a = {3: 4} + + assert all_attrs(Child()) == {DICTS: set(), "a": {3: 4}} + + class Child2(Parent): + _dicts_to_inherit = set() + + # regular inheritance + assert all_attrs(Child2()) == {DICTS: set(), "a": {1: 2}} + + +def test_persists(): + class Parent(InheritDicts): + _dicts_to_inherit = {"a"} + a = {1: 2} + + assert all_attrs(Parent()) == {DICTS: {"a"}, "a": {1: 2}} + + class Child(Parent): + pass + + assert all_attrs(Child()) == {DICTS: {"a"}, "a": {1: 2}} + + +def test_nonexisting(): + with pytest.raises(DictNotFoundError, match=str(DictNotFoundError("a", "Cls1"))): + + class Cls1(InheritDicts): + _dicts_to_inherit = {"a"} + + with pytest.raises(DictNotFoundError, match=str(DictNotFoundError("b", "Cls2"))): + + class Cls2(InheritDicts): + _dicts_to_inherit = {"a", "b"} + a = {1: 2} + + +def test_as_a_whole(): + class A(InheritDicts): + _dicts_to_inherit = {"a"} + a = {1: 2} + + class B(A): + a = {5: 6} + + class C(B): + _dicts_to_inherit = {"a", "b"} + a = {1: 8} + b = {1: 9} + + class D(C): + _dicts_to_inherit = {"b"} + b = {2: 19} + + classes = [InheritDicts, A, B, C, D] + values = [ + {DICTS: set()}, + {DICTS: {"a"}, "a": {1: 2}}, + {DICTS: {"a"}, "a": {1: 2, 5: 6}}, + {DICTS: {"b", "a"}, "a": {1: 8, 5: 6}, "b": {1: 9}}, + {DICTS: {"b"}, "a": {1: 8, 5: 6}, "b": {1: 9, 2: 19}}, + ] + + assert len(classes) == len(values) + for cls, value in zip(classes, values): + assert value == all_attrs(cls()), cls.__name__ + + +if __name__ == "__main__": + do_test(__file__) diff --git a/tests/test_inheritance.py b/tests/test_inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..65e0da6615ddcb4af56f466759f8fc385557fd4e --- /dev/null +++ b/tests/test_inheritance.py @@ -0,0 +1,233 @@ +from typing import Tuple, Type +from pynalyser.types.inheritance import Inheritable, is_subclass, is_type, set_bases +from pynalyser.types.exceptions import duplicate_base, invalid_mro +from utils import do_test, raises_instance + + +def make_class( + name: str = "", bases: Tuple[Type[Inheritable], ...] = () +) -> Type[Inheritable]: + cls = type(name, (Inheritable,), {}) + set_bases(cls, bases) + return cls + + +# some tests are adopted from cpython/Lib/test/test_descr.py +def test_no_inheritance(): + A = make_class("A") + assert A.mro == (A,) + + +def test_single_inheritance(): + A = make_class("A") + B = make_class("B", (A,)) + assert B.mro == (B, A) + + +def test_multiple_inheritance(): + A = make_class("A") + A = make_class("A") + B = make_class("B") + C = make_class("C", (A, B)) + assert C.mro == (C, A, B) + + +def test_diamond_inheritance(): + A = make_class("A") + B = make_class("B", (A,)) + C = make_class("C", (A,)) + D = make_class("D", (B, C)) + assert D.mro == (D, B, C, A) + + E = make_class("E", (C, B)) + assert E.mro == (E, C, B, A) + + with raises_instance(invalid_mro(["D", "E"])): + make_class("F", (D, E)) + + with raises_instance(invalid_mro(["E", "D"])): + make_class("G", (E, D)) + + +def test_ex5_from_c3_switch(): + A = make_class("A") + B = make_class("B") + C = make_class("C") + X = make_class("X", (A,)) + Y = make_class("Y", (A,)) + Z = make_class("Z", (X, B, Y, C)) + assert Z.mro == (Z, X, B, Y, A, C) + + +def test_monotonicity(): + Boat = make_class("Boat") + DayBoat = make_class("DayBoat", (Boat,)) + WheelBoat = make_class("WheelBoat", (Boat,)) + EngineLess = make_class("EngineLess", (DayBoat,)) + SmallMultihull = make_class("SmallMultihull", (DayBoat,)) + PedalWheelBoat = make_class("PedalWheelBoat", (EngineLess, WheelBoat)) + SmallCatamaran = make_class("SmallCatamaran", (SmallMultihull,)) + Pedalo = make_class("Pedalo", (PedalWheelBoat, SmallCatamaran)) + assert PedalWheelBoat.mro == ( + PedalWheelBoat, + EngineLess, + DayBoat, + WheelBoat, + Boat, + ) + assert SmallCatamaran.mro == (SmallCatamaran, SmallMultihull, DayBoat, Boat) + assert Pedalo.mro == ( + Pedalo, + PedalWheelBoat, + EngineLess, + SmallCatamaran, + SmallMultihull, + DayBoat, + WheelBoat, + Boat, + ) + + +def test_consistency_with_epg(): + Pane = make_class("Pane") + ScrollingMixin = make_class("ScrollingMixin") + EditingMixin = make_class("EditingMixin") + ScrollablePane = make_class("ScrollablePane", (Pane, ScrollingMixin)) + EditablePane = make_class("EditablePane", (Pane, EditingMixin)) + EditableScrollablePane = make_class( + "EditableScrollablePane", (ScrollablePane, EditablePane) + ) + assert EditableScrollablePane.mro == ( + EditableScrollablePane, + ScrollablePane, + EditablePane, + Pane, + ScrollingMixin, + EditingMixin, + ) + + +def test_mro_disagreement(): + # FIXME: the exact msg is generally considered an impl detail + # if util.check_impl_detail(): check message + + A = make_class("A") + B = make_class("B", (A,)) + C = make_class("C") + + with raises_instance(duplicate_base("A")): + make_class("X", (A, A)) + + with raises_instance(invalid_mro(["A", "B"])): + make_class("X", (A, B)) + + with raises_instance(invalid_mro(["A", "C", "B"])): + make_class("X", (A, C, B)) + + GridLayout = make_class("GridLayout") + HorizontalGrid = make_class("HorizontalGrid", (GridLayout,)) + VerticalGrid = make_class("VerticalGrid", (GridLayout,)) + HVGrid = make_class("HVGrid", (HorizontalGrid, VerticalGrid)) + VHGrid = make_class("VHGrid", (VerticalGrid, HorizontalGrid)) + + with raises_instance(invalid_mro(["HVGrid", "VHGrid"])): + make_class("ConfusedGrid", (HVGrid, VHGrid)) + + +# TODO: add cpython/Lib/test/test_genericclass.py + + +def test_is_type(): + A = make_class("A") + B = make_class("B") + assert not is_type(A, B) + assert not is_type(A, B()) + assert not is_type(A(), B) + assert not is_type(A(), B()) + + C = make_class("C") + assert is_type(C, C) + assert is_type(C, C()) + assert is_type(C(), C) + assert is_type(C(), C()) + + +def test_is_subclass(): + A = make_class("A") + B = make_class("B") + + assert not is_subclass(A, B) + assert not is_subclass(A, B()) + assert not is_subclass(A(), B) + assert not is_subclass(A(), B()) + + assert not is_subclass(B, A) + assert not is_subclass(B, A()) + assert not is_subclass(B(), A) + assert not is_subclass(B(), A()) + + C = make_class("C") + D = make_class("D", (C,)) + + assert is_subclass(D, C) + assert is_subclass(D, C()) + assert is_subclass(D(), C) + assert is_subclass(D(), C()) + + assert not is_subclass(C, D) + assert not is_subclass(C, D()) + assert not is_subclass(C(), D) + assert not is_subclass(C(), D()) + + E = make_class("E", (D, A)) + + assert is_subclass(E, D) + assert is_subclass(E, D()) + assert is_subclass(E(), D) + assert is_subclass(E(), D()) + + assert is_subclass(E, C) + assert is_subclass(E, C()) + assert is_subclass(E(), C) + assert is_subclass(E(), C()) + + assert is_subclass(E, A) + assert is_subclass(E, A()) + assert is_subclass(E(), A) + assert is_subclass(E(), A()) + + +def test_is_subclass_tuple(): + A = make_class("A") + + assert not is_subclass(A, ()) + assert not is_subclass(A(), ()) + + B = make_class("B") + C = make_class("C") + + assert not is_subclass(A, (B, C)) + assert not is_subclass(A, (B, C())) + assert not is_subclass(A, (B(), C)) + assert not is_subclass(A, (B(), C())) + + assert not is_subclass(A(), (B, C)) + assert not is_subclass(A(), (B, C())) + assert not is_subclass(A(), (B(), C)) + assert not is_subclass(A(), (B(), C())) + + D = make_class("D", (A,)) + + assert is_subclass(D, (B, A)) + assert is_subclass(D, (B, A())) + assert is_subclass(D, (B(), A)) + assert is_subclass(D, (B(), A())) + + assert is_subclass(D(), (B, A)) + assert is_subclass(D(), (B, A())) + assert is_subclass(D(), (B(), A)) + assert is_subclass(D(), (B(), A())) + + +if __name__ == "__main__": + do_test(__file__) diff --git a/tests/test_normalize_ast.py b/tests/test_normalize_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2598e7535508f09bd549a8325e6c7432bc3b9d --- /dev/null +++ b/tests/test_normalize_ast.py @@ -0,0 +1,427 @@ +import ast +import sys +from typing import cast + +from pynalyser.ast import AstNormalizer, normalize_ast + +from utils import do_test + + +def assert_node_equality(node1: ast.AST, node2: ast.AST, attributes: bool = False): + assert ast.dump(node1, include_attributes=attributes) == ast.dump( + node2, include_attributes=attributes + ) + + +USE_STR = "use '<>' instead of '!='" +USE_BYTES = USE_STR.encode() + +nodes = dict( + Num=( + "42", + ast.Num(n=42, lineno=1, col_offset=0, end_lineno=1, end_col_offset=2), + ast.Constant( + value=42, kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=2 + ), + ), + Str1=( + "''", + ast.Str(s="", lineno=1, col_offset=0, end_lineno=1, end_col_offset=2), + ast.Constant( + value="", kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=2 + ), + ), + Str2=( + repr(USE_STR), + ast.Str(s=USE_STR, lineno=1, col_offset=0, end_lineno=1, end_col_offset=26), + ast.Constant( + value=USE_STR, + kind=None, + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=26, + ), + ), + Bytes1=( + "b''", + ast.Bytes(s=b"", lineno=1, col_offset=0, end_lineno=1, end_col_offset=3), + ast.Constant( + value=b"", kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=3 + ), + ), + Bytes2=( + repr(USE_BYTES), + ast.Bytes(s=USE_BYTES, lineno=1, col_offset=0, end_lineno=1, end_col_offset=27), + ast.Constant( + value=USE_BYTES, + kind=None, + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=27, + ), + ), + NameConstant1=( + "True", + ast.NameConstant( + value=True, lineno=1, col_offset=0, end_lineno=1, end_col_offset=4 + ), + ast.Constant( + value=True, + kind=None, + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=4, + ), + ), + NameConstant2=( + "False", + ast.NameConstant( + value=False, lineno=1, col_offset=0, end_lineno=1, end_col_offset=5 + ), + ast.Constant( + value=False, + kind=None, + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=5, + ), + ), + NameConstant3=( + "None", + ast.NameConstant( + value=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=4 + ), + ast.Constant( + value=None, + kind=None, + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=4, + ), + ), + Ellipsis1=( + "...", + ast.Ellipsis(lineno=1, col_offset=0, end_lineno=1, end_col_offset=3), + ast.Constant( + value=Ellipsis, + kind=None, + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=3, + ), + ), + Ellipsis2=( + "...", + ast.Ellipsis(lineno=1, col_offset=0, end_lineno=1, end_col_offset=3), + ast.Constant( + value=..., kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=3 + ), + ), + Index1=( + "the_numbers_thou_shalt_count [ 3 ]", + ast.Subscript( + value=ast.Name( + id="the_numbers_thou_shalt_count", + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=28, + ), + slice=ast.Index( + value=ast.Num( + n=3, lineno=1, col_offset=31, end_lineno=1, end_col_offset=32 + ) + ), + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=34, + ), + ast.Subscript( + value=ast.Name( + id="the_numbers_thou_shalt_count", + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=28, + ), + slice=ast.Constant( + value=3, + kind=None, + lineno=1, + col_offset=31, + end_lineno=1, + end_col_offset=32, + ), + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=34, + ), + ), + Index2=( + "airspeed_velocities [ UnladenSwallow ]", + ast.Subscript( + value=ast.Name( + id="airspeed_velocities", + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=19, + ), + slice=ast.Index( + value=ast.Name( + id="UnladenSwallow", + ctx=ast.Load(), + lineno=1, + col_offset=22, + end_lineno=1, + end_col_offset=36, + ) + ), + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=38, + ), + ast.Subscript( + value=ast.Name( + id="airspeed_velocities", + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=19, + ), + slice=ast.Name( + id="UnladenSwallow", + ctx=ast.Load(), + lineno=1, + col_offset=22, + end_lineno=1, + end_col_offset=36, + ), + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=38, + ), + ), + ExtSlice=( + "pi [ 3 : 14, 15 ]", + ast.Subscript( + value=ast.Name( + id="pi", + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=2, + ), + slice=ast.ExtSlice( + dims=[ + ast.Slice( + lower=ast.Num( + n=3, + lineno=1, + col_offset=5, + end_lineno=1, + end_col_offset=6, + ), + upper=ast.Num( + n=14, + lineno=1, + col_offset=9, + end_lineno=1, + end_col_offset=11, + ), + step=None, + lineno=1, + col_offset=5, + end_lineno=1, + end_col_offset=11, + ), + ast.Index( + value=ast.Num( + n=15, + lineno=1, + col_offset=13, + end_lineno=1, + end_col_offset=15, + ) + ), + ] + ), + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=17, + ), + ast.Subscript( + value=ast.Name( + id="pi", + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=2, + ), + slice=ast.Tuple( + elts=[ + ast.Slice( + lower=ast.Constant( + value=3, + lineno=1, + col_offset=5, + end_lineno=1, + end_col_offset=6, + ), + upper=ast.Constant( + value=14, + lineno=1, + col_offset=9, + end_lineno=1, + end_col_offset=11, + ), + step=None, + lineno=1, + col_offset=5, + end_lineno=1, + end_col_offset=11, + ), + ast.Constant( + value=15, + lineno=1, + col_offset=13, + end_lineno=1, + end_col_offset=15, + ), + ], + ctx=ast.Load(), + lineno=1, + col_offset=5, + end_lineno=1, + end_col_offset=15, + ), + ctx=ast.Load(), + lineno=1, + col_offset=0, + end_lineno=1, + end_col_offset=17, + ), + ), +) + + +############ AstNormalizer ############# + + +def normalized_node(node: ast.AST) -> ast.AST: + return AstNormalizer().visit(node) + + +def check_node(source: str, deprecated_node: ast.AST, node: ast.AST) -> None: + assert_node_equality(normalized_node(deprecated_node), node, True) + + +if sys.version < "3.8": + + def test_visit_Num(): + check_node(*nodes["Num"]) + + +def test_visit_Str(): + check_node(*nodes["Str1"]) + check_node(*nodes["Str2"]) + + +def test_visit_Bytes(): + check_node(*nodes["Bytes1"]) + check_node(*nodes["Bytes2"]) + + +def test_visit_NameConstant(): + check_node(*nodes["NameConstant1"]) + check_node(*nodes["NameConstant2"]) + check_node(*nodes["NameConstant3"]) + + +def test_visit_Ellipsis(): + check_node(*nodes["Ellipsis1"]) + check_node(*nodes["Ellipsis2"]) + + +if sys.version < "3.9": + + def test_visit_Index(): + check_node(*nodes["Index1"]) + check_node(*nodes["Index2"]) + + def test_visit_ExtSlice(): + return # for now + check_node(*nodes["ExtSlice"]) + + +############ normalize_ast ############# + + +def normalized_source(source: str) -> ast.AST: + tree = normalize_ast(ast.parse(source, mode="eval")) + return cast(ast.Expression, tree).body + + +def check_source(source: str, deprecated_node: ast.AST, node: ast.AST) -> None: + assert_node_equality(normalized_source(source), node, True) + + +def test_normalize_ast_Num(): + check_source(*nodes["Num"]) + + +def test_normalize_ast_Str(): + check_source(*nodes["Str1"]) + check_source(*nodes["Str2"]) + + +def test_normalize_ast_Bytes(): + check_source(*nodes["Bytes1"]) + check_source(*nodes["Bytes2"]) + + +def test_normalize_ast_NameConstant(): + check_source(*nodes["NameConstant1"]) + check_source(*nodes["NameConstant2"]) + check_source(*nodes["NameConstant3"]) + + +def test_normalize_ast_Ellipsis(): + check_source(*nodes["Ellipsis1"]) + check_source(*nodes["Ellipsis2"]) + + +def test_normalize_ast_Index(): + check_source(*nodes["Index1"]) + check_source(*nodes["Index2"]) + + +def test_normalize_ast_ExtSlice(): + return # for now + check_source(*nodes["ExtSlice"]) + + +if __name__ == "__main__": + do_test(__file__) diff --git a/tests/test_structure_types.py b/tests/test_structure_types.py new file mode 100644 index 0000000000000000000000000000000000000000..573bba67bea14c940b9a06e817b5f295fd6492f9 --- /dev/null +++ b/tests/test_structure_types.py @@ -0,0 +1,75 @@ +from pynalyser.types import * +from pynalyser.analysers.type_inference import CMPOP, BINOP + +from utils import do_test + +import operator + +# you cannot overwrite 'is' and True/False != BoolType :( +# operator.__is__ = operator.is_ # type: ignore[attr-defined] +# operator.__is_not__ = operator.is_not # type: ignore[attr-defined] +operator.__contains_not__ = lambda a, b: a not in b # type: ignore[attr-defined] + + +def check_binop(op, lhs, rhs, result): + assert isinstance(getattr(operator, f"__{op}__")(lhs, rhs), result) + assert isinstance(BinOpType(lhs, op, rhs).deref(report=True), result) + + +def check_cmpop(op, lhs, rhs, result): + if op not in ("is", "is_not"): + assert isinstance(getattr(operator, f"__{op}__")(lhs, rhs), result) + assert isinstance(CompareOpType(lhs, [op], [rhs]).deref(report=True), result) + + +BINOPS = set(BINOP.values()) + +CMPOPS = set(CMPOP.values()) + + +def test_int_binop(): + for op in BINOPS - {"matmul", "truediv", "pow"}: + check_binop(op, IntType(), IntType(), IntType) + check_binop("truediv", IntType(), IntType(), FloatType) + # IntType() ** X() can be different, depending on the sign + + +def test_int_cmp(): + for op in CMPOPS - {"contains", "contains_not"}: + check_cmpop(op, IntType(), IntType(), BoolType) + + +def test_float_binop(): + for op in BINOPS - {"matmul", "pow"}: + check_binop(op, FloatType(), IntType(), FloatType) + check_binop(op, IntType(), FloatType(), FloatType) + check_binop(op, FloatType(), FloatType(), FloatType) + # FloatType() ** X() can be different, depending on the sign + + +def test_sequence(): + seq = SequenceType(item_type=PynalyserType(), is_builtin=False) + check_binop("mul", seq, IntType(), SequenceType) + check_binop("mul", IntType(), seq, SequenceType) + # assert seq[SliceType()] is AnyType + assert SubscriptType(seq, SliceType()).deref(True) is AnyType + + +def test_list(): + lst = ListType(item_type=DataType(name="test", is_builtin=False), is_builtin=False) + assert isinstance(lst * IntType(), SequenceType) + # assert lst[IntType()] is lst.item_type + assert SubscriptType(lst, IntType()).deref(True) is lst.item_type + # assert isinstance(lst[SliceType()], ListType) + assert isinstance(SubscriptType(lst, SliceType()).deref(True), ListType) + + +def test_tuple(): + tpl = TupleType(item_type=PynalyserType(), is_builtin=False) + assert isinstance(tpl * IntType(), SequenceType) + # assert tpl[SliceType()] is AnyType + assert SubscriptType(tpl, SliceType()).deref(True) is AnyType + + +if __name__ == "__main__": + do_test(__file__) diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..10e0a13e7b165ab5afef9cd868c94e3459816c19 --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,19 @@ +""" +Things that simplify the testing process and help with it +""" + +import re + +import pytest + + +def fix_message(message: str): + return "^" + re.escape(message).replace("\\ ", " ") + "$" + + +def raises_instance(exc: Exception): + return pytest.raises(type(exc), match=fix_message(exc.args[0])) + + +def do_test(file: str) -> None: + pytest.main([file, "-vv", "-W", "ignore::pytest.PytestAssertRewriteWarning"])
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bc68ca9dd8b84c46cc676c96147c2862c2082e3
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,38 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# For the full list of built-in configuration values, see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+import sys
+import os
+
+# insert pynalyser"s path into the system.
+sys.path.insert(0, os.path.abspath(".."))
+
+import pynalyser # noqa
+
+# -- Project information -----------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
+
+project = pynalyser.__name__
+copyright = "2022, 0dminnimda"
+author = "0dminnimda"
+release = pynalyser.__version__
+
+# -- General configuration ---------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+
+extensions = ["sphinx.ext.autodoc"]
+
+templates_path = ["_templates"]
+exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
+
+# -- Options for HTML output -------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
+
+html_theme = "sphinx_book_theme"
+html_title = pynalyser.__name__.capitalize()
+
+html_static_path = ["_static"]
+
+html_logo = "_static/logo_icon.svg"
diff --git a/pynalyser/__init__.py b/pynalyser/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa6ff8d5329626659615137a0ad50f7d41a345a
--- /dev/null
+++ b/pynalyser/__init__.py
@@ -0,0 +1,2 @@
+__version__ = "0.1.0"
+__name__ = "pynalyser"
diff --git a/pynalyser/acr/__init__.py b/pynalyser/acr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..475d2a03efc0391dc867bc03cf449f5b2f70e051
--- /dev/null
+++ b/pynalyser/acr/__init__.py
@@ -0,0 +1,3 @@
+from .classes import *
+from .translation import translate_ast_to_acr
+from .utils import dump, NODE, NodeVisitor, ACRCodeTransformer
diff --git a/pynalyser/acr/classes.py b/pynalyser/acr/classes.py
new file mode 100644
index 0000000000000000000000000000000000000000..e452dd3c59abf868ce93feccd30402a304cc1b56
--- /dev/null
+++ b/pynalyser/acr/classes.py
@@ -0,0 +1,323 @@
+from typing import List, Optional, Tuple, TypeVar, Union
+
+import attr
+
+from .. import ast
+
+ACR_T = TypeVar("ACR_T")
+
+
+@attr.s
+class ACR:
+ """The base class for each class of abstract representation of the code.
+ Inherited classes can be dumped by :func:`acr.dump <pynalyser.acr.utils.dump>`,
+ but for that to work properly inherited class should use `attr.s`.
+ """
+
+ _attributes: Tuple[str, ...] = attr.ib(init=False, default=())
+ _fields: Tuple[str, ...] = attr.ib(init=False, default=())
+ # _nonblock_fields: Tuple[str, ...] = ()
+ # _block_fields: Tuple[str, ...] = attr.ib(init=False, default=())
+
+ # XXX: abc ? from_ast, to_ast
+ # @classmethod
+ # def from_ast(cls: Type[ACR_T], node: ast.AST) -> ACR_T:
+ # raise NotImplementedError
+
+ # FIXME: this should run only on class creation, so metaclasses?
+ def __attrs_post_init__(self) -> None:
+ _fields = list(attr.fields_dict(type(self)).keys())
+
+ for name in self._attributes:
+ _fields.remove(name)
+ _fields.remove("_attributes")