code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
import re from twovyper.ast.names import RESOURCE_PREFIX, DERIVED_RESOURCE_PREFIX def preprocess(program: str) -> str: # Make specifications valid python statements. We use assignments instead of variable # declarations because we could have contract variables called 'ensures'. # Padding with spaces is used to keep the column numbers correct in the preprocessed program. def padding(old_length: int, match_length: int) -> str: return (match_length - old_length) * ' ' def replacement(start: str, end: str): old_length = len(start) + len(end) return lambda m: f'{start}{padding(old_length, len(m.group(0)))}{end}' def replace(regex, repl): nonlocal program program = re.sub(regex, repl, program, flags=re.MULTILINE) replace(r'#@\s*config\s*:', replacement('config', '=')) replace(r'#@\s*interface', replacement('internal_interface', '=True')) replace(r'#@\s*ghost\s*:', replacement('with(g)', ':')) replace(r'#@\s*resource\s*:\s*', replacement('def ', RESOURCE_PREFIX)) replace(r'#@\s*derived\s*resource\s*:\s*', replacement('def ', DERIVED_RESOURCE_PREFIX)) replace(r'#@\s*ensures\s*:', replacement('ensures', '=')) replace(r'#@\s*requires\s*:', replacement('requires', '=')) replace(r'#@\s*check\s*:', replacement('check', '=')) replace(r'#@\s*performs\s*:', replacement('performs', '=')) replace(r'#@\s*invariant\s*:', replacement('invariant', '=')) replace(r'#@\s*inter\s*contract\s*invariant\s*:', replacement('inter_contract_invariant', '=')) replace(r'#@\s*always\s*ensures\s*:', replacement('always_ensures', '=')) replace(r'#@\s*always\s*check\s*:', replacement('always_check', '=')) replace(r'#@\s*caller\s*private\s*:', replacement('caller_private', '=')) replace(r'#@\s*preserves\s*:', replacement('if False', ':')) replace(r'#@\s*pure', replacement('@pure', '')) replace(r'#@\s*interpreted', replacement('@interpreted', '')) replace(r'#@\s*lemma_def', replacement('def', '')) replace(r'#@\s*lemma_assert', replacement('assert', '')) return program
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/preprocessor.py
preprocessor.py
from functools import reduce from typing import Any, Dict, List import re from lark import Lark from lark.exceptions import ParseError, UnexpectedInput, VisitError from lark.indenter import Indenter from lark.tree import Meta from lark.visitors import Transformer, v_args from twovyper.ast import ast_nodes as ast, names from twovyper.ast.arithmetic import Decimal from twovyper.ast.visitors import NodeVisitor from twovyper.exceptions import ParseException, InvalidProgramException from twovyper.vyper import select_version class PythonIndenter(Indenter): NL_type = '_NEWLINE' OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE'] CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE'] INDENT_type = '_INDENT' DEDENT_type = '_DEDENT' tab_len = 8 _kwargs = dict(postlex=PythonIndenter(), parser='lalr', propagate_positions=True, maybe_placeholders=False) _lark_file = select_version({'^0.2.0': 'vyper_0_2.lark', '>=0.1.0-beta.16 <0.1.0': 'vyper_0_1.lark'}) _vyper_module_parser = Lark.open(_lark_file, rel_to=__file__, start='file_input', **_kwargs) _vyper_expr_parser = Lark.open(_lark_file, rel_to=__file__, start='test', **_kwargs) def copy_pos(function): def with_pos(self, children: List[Any], meta: Meta): node = function(self, children, meta) node.file = self.file node.lineno = meta.line node.col_offset = meta.column node.end_lineno = meta.end_line node.end_col_offset = meta.end_column return node return with_pos def copy_pos_from(node: ast.Node, to: ast.Node): to.file = node.file to.lineno = node.lineno to.col_offset = node.col_offset to.end_lineno = node.end_lineno to.end_col_offset = node.end_col_offset def copy_pos_between(node: ast.Node, left: ast.Node, right: ast.Node) -> ast.Node: assert left.file == right.file assert left.lineno <= right.lineno assert left.lineno != right.lineno or left.col_offset < right.col_offset node.file = left.file node.lineno = left.lineno node.col_offset = left.col_offset node.end_lineno = right.end_lineno node.end_col_offset = right.end_col_offset return node # noinspection PyUnusedLocal @v_args(meta=True) class _PythonTransformer(Transformer): def transform_tree(self, tree, file): self.file = file transformed = self.transform(tree) self.file = None return transformed @copy_pos def file_input(self, children, meta): return ast.Module(children) @copy_pos def contractdef(self, children, meta): name = str(children[0]) body = children[1] return ast.ContractDef(name, body) @copy_pos def structdef(self, children, meta): name = str(children[0]) body = children[1] return ast.StructDef(name, body) @copy_pos def eventdef(self, children, meta): name = str(children[0]) body = children[1] return ast.EventDef(name, body) @copy_pos def mapdef(self, children, meta): assert len(children) == 1 return ast.FunctionCall(names.MAP, children[0], []) @copy_pos def funcdef(self, children, meta): decorators = children[0] name = str(children[1]) args = children[2] if len(children) == 3: # This is a function stub without a return value if decorators: raise InvalidProgramException(decorators[0], 'invalid.function.stub') return ast.FunctionStub(name, args, None) elif len(children) == 4: if isinstance(children[3], list): # This is a function definition without a return value body = children[3] return ast.FunctionDef(name, args, body, decorators, None) else: # This is a function stub with a return value ret = children[3].children ret = ret[0] if len(ret) == 1 else self._tuple(ret, meta) return ast.FunctionStub(name, args, ret) elif len(children) == 5: # This is a function definition with a return value ret = children[3].children ret = ret[0] if len(ret) == 1 else self._tuple(ret, meta) body = children[4] return ast.FunctionDef(name, args, body, decorators, ret) def decorators(self, children, meta): return children @copy_pos def decorator(self, children, meta): name = str(children[0]) if len(children) == 1: args = [] else: args, kwargs = children[1] if kwargs: raise InvalidProgramException(kwargs[0], 'invalid.decorator') return ast.Decorator(name, args) def parameter_list(self, children, meta): return children @copy_pos def parameter(self, children, meta): name = str(children[0]) annotation = children[1] default = children[2] if len(children) == 3 else None return ast.Arg(name, annotation, default) @copy_pos def expr_stmt(self, children, meta): target = children[0] if isinstance(target, list): target = self._tuple(target, meta) if len(children) == 2: assign_builder = children[1] return assign_builder(target) else: return ast.ExprStmt(target) def assign(self, children, meta): if len(children[0]) > 1: # Used for config value = self._tuple(children[0], meta) else: value = children[0][0] return lambda target: ast.Assign(target, value) @copy_pos def _tuple(self, children, meta): return ast.Tuple(children) def annassign(self, children, meta): annotation = children[0] value = children[1] if len(children) == 2 else None return lambda target: ast.AnnAssign(target, annotation, value) def augassign(self, children, meta): op = children[0] value = children[1] return lambda target: ast.AugAssign(target, op, value) def aug_op(self, children, meta): # The actual operation is the first character of augment operator op = children[0][0] return ast.ArithmeticOperator(op) @copy_pos def pass_stmt(self, children, meta): return ast.Pass() @copy_pos def break_stmt(self, children, meta): return ast.Break() @copy_pos def continue_stmt(self, children, meta): return ast.Continue() @copy_pos def return_stmt(self, children, meta): if not children: return ast.Return(None) value = children[0][0] if len(children[0]) == 1 else self._tuple(children[0], meta) return ast.Return(value) @copy_pos def raise_stmt(self, children, meta): exc = children[0] if children else None return ast.Raise(exc) @copy_pos def import_name(self, children, meta): names = children[0] return ast.Import(names) @copy_pos def import_from(self, children, meta): level, module = children[0] names = children[1] return ast.ImportFrom(module, names, level) def relative_name(self, children, meta): if len(children) == 2: level = children[0] name = children[1] elif isinstance(children[0], str): level = 0 name = children[0] else: level = children[0] name = None return level, name def dots(self, children, meta): return len(children[0]) def alias_list(self, children, meta): return children @copy_pos def alias(self, children, meta): name = children[0] asname = children[1] if len(children) == 2 else None return ast.Alias(name, asname) def dotted_name_list(self, children, meta): return children def dotted_name(self, children, meta): return '.'.join(children) @copy_pos def assert_stmt(self, children, meta): test = children[0] msg = children[1] if len(children) == 2 else None return ast.Assert(test, msg) @copy_pos def if_stmt(self, children, meta): if len(children) % 2 == 0: # We have no else branch orelse = [] else: orelse = children.pop() while children: body = children.pop() test = children.pop() orelse = [self._if_stmt([test, body, orelse], meta)] return orelse[0] @copy_pos def log_stmt(self, children, meta): assert len(children) == 1 assert len(children[0]) == 1 assert isinstance(children[0][0], ast.ExprStmt) return ast.Log(children[0][0].value) @copy_pos def _if_stmt(self, children, meta): test = children[0] body = children[1] orelse = children[2] return ast.If(test, body, orelse) @copy_pos def for_stmt(self, children, meta): target = children[0] iter = children[1] body = children[2] return ast.For(target, iter, body) @copy_pos def with_stmt(self, children, meta): body = children[1] # We ignore the items, as we don't need them return ast.Ghost(body) def suite(self, children, meta): return children @copy_pos def test(self, children, meta): body = children[0] cond = children[1] orelse = children[2] return ast.IfExpr(cond, body, orelse) def _left_associative_bool_op(self, children, op): return reduce(lambda l, r: copy_pos_between(ast.BoolOp(l, op, r), l, r), children) def _right_associative_bool_op(self, children, op): return reduce(lambda r, l: copy_pos_between(ast.BoolOp(l, op, r), l, r), reversed(children)) @copy_pos def impl_test(self, children, meta): return self._right_associative_bool_op(children, ast.BoolOperator.IMPLIES) @copy_pos def or_test(self, children, meta): return self._left_associative_bool_op(children, ast.BoolOperator.OR) @copy_pos def and_test(self, children, meta): return self._left_associative_bool_op(children, ast.BoolOperator.AND) @copy_pos def unot(self, children, meta): operand = children[0] return ast.Not(operand) @copy_pos def comparison(self, children, meta): left = children[0] op = children[1] right = children[2] if isinstance(op, ast.ComparisonOperator): return ast.Comparison(left, op, right) elif isinstance(op, ast.ContainmentOperator): return ast.Containment(left, op, right) elif isinstance(op, ast.EqualityOperator): return ast.Equality(left, op, right) else: assert False @copy_pos def arith_expr(self, children, meta): return self._bin_op(children) @copy_pos def term(self, children, meta): return self._bin_op(children) @copy_pos def factor(self, children, meta): op = children[0] operand = children[1] return ast.UnaryArithmeticOp(op, operand) def _bin_op(self, children): operand = children.pop() def bop(right): if children: op = children.pop() left = bop(children.pop()) ret = ast.ArithmeticOp(left, op, right) copy_pos_between(ret, left, right) return ret else: return right return bop(operand) def factor_op(self, children, meta): return ast.UnaryArithmeticOperator(children[0]) def add_op(self, children, meta): return ast.ArithmeticOperator(children[0]) def mul_op(self, children, meta): return ast.ArithmeticOperator(children[0]) def comp_op(self, children, meta): return ast.ComparisonOperator(children[0]) def cont_op(self, children, meta): if len(children) == 1: return ast.ContainmentOperator.IN else: return ast.ContainmentOperator.NOT_IN def eq_op(self, children, meta): return ast.EqualityOperator(children[0]) @copy_pos def power(self, children, meta): left = children[0] right = children[1] return ast.ArithmeticOp(left, ast.ArithmeticOperator.POW, right) @copy_pos def funccall(self, children, meta): func = children[0] args, kwargs = children[1] if isinstance(func, ast.Name): return ast.FunctionCall(func.id, args, kwargs) elif isinstance(func, ast.Subscript) and isinstance(func.value, ast.Name): return ast.FunctionCall(func.value.id, args, kwargs, func.index) elif isinstance(func, ast.Attribute): return ast.ReceiverCall(func.attr, func.value, args, kwargs) elif isinstance(func, ast.Subscript) and isinstance(func.value, ast.Attribute): return ast.ReceiverCall(func.value.attr, func, args, kwargs) else: raise InvalidProgramException(func, 'invalid.receiver') @copy_pos def getitem(self, children, meta): if isinstance(children[0], ast.Name): if children[0].id == names.MAP: assert len(children) == 3 return ast.FunctionCall(names.MAP, children[1:], []) if children[0].id in (names.EXCHANGE, names.OFFER, names.OFFERED, names.REVOKE): if len(children) == 3: value = children[0] index = ast.Exchange(children[1], children[2]) copy_pos_from(children[1], index) return ast.Subscript(value, index) value = children[0] index = children[1] return ast.Subscript(value, index) @copy_pos def getattr(self, children, meta): value = children[0] attr = str(children[1]) return ast.Attribute(value, attr) @copy_pos def exchange(self, children, meta): value1 = children[0] value2 = children[1] return ast.Exchange(value1, value2) @copy_pos def list(self, children, meta): return ast.List(children[0]) @copy_pos def dictset(self, children, meta): if not children: return ast.Dict([], []) elif isinstance(children[0], tuple): keys, values = children[0] return ast.Dict(keys, values) else: return ast.Set(children[0]) @copy_pos def var(self, children, meta): return ast.Name(str(children[0])) @copy_pos def strings(self, children, meta): if isinstance(children[0], ast.Str): conc = ''.join(c.s for c in children) return ast.Str(conc) else: conc = b''.join(c.s for c in children) return ast.Bytes(conc) @copy_pos def ellipsis(self, children, meta): return ast.Ellipsis() @copy_pos def const_true(self, children, meta): return ast.Bool(True) @copy_pos def const_false(self, children, meta): return ast.Bool(False) def testlist(self, children, meta): return children def dictlist(self, children, meta): keys = [] values = [] it = iter(children) for c in it: keys.append(c) values.append(next(it)) return keys, values def arguments(self, children, meta): args = [] kwargs = [] for c in children: if isinstance(c, ast.Keyword): kwargs.append(c) else: # kwargs cannot come before normal args if kwargs: raise InvalidProgramException(kwargs[0], 'invalid.kwargs') args.append(c) return args, kwargs @copy_pos def argvalue(self, children, meta): identifier = str(children[0]) value = children[1] return ast.Keyword(identifier, value) @copy_pos def number(self, children, meta): n = eval(children[0]) return ast.Num(n) @copy_pos def float(self, children, meta): assert 'e' not in children[0] numd = 10 first, second = children[0].split('.') if len(second) > numd: node = self.number(children, meta) raise InvalidProgramException(node, 'invalid.decimal.literal') int_value = int(first) * 10 ** numd + int(second.ljust(numd, '0')) return ast.Num(Decimal[numd](scaled_value=int_value)) @copy_pos def string(self, children, meta): s = eval(children[0]) if isinstance(s, str): return ast.Str(s) elif isinstance(s, bytes): return ast.Bytes(s) else: assert False def parse(parser, text, file): try: tree = parser.parse(text) except (ParseError, UnexpectedInput) as e: raise ParseException(str(e)) try: return _PythonTransformer().transform_tree(tree, file) except VisitError as e: raise e.orig_exc class CodeVisitor(NodeVisitor): def find_lost_code_information(self, text: str, node: ast.Node): lines = text.splitlines() ghost = {} lemmas = {} pattern = re.compile(r'#@\s*lemma_(def|assert).*') for idx, line in enumerate(lines): line_strip = line.strip() ghost[idx + 1] = line_strip.startswith('#@') match = pattern.match(line_strip) lemmas[idx + 1] = match is not None self.visit(node, ghost, lemmas) def generic_visit(self, node: ast.Node, *args): ghost: Dict[int, bool] = args[0] node.is_ghost_code = ghost[node.lineno] super().generic_visit(node, *args) def visit_FunctionDef(self, node: ast.FunctionDef, *args): lemmas: Dict[int, bool] = args[1] node.is_lemma = lemmas[node.lineno] or lemmas[node.lineno + len(node.decorators)] self.generic_visit(node, *args) def visit_Assert(self, node: ast.Assert, *args): lemmas: Dict[int, bool] = args[1] node.is_lemma = lemmas[node.lineno] self.generic_visit(node, *args) def parse_module(text, original, file) -> ast.Module: node = parse(_vyper_module_parser, text + '\n', file) CodeVisitor().find_lost_code_information(original, node) return node def parse_expr(text, file) -> ast.Expr: return parse(_vyper_expr_parser, text, file)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/lark.py
lark.py
from typing import List, Dict, Any, Tuple from twovyper.ast import ast_nodes as ast, names from twovyper.ast.arithmetic import div, mod, Decimal from twovyper.ast.visitors import NodeVisitor, NodeTransformer, descendants from twovyper.exceptions import UnsupportedException from twovyper.parsing import lark from twovyper.utils import switch def transform(vyper_ast: ast.Module) -> ast.Module: constants_decls, new_ast = ConstantCollector().collect_constants(vyper_ast) constant_values, constant_nodes = _interpret_constants(constants_decls) transformed_ast = ConstantTransformer(constant_values, constant_nodes).visit(new_ast) return transformed_ast def _parse_value(val) -> ast.Expr: """ Returns a new ast.Node containing the value. """ return lark.parse_expr(f'{val}', None) def _builtin_constants(): values = {name: value for name, value in names.CONSTANT_VALUES.items()} constants = {name: _parse_value(value) for name, value in names.CONSTANT_VALUES.items()} return values, constants def _interpret_constants(nodes: List[ast.AnnAssign]) -> Tuple[Dict[str, Any], Dict[str, ast.Node]]: env, constants = _builtin_constants() interpreter = ConstantInterpreter(env) for node in nodes: name = node.target.id value = interpreter.visit(node.value) env[name] = value constants[name] = _parse_value(value) return env, constants class ConstantInterpreter(NodeVisitor): """ Determines the value of all constants in the AST. """ def __init__(self, constants: Dict[str, Any]): self.constants = constants def generic_visit(self, node: ast.Node, *args): raise UnsupportedException(node) def visit_BoolOp(self, node: ast.BoolOp): left = self.visit(node.left) right = self.visit(node.right) if node.op == ast.BoolOperator.AND: return left and right elif node.op == ast.BoolOperator.OR: return left or right else: assert False def visit_Not(self, node: ast.Not): operand = self.visit(node.operand) return not operand def visit_ArithmeticOp(self, node: ast.ArithmeticOp): lhs = self.visit(node.left) rhs = self.visit(node.right) op = node.op if op == ast.ArithmeticOperator.ADD: return lhs + rhs elif op == ast.ArithmeticOperator.SUB: return lhs - rhs elif op == ast.ArithmeticOperator.MUL: return lhs * rhs elif op == ast.ArithmeticOperator.DIV: return div(lhs, rhs) elif op == ast.ArithmeticOperator.MOD: return mod(lhs, rhs) elif op == ast.ArithmeticOperator.POW: return lhs ** rhs else: assert False def visit_UnaryArithmeticOp(self, node: ast.UnaryArithmeticOp): operand = self.visit(node.operand) if node.op == ast.UnaryArithmeticOperator.ADD: return operand elif node.op == ast.UnaryArithmeticOperator.SUB: return -operand else: assert False def visit_Comparison(self, node: ast.Comparison): lhs = self.visit(node.left) rhs = self.visit(node.right) with switch(node.op) as case: if case(ast.ComparisonOperator.LT): return lhs < rhs elif case(ast.ComparisonOperator.LTE): return lhs <= rhs elif case(ast.ComparisonOperator.GT): return lhs > rhs elif case(ast.ComparisonOperator.GTE): return lhs >= rhs else: assert False def visit_Equality(self, node: ast.Equality): lhs = self.visit(node.left) rhs = self.visit(node.right) if node.op == ast.EqualityOperator.EQ: return lhs == rhs elif node.op == ast.EqualityOperator.NEQ: return lhs != rhs else: assert False def visit_FunctionCall(self, node: ast.FunctionCall): args = [self.visit(arg) for arg in node.args] if node.name == names.MIN: return min(args) elif node.name == names.MAX: return max(args) elif node.name == names.CONVERT: arg = args[0] second_arg = node.args[1] assert isinstance(second_arg, ast.Name) type_name = second_arg.id if isinstance(arg, int): with switch(type_name) as case: if case(names.BOOL): return bool(arg) elif case(names.DECIMAL): return Decimal[10](value=arg) elif (case(names.INT128) or case(names.UINT256) or case(names.BYTES32)): return arg elif isinstance(arg, Decimal): with switch(type_name) as case: if case(names.BOOL): # noinspection PyUnresolvedReferences return bool(arg.scaled_value) elif case(names.DECIMAL): return arg elif (case(names.INT128) or case(names.UINT256) or case(names.BYTES32)): # noinspection PyUnresolvedReferences return div(arg.scaled_value, arg.scaling_factor) elif isinstance(arg, bool): with switch(type_name) as case: if case(names.BOOL): return arg elif (case(names.DECIMAL) or case(names.INT128) or case(names.UINT256) or case(names.BYTES32)): return int(arg) raise UnsupportedException(node) @staticmethod def visit_Num(node: ast.Num): if isinstance(node.n, int) or isinstance(node.n, Decimal): return node.n else: assert False @staticmethod def visit_Bool(node: ast.Bool): return node.value def visit_Str(self, node: ast.Str): return '"{}"'.format(node.s) def visit_Name(self, node: ast.Name): return self.constants.get(node.id) def visit_List(self, node: ast.List): return [self.visit(element) for element in node.elements] class ConstantCollector(NodeTransformer): """ Collects constants and deletes their declarations from the AST. """ def __init__(self): self.constants = [] @staticmethod def _is_constant(node: ast.Node): return isinstance(node, ast.FunctionCall) and node.name == 'constant' def collect_constants(self, node): new_node = self.visit(node) return self.constants, new_node def visit_AnnAssign(self, node: ast.AnnAssign): if self._is_constant(node.annotation): self.constants.append(node) return None else: return node @staticmethod def visit_FunctionDef(node: ast.FunctionDef): return node class ConstantTransformer(NodeTransformer): """ Replaces all constants in the AST by their value. """ def __init__(self, constant_values: Dict[str, Any], constant_nodes: Dict[str, ast.Node]): self.constants = constant_nodes self.interpreter = ConstantInterpreter(constant_values) def _copy_pos(self, to: ast.Node, node: ast.Node) -> ast.Node: to.file = node.file to.lineno = node.lineno to.col_offset = node.col_offset to.end_lineno = node.end_lineno to.end_col_offset = node.end_col_offset to.is_ghost_code = node.is_ghost_code for child in descendants(to): self._copy_pos(child, node) return to def visit_Name(self, node: ast.Name): return self._copy_pos(self.constants.get(node.id) or node, node) # noinspection PyBroadException def visit_FunctionCall(self, node: ast.FunctionCall): if node.name == names.RANGE: if len(node.args) == 1: try: val = self.interpreter.visit(node.args[0]) new_node = _parse_value(val) new_node = self._copy_pos(new_node, node.args[0]) assert isinstance(new_node, ast.Expr) node.args[0] = new_node except Exception: pass elif len(node.args) == 2: first_arg = node.args[0] second_arg = node.args[1] if isinstance(second_arg, ast.ArithmeticOp) \ and second_arg.op == ast.ArithmeticOperator.ADD \ and ast.compare_nodes(first_arg, second_arg.left): try: val = self.interpreter.visit(second_arg.right) new_node = _parse_value(val) second_arg.right = self._copy_pos(new_node, second_arg.right) except Exception: pass else: try: first_val = self.interpreter.visit(first_arg) first_new_node = _parse_value(first_val) first_new_node = self._copy_pos(first_new_node, first_arg) assert isinstance(first_new_node, ast.Expr) second_val = self.interpreter.visit(second_arg) second_new_node = _parse_value(second_val) second_new_node = self._copy_pos(second_new_node, first_arg) assert isinstance(second_new_node, ast.Expr) node.args[0] = first_new_node node.args[1] = second_new_node except Exception: pass else: self.generic_visit(node) return node
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/transformer.py
transformer.py
import os from contextlib import contextmanager from typing import Optional, Dict, Union, List from twovyper.parsing.lark import copy_pos_from from twovyper.utils import switch, first from twovyper.parsing import lark from twovyper.parsing.preprocessor import preprocess from twovyper.parsing.transformer import transform from twovyper.ast import ast_nodes as ast, interfaces, names from twovyper.ast.visitors import NodeVisitor, NodeTransformer from twovyper.ast.nodes import ( VyperProgram, VyperFunction, VyperStruct, VyperContract, VyperEvent, VyperVar, Config, VyperInterface, GhostFunction, Resource ) from twovyper.ast.types import ( TypeBuilder, FunctionType, EventType, SelfType, InterfaceType, ResourceType, StructType, ContractType, DerivedResourceType ) from twovyper.exceptions import InvalidProgramException, UnsupportedException def parse(path: str, root: Optional[str], as_interface=False, name=None, parse_level=0) -> VyperProgram: with open(path, 'r') as file: contract = file.read() preprocessed_contract = preprocess(contract) contract_ast = lark.parse_module(preprocessed_contract, contract, path) contract_ast = transform(contract_ast) program_builder = ProgramBuilder(path, root, as_interface, name, parse_level) return program_builder.build(contract_ast) class ProgramBuilder(NodeVisitor): """ The program builder creates a Vyper program out of the AST. It collects contract state variables and functions. It should only be used by calling the build method once. """ # Pre and postconditions are only allowed before a function. As we walk through all # top-level statements we gather pre and postconditions until we reach a function # definition. def __init__(self, path: str, root: Optional[str], is_interface: bool, name: str, parse_level: int): self.path = os.path.abspath(path) self.root = root self.is_interface = is_interface self.name = name self.parse_further_interfaces = parse_level <= 3 self.parse_level = parse_level self.config = None self.field_types = {} self.functions = {} self.lemmas = {} self.function_counter = 0 self.interfaces = {} self.structs = {} self.contracts = {} self.events = {} self.resources = {} self.local_state_invariants = [] self.inter_contract_invariants = [] self.general_postconditions = [] self.transitive_postconditions = [] self.general_checks = [] self.implements = [] self.additional_implements = [] self.ghost_functions = {} self.ghost_function_implementations = {} self.postconditions = [] self.preconditions = [] self.checks = [] self.caller_private = [] self.performs = [] self.is_preserves = False @property def type_builder(self): type_map = {} for name, struct in self.structs.items(): type_map[name] = struct.type for name, contract in self.contracts.items(): type_map[name] = contract.type for name, interface in self.interfaces.items(): type_map[name] = interface.type return TypeBuilder(type_map, not self.parse_further_interfaces) def build(self, node) -> VyperProgram: self.visit(node) # No trailing local specs allowed self._check_no_local_spec() self.config = self.config or Config([]) if self.config.has_option(names.CONFIG_ALLOCATION): # Add wei underlying resource underlying_wei_type = ResourceType(names.UNDERLYING_WEI, {}) underlying_wei_resource = Resource(underlying_wei_type, None, None) self.resources[names.UNDERLYING_WEI] = underlying_wei_resource # Create a fake node for the underlying wei resource fake_node = ast.Name(names.UNDERLYING_WEI) copy_pos_from(node, fake_node) fake_node.is_ghost_code = True if not self.config.has_option(names.CONFIG_NO_DERIVED_WEI): # Add wei derived resource wei_type = DerivedResourceType(names.WEI, {}, underlying_wei_type) wei_resource = Resource(wei_type, None, None, fake_node) self.resources[names.WEI] = wei_resource if self.is_interface: interface_type = InterfaceType(self.name) if self.parse_level <= 2: return VyperInterface(node, self.path, self.name, self.config, self.functions, self.interfaces, self.resources, self.local_state_invariants, self.inter_contract_invariants, self.general_postconditions, self.transitive_postconditions, self.general_checks, self.caller_private, self.ghost_functions, interface_type) else: return VyperInterface(node, self.path, self.name, self.config, {}, {}, self.resources, [], [], [], [], [], [], self.ghost_functions, interface_type, is_stub=True) else: if self.caller_private: node = first(self.caller_private) raise InvalidProgramException(node, 'invalid.caller.private', 'Caller private is only allowed in interfaces') # Create the self-type self_type = SelfType(self.field_types) self_struct = VyperStruct(names.SELF, self_type, None) return VyperProgram(node, self.path, self.config, self_struct, self.functions, self.interfaces, self.structs, self.contracts, self.events, self.resources, self.local_state_invariants, self.inter_contract_invariants, self.general_postconditions, self.transitive_postconditions, self.general_checks, self.lemmas, self.implements, self.implements + self.additional_implements, self.ghost_function_implementations) def _check_no_local_spec(self): """ Checks that there are no specifications for functions pending, i.e. there are no local specifications followed by either global specifications or eof. """ if self.postconditions: cond = "Postcondition" node = self.postconditions[0] elif self.checks: cond = "Check" node = self.checks[0] elif self.performs: cond = "Performs" node = self.performs[0] else: return raise InvalidProgramException(node, 'local.spec', f"{cond} only allowed before function") def _check_no_ghost_function(self): if self.ghost_functions: cond = "Ghost function declaration" node = first(self.ghost_functions.values()).node elif self.ghost_function_implementations: cond = "Ghost function definition" node = first(self.ghost_function_implementations.values()).node else: return raise InvalidProgramException(node, 'invalid.ghost', f'{cond} only allowed after "#@ interface"') def _check_no_lemmas(self): if self.lemmas: raise InvalidProgramException(first(self.lemmas.values()).node, 'invalid.lemma', 'Lemmas are not allowed in interfaces') def generic_visit(self, node: ast.Node, *args): raise InvalidProgramException(node, 'invalid.spec') def visit_Module(self, node: ast.Module): for stmt in node.stmts: self.visit(stmt) def visit_ExprStmt(self, node: ast.ExprStmt): if not isinstance(node.value, ast.Str): # Long string comment, ignore. self.generic_visit(node) def visit_Import(self, node: ast.Import): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') if not self.parse_further_interfaces: return files = {} for alias in node.names: components = alias.name.split('.') components[-1] = f'{components[-1]}.vy' path = os.path.join(self.root or '', *components) files[path] = alias.asname.value if hasattr(alias.asname, 'value') else alias.asname for file, name in files.items(): if name in [names.SELF, names.LOG, names.LEMMA, *names.ENV_VARIABLES]: raise UnsupportedException(node, 'Invalid file name.') interface = parse(file, self.root, True, name, self.parse_level + 1) self.interfaces[name] = interface def visit_ImportFrom(self, node: ast.ImportFrom): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') module = node.module or '' components = module.split('.') if not self.parse_further_interfaces: return if components == interfaces.VYPER_INTERFACES: for alias in node.names: name = alias.name if name == interfaces.ERC20: self.contracts[name] = VyperContract(name, interfaces.ERC20_TYPE, None) elif name == interfaces.ERC721: self.contracts[name] = VyperContract(name, interfaces.ERC721_TYPE, None) else: assert False return if node.level == 0: path = os.path.join(self.root or '', *components) else: path = self.path for _ in range(node.level): path = os.path.dirname(path) path = os.path.join(path, *components) files = {} for alias in node.names: name = alias.name interface_path = os.path.join(path, f'{name}.vy') files[interface_path] = name for file, name in files.items(): if name in [names.SELF, names.LOG, names.LEMMA, *names.ENV_VARIABLES]: raise UnsupportedException(node, 'Invalid file name.') interface = parse(file, self.root, True, name, self.parse_level + 1) self.interfaces[name] = interface def visit_StructDef(self, node: ast.StructDef): vyper_type = self.type_builder.build(node) assert isinstance(vyper_type, StructType) struct = VyperStruct(node.name, vyper_type, node) self.structs[struct.name] = struct def visit_EventDef(self, node: ast.EventDef): vyper_type = self.type_builder.build(node) if isinstance(vyper_type, EventType): event = VyperEvent(node.name, vyper_type) self.events[node.name] = event def visit_FunctionStub(self, node: ast.FunctionStub): # A function stub on the top-level is a resource declaration self._check_no_local_spec() name, is_derived = Resource.get_name_and_derived_flag(node) if name in self.resources or name in names.SPECIAL_RESOURCES: raise InvalidProgramException(node, 'duplicate.resource') vyper_type = self.type_builder.build(node) if isinstance(vyper_type, ResourceType): if is_derived: resource = Resource(vyper_type, node, self.path, node.returns) else: resource = Resource(vyper_type, node, self.path) self.resources[name] = resource def visit_ContractDef(self, node: ast.ContractDef): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') vyper_type = self.type_builder.build(node) if isinstance(vyper_type, ContractType): contract = VyperContract(node.name, vyper_type, node) self.contracts[contract.name] = contract def visit_AnnAssign(self, node: ast.AnnAssign): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') # No local specs are allowed before contract state variables self._check_no_local_spec() variable_name = node.target.id if variable_name == names.IMPLEMENTS: interface_name = node.annotation.id if interface_name not in [interfaces.ERC20, interfaces.ERC721] or interface_name in self.interfaces: interface_type = InterfaceType(interface_name) self.implements.append(interface_type) elif interface_name in [interfaces.ERC20, interfaces.ERC721]: interface_type = InterfaceType(interface_name) self.additional_implements.append(interface_type) # We ignore the units declarations elif variable_name != names.UNITS: variable_type = self.type_builder.build(node.annotation) if isinstance(variable_type, EventType): event = VyperEvent(variable_name, variable_type) self.events[variable_name] = event else: self.field_types[variable_name] = variable_type def visit_Assign(self, node: ast.Assign): # This is for invariants and postconditions which get translated to # assignments during preprocessing. name = node.target.id if name != names.GENERAL_POSTCONDITION and self.is_preserves: msg = f"Only general postconditions are allowed in preserves. ({name} is not allowed)" raise InvalidProgramException(node, 'invalid.preserves', msg) with switch(name) as case: if case(names.CONFIG): if isinstance(node.value, ast.Name): options = [node.value.id] elif isinstance(node.value, ast.Tuple): options = [n.id for n in node.value.elements] for option in options: if option not in names.CONFIG_OPTIONS: msg = f"Option {option} is invalid." raise InvalidProgramException(node, 'invalid.config.option', msg) if self.config is not None: raise InvalidProgramException(node, 'invalid.config', 'The "config" is specified multiple times.') self.config = Config(options) elif case(names.INTERFACE): self._check_no_local_spec() self._check_no_ghost_function() self._check_no_lemmas() self.is_interface = True elif case(names.INVARIANT): # No local specifications allowed before invariants self._check_no_local_spec() self.local_state_invariants.append(node.value) elif case(names.INTER_CONTRACT_INVARIANTS): # No local specifications allowed before inter contract invariants self._check_no_local_spec() self.inter_contract_invariants.append(node.value) elif case(names.GENERAL_POSTCONDITION): # No local specifications allowed before general postconditions self._check_no_local_spec() if self.is_preserves: self.transitive_postconditions.append(node.value) else: self.general_postconditions.append(node.value) elif case(names.GENERAL_CHECK): # No local specifications allowed before general check self._check_no_local_spec() self.general_checks.append(node.value) elif case(names.POSTCONDITION): self.postconditions.append(node.value) elif case(names.PRECONDITION): self.preconditions.append(node.value) elif case(names.CHECK): self.checks.append(node.value) elif case(names.CALLER_PRIVATE): # No local specifications allowed before caller private self._check_no_local_spec() self.caller_private.append(node.value) elif case(names.PERFORMS): self.performs.append(node.value) else: assert False def visit_If(self, node: ast.If): # This is a preserves clause, since we replace all preserves clauses with if statements # when preprocessing if self.is_preserves: raise InvalidProgramException(node, 'preserves.in.preserves') self.is_preserves = True for stmt in node.body: self.visit(stmt) self.is_preserves = False def _arg(self, node: ast.Arg) -> VyperVar: arg_name = node.name arg_type = self.type_builder.build(node.annotation) return VyperVar(arg_name, arg_type, node) def visit_Ghost(self, node: ast.Ghost): for func in node.body: def check_ghost(cond): if not cond: raise InvalidProgramException(func, 'invalid.ghost') check_ghost(isinstance(func, ast.FunctionDef)) assert isinstance(func, ast.FunctionDef) check_ghost(len(func.body) == 1) func_body = func.body[0] check_ghost(isinstance(func_body, ast.ExprStmt)) assert isinstance(func_body, ast.ExprStmt) check_ghost(func.returns) decorators = [dec.name for dec in func.decorators] check_ghost(len(decorators) == len(func.decorators)) name = func.name args = {arg.name: self._arg(arg) for arg in func.args} arg_types = [arg.type for arg in args.values()] return_type = None if func.returns is None else self.type_builder.build(func.returns) vyper_type = FunctionType(arg_types, return_type) if names.IMPLEMENTS in decorators: check_ghost(not self.is_interface) check_ghost(len(decorators) == 1) ghost_functions = self.ghost_function_implementations else: check_ghost(self.is_interface) check_ghost(not decorators) check_ghost(isinstance(func_body.value, ast.Ellipsis)) ghost_functions = self.ghost_functions if name in ghost_functions: raise InvalidProgramException(func, 'duplicate.ghost') ghost_functions[name] = GhostFunction(name, args, vyper_type, func, self.path) def visit_FunctionDef(self, node: ast.FunctionDef): args = {arg.name: self._arg(arg) for arg in node.args} defaults = {arg.name: arg.default for arg in node.args} arg_types = [arg.type for arg in args.values()] return_type = None if node.returns is None else self.type_builder.build(node.returns) vyper_type = FunctionType(arg_types, return_type) decs = node.decorators loop_invariant_transformer = LoopInvariantTransformer() loop_invariant_transformer.visit(node) function = VyperFunction(node.name, self.function_counter, args, defaults, vyper_type, self.postconditions, self.preconditions, self.checks, loop_invariant_transformer.loop_invariants, self.performs, decs, node) if node.is_lemma: if node.decorators: decorator = node.decorators[0] if len(node.decorators) > 1 or decorator.name != names.INTERPRETED_DECORATOR: raise InvalidProgramException(decorator, 'invalid.lemma', f'A lemma can have only one decorator: {names.INTERPRETED_DECORATOR}') if not decorator.is_ghost_code: raise InvalidProgramException(decorator, 'invalid.lemma', 'The decorator of a lemma must be ghost code') if vyper_type.return_type is not None: raise InvalidProgramException(node, 'invalid.lemma', 'A lemma cannot have a return type') if node.name in self.lemmas: raise InvalidProgramException(node, 'duplicate.lemma') if self.is_interface: raise InvalidProgramException(node, 'invalid.lemma', 'Lemmas are not allowed in interfaces') self.lemmas[node.name] = function else: for decorator in node.decorators: if decorator.is_ghost_code and decorator.name != names.PURE: raise InvalidProgramException(decorator, 'invalid.ghost.code') self.functions[node.name] = function self.function_counter += 1 # Reset local specs self.postconditions = [] self.preconditions = [] self.checks = [] self.performs = [] class LoopInvariantTransformer(NodeTransformer): """ Replaces all constants in the AST by their value. """ def __init__(self): self._last_loop: Union[ast.For, None] = None self._possible_loop_invariant_nodes: List[ast.Assign] = [] self.loop_invariants: Dict[ast.For, List[ast.Expr]] = {} @contextmanager def _in_loop_scope(self, node: ast.For): possible_loop_invariant_nodes = self._possible_loop_invariant_nodes last_loop = self._last_loop self._last_loop = node yield self._possible_loop_invariant_nodes = possible_loop_invariant_nodes self._last_loop = last_loop def visit_Assign(self, node: ast.Assign): if node.is_ghost_code: if isinstance(node.target, ast.Name) and node.target.id == names.INVARIANT: if self._last_loop and node in self._possible_loop_invariant_nodes: self.loop_invariants.setdefault(self._last_loop, []).append(node.value) else: raise InvalidProgramException(node, 'invalid.loop.invariant', 'You may only write loop invariants at beginning in loops') return None return node def visit_For(self, node: ast.For): with self._in_loop_scope(node): self._possible_loop_invariant_nodes = [] for n in node.body: if isinstance(n, ast.Assign) and n.is_ghost_code and n.target.id == names.INVARIANT: self._possible_loop_invariant_nodes.append(n) else: break return self.generic_visit(node)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/parser.py
parser.py
from typing import Dict, Tuple """Conversion rules from Silver level errors to 2vyper errors.""" Rule = Dict[Tuple[str, str], Tuple[str, str]] def combine(first: Rule, second: Rule) -> Rule: """ Combines `first` and `second` to produce a rule as if we first apply `first` and then apply `second` to its result. """ res = first.copy() for k, v in first.items(): # If the result of the first mapping is an input to the second mapping, # do the mapping if v in second: res[k] = second[v] # For all keys which are not mentioned in the first mapping, add the second # mapping for k, v in second.items(): if k not in res: res[k] = v return res INVARIANT_FAIL = { ('assert.failed', 'assertion.false'): ('invariant.violated', 'assertion.false'), ('assert.failed', 'division.by.zero'): ('invariant.not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('invariant.not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('invariant.not.wellformed', 'seq.index.negative') } LOOP_INVARIANT_BASE_FAIL = { ('assert.failed', 'assertion.false'): ('loop.invariant.not.established', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('loop.invariant.not.established', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('loop.invariant.not.established', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative') } LOOP_INVARIANT_STEP_FAIL = { ('assert.failed', 'assertion.false'): ('loop.invariant.not.preserved', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('loop.invariant.not.preserved', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('loop.invariant.not.preserved', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative') } POSTCONDITION_FAIL = { ('assert.failed', 'assertion.false'): ('postcondition.violated', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('postcondition.violated', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('postcondition.violated', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative') } PRECONDITION_FAIL = { ('assert.failed', 'assertion.false'): ('precondition.violated', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('precondition.violated', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('precondition.violated', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative') } INTERFACE_POSTCONDITION_FAIL = { ('assert.failed', 'assertion.false'): ('postcondition.not.implemented', 'assertion.false') } LEMMA_FAIL = { ('postcondition.violated', 'assertion.false'): ('lemma.step.invalid', 'assertion.false'), ('application.precondition', 'assertion.false'): ('lemma.application.invalid', 'assertion.false') } CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('check.violated', 'assertion.false'), ('assert.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative') } CALL_INVARIANT_FAIL = { ('assert.failed', 'assertion.false'): ('call.invariant', 'assertion.false') } DURING_CALL_INVARIANT_FAIL = { ('assert.failed', 'assertion.false'): ('during.call.invariant', 'assertion.false') } CALL_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('call.check', 'assertion.false') } CALLER_PRIVATE_FAIL = { ('assert.failed', 'assertion.false'): ('caller.private.violated', 'assertion.false') } PRIVATE_CALL_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('private.call.check', 'assertion.false') } CALL_LEAK_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('call.leakcheck', 'allocation.leaked') } INHALE_INVARIANT_FAIL = { ('inhale.failed', 'division.by.zero'): ('invariant.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('invariant.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('invariant.not.wellformed', 'seq.index.negative') } INHALE_CALLER_PRIVATE_FAIL = { ('inhale.failed', 'division.by.zero'): ('caller.private.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('caller.private.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('caller.private.not.wellformed', 'seq.index.negative') } INHALE_LOOP_INVARIANT_FAIL = { ('inhale.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative') } INHALE_POSTCONDITION_FAIL = { ('inhale.failed', 'division.by.zero'): ('postcondition.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('postcondition.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('postcondition.not.wellformed', 'seq.index.negative') } INHALE_PRECONDITION_FAIL = { ('inhale.failed', 'division.by.zero'): ('precondition.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('precondition.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('precondition.not.wellformed', 'seq.index.negative') } INHALE_INTERFACE_FAIL = { ('inhale.failed', 'division.by.zero'): ('interface.postcondition.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('interface.postcondition.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('interface.postcondition.not.wellformed', 'seq.index.negative') } INVARIANT_TRANSITIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('invariant.not.wellformed', 'transitivity.violated') } INVARIANT_REFLEXIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('invariant.not.wellformed', 'reflexivity.violated') } POSTCONDITION_TRANSITIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('postcondition.not.wellformed', 'transitivity.violated') } POSTCONDITION_REFLEXIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('postcondition.not.wellformed', 'reflexivity.violated') } POSTCONDITION_CONSTANT_BALANCE = { ('assert.failed', 'assertion.false'): ('postcondition.not.wellformed', 'constant.balance') } PRECONDITION_IMPLEMENTS_INTERFACE = { ('application.precondition', 'assertion.false'): ('application.precondition', 'not.implements.interface') } INTERFACE_RESOURCE_PERFORMS = { ('assert.failed', 'assertion.false'): ('interface.resource', 'resource.address.self') } REALLOCATE_FAIL_INSUFFICIENT_FUNDS = { ('assert.failed', 'assertion.false'): ('reallocate.failed', 'insufficient.funds') } CREATE_FAIL_NOT_A_CREATOR = { ('assert.failed', 'assertion.false'): ('create.failed', 'not.a.creator') } DESTROY_FAIL_INSUFFICIENT_FUNDS = { ('assert.failed', 'assertion.false'): ('destroy.failed', 'insufficient.funds') } EXCHANGE_FAIL_NO_OFFER = { ('assert.failed', 'assertion.false'): ('exchange.failed', 'no.offer') } EXCHANGE_FAIL_INSUFFICIENT_FUNDS = { ('assert.failed', 'assertion.false'): ('exchange.failed', 'insufficient.funds') } INJECTIVITY_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('$operation.failed', 'offer.not.injective') } NO_PERFORMS_FAIL = { ('exhale.failed', 'insufficient.permission'): ('$operation.failed', 'no.performs') } NOT_TRUSTED_FAIL = { ('assert.failed', 'assertion.false'): ('$operation.failed', 'not.trusted') } REALLOCATE_FAIL = { ('$operation.failed', 'no.performs'): ('reallocate.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('reallocate.failed', 'not.trusted') } CREATE_FAIL = { ('$operation.failed', 'offer.not.injective'): ('create.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('create.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('create.failed', 'not.trusted') } DESTROY_FAIL = { ('$operation.failed', 'offer.not.injective'): ('destroy.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('destroy.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('destroy.failed', 'not.trusted') } EXCHANGE_FAIL = { ('$operation.failed', 'no.performs'): ('exchange.failed', 'no.performs') } PAYABLE_FAIL = { ('$operation.failed', 'no.performs'): ('payable.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('payable.failed', 'not.trusted') } PAYOUT_FAIL = { ('$operation.failed', 'no.performs'): ('payout.failed', 'no.performs') } OFFER_FAIL = { ('$operation.failed', 'offer.not.injective'): ('offer.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('offer.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('offer.failed', 'not.trusted') } REVOKE_FAIL = { ('$operation.failed', 'offer.not.injective'): ('revoke.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('revoke.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('revoke.failed', 'not.trusted') } TRUST_FAIL = { ('$operation.failed', 'offer.not.injective'): ('trust.failed', 'trust.not.injective'), ('$operation.failed', 'no.performs'): ('trust.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('trust.failed', 'not.trusted') } ALLOCATE_UNTRACKED_FAIL = { ('$operation.failed', 'no.performs'): ('allocate.untracked.failed', 'no.performs') } ALLOCATION_LEAK_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('leakcheck.failed', 'allocation.leaked') } PERFORMS_LEAK_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('performs.leakcheck.failed', 'performs.leaked') } UNDERLYING_ADDRESS_SELF_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.address.self') } UNDERLYING_ADDRESS_CONSTANT_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.address.constant') } UNDERLYING_ADDRESS_TRUST_NO_ONE_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.address.trust') } UNDERLYING_RESOURCE_NO_OFFERS_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.resource.offers') } UNDERLYING_RESOURCE_NEQ_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.resource.eq') } PURE_FUNCTION_FAIL = { ('application.precondition', 'assertion.false'): ('function.failed', 'function.revert') }
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/rules.py
rules.py
from typing import Any, Dict, List, Optional from twovyper.ast import ast_nodes as ast from twovyper.viper.typedefs import Node, AbstractSourcePosition from twovyper.viper.typedefs import AbstractVerificationError, AbstractErrorReason from twovyper.verification.messages import ERRORS, REASONS from twovyper.verification.model import Model, ModelTransformation from twovyper.verification.rules import Rule """Wrappers for Scala error objects.""" class Position: """Wrapper around ``AbstractSourcePosition``.""" def __init__(self, position: AbstractSourcePosition): self._position = position if hasattr(position, 'id'): self.node_id = position.id() else: self.node_id = None @property def file_name(self) -> str: """Return ``file``.""" return str(self._position.file()) @property def line(self) -> int: """Return ``start.line``.""" return self._position.line() @property def column(self) -> int: """Return ``start.column``.""" return self._position.column() def __str__(self) -> str: return str(self._position) class Via: def __init__(self, origin: str, position: AbstractSourcePosition): self.origin = origin self.position = position class ErrorInfo: def __init__(self, node: ast.Node, vias: List[Via], model_transformation: Optional[ModelTransformation], values: Dict[str, Any]): self.node = node self.vias = vias self.model_transformation = model_transformation self.values = values def __getattribute__(self, name: str) -> Any: try: return super().__getattribute__(name) except AttributeError: try: return self.values.get(name) except KeyError: raise AttributeError(f"'ErrorInfo' object has no attribute '{name}'") class Reason: """Wrapper around ``AbstractErrorReason``.""" def __init__(self, reason_id: str, reason: AbstractErrorReason, reason_info: ErrorInfo): self._reason = reason self.identifier = reason_id self._reason_info = reason_info self.offending_node = reason.offendingNode() self.position = Position(self.offending_node.pos()) def __str__(self) -> str: """ Creates a string representation of this reason including a reference to the Python AST node that caused it. """ return REASONS[self.identifier](self._reason_info) class Error: """Wrapper around ``AbstractVerificationError``.""" def __init__(self, error: AbstractVerificationError, rules: Rule, reason_item: ErrorInfo, error_item: ErrorInfo, jvm) -> None: # Translate error id. viper_reason = error.reason() error_id = error.id() reason_id = viper_reason.id() # This error might come from a precondition fail of the Viper function "$pure$return_get" which has no position. # if the reason_item could not be found due to this, use the error_item instead. if error_id == 'application.precondition' and reason_item is None: reason_item = error_item key = error_id, reason_id if key in rules: error_id, reason_id = rules[key] # Construct object. self._error = error self.identifier = error_id self._error_info = error_item self.reason = Reason(reason_id, viper_reason, reason_item) if error.counterexample().isDefined(): self.model = Model(error, jvm, error_item.model_transformation) else: self._model = None self.position = Position(error.pos()) def pos(self) -> AbstractSourcePosition: """ Get position. """ return self._error.pos() @property def full_id(self) -> str: """ Full error identifier. """ return f"{self.identifier}:{self.reason.identifier}" @property def offending_node(self) -> Node: """ AST node where the error occurred. """ return self._error.offendingNode() @property def readable_message(self) -> str: """ Readable error message. """ return self._error.readableMessage() @property def position_string(self) -> str: """ Full error position as a string. """ vias = self._error_info.vias or self.reason._reason_info.vias or [] vias_string = "".join(f", via {via.origin} at {via.position}" for via in vias) return f"{self.position}{vias_string}" @property def message(self) -> str: """ Human readable error message. """ return ERRORS[self.identifier](self._error_info) def __str__(self) -> str: return self.string(False, False) def string(self, ide_mode: bool, include_model: bool = False) -> str: """ Format error. Creates an appropriate error message (referring to the responsible Python code) for the given Viper error. The error format is either optimized for human readability or uses the same format as IDE-mode Viper error messages, depending on the first parameter. The second parameter determines if the message may show Viper-level error explanations if no Python-level explanation is available. """ assert not (ide_mode and include_model) if ide_mode: file_name = self.position.file_name line = self.position.line col = self.position.column msg = self.message reason = self.reason return f"{file_name}:{line}:{col}: error: {msg} {reason}" else: msg = self.message reason = self.reason pos = self.position_string error_msg = f"{msg} {reason} ({pos})" if include_model and self.model: return f"{error_msg}\nCounterexample:\n{self.model}" else: return error_msg
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/error.py
error.py
from uuid import uuid1 from typing import Any, Dict, List, Optional from twovyper.utils import unique from twovyper.viper.jvmaccess import JVM from twovyper.viper.typedefs import Node, AbstractSourcePosition from twovyper.viper.typedefs import AbstractVerificationError from twovyper.verification.error import Error, ErrorInfo from twovyper.verification.rules import Rule """Error handling state is stored in singleton ``manager``.""" class ErrorManager: """A singleton object that stores the state needed for error handling.""" def __init__(self) -> None: self._items: Dict[str, ErrorInfo] = {} self._conversion_rules: Dict[str, Rule] = {} def add_error_information(self, error_info: ErrorInfo, conversion_rules: Rule) -> str: """Add error information to state.""" item_id = str(uuid1()) assert item_id not in self._items self._items[item_id] = error_info if conversion_rules is not None: self._conversion_rules[item_id] = conversion_rules return item_id def clear(self) -> None: """Clear all state.""" self._items.clear() self._conversion_rules.clear() def convert( self, errors: List[AbstractVerificationError], jvm: Optional[JVM]) -> List[Error]: """Convert Viper errors into 2vyper errors. It does that by wrapping in ``Error`` subclasses. """ def eq(e1: Error, e2: Error) -> bool: ide = e1.string(True, False) == e2.string(True, False) normal = e1.string(False, False) == e2.string(False, False) return ide and normal return unique(eq, [self._convert_error(error, jvm) for error in errors]) def get_vias(self, node_id: str) -> List[Any]: """Get via information for the given ``node_id``.""" item = self._items[node_id] return item.vias def _get_error_info(self, pos: AbstractSourcePosition) -> Optional[ErrorInfo]: if hasattr(pos, 'id'): node_id = pos.id() return self._items[node_id] return None def _get_conversion_rules( self, position: AbstractSourcePosition) -> Optional[Rule]: if hasattr(position, 'id'): node_id = position.id() return self._conversion_rules.get(node_id) else: return None def _try_get_rules_workaround( self, node: Node, jvm: Optional[JVM]) -> Optional[Rule]: """Try to extract rules out of ``node``. Due to optimizations, Silicon sometimes returns not the correct offending node, but an And that contains it. This method tries to work around this problem. .. todo:: In the long term we should discuss with Malte how to solve this problem properly. """ rules = self._get_conversion_rules(node.pos()) if rules or not jvm: return rules if (isinstance(node, jvm.viper.silver.ast.And) or isinstance(node, jvm.viper.silver.ast.Implies)): return (self._get_conversion_rules(node.left().pos()) or self._get_conversion_rules(node.right().pos()) or self._try_get_rules_workaround(node.left(), jvm) or self._try_get_rules_workaround(node.right(), jvm)) return def transformError(self, error: AbstractVerificationError) -> AbstractVerificationError: """ Transform silver error to a fixpoint. """ old_error = None while old_error != error: old_error = error error = error.transformedError() return error def _convert_error( self, error: AbstractVerificationError, jvm: Optional[JVM]) -> Error: error = self.transformError(error) reason_pos = error.reason().offendingNode().pos() reason_item = self._get_error_info(reason_pos) position = error.pos() rules = self._try_get_rules_workaround( error.offendingNode(), jvm) if rules is None: rules = self._try_get_rules_workaround( error.reason().offendingNode(), jvm) if rules is None: rules = {} error_item = self._get_error_info(position) return Error(error, rules, reason_item, error_item, jvm) manager = ErrorManager()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/manager.py
manager.py
from collections import OrderedDict from typing import Any, Dict, List, Optional, Tuple from twovyper.utils import seq_to_list from twovyper.ast import types from twovyper.ast.arithmetic import Decimal from twovyper.ast.types import ArrayType, DecimalType, MapType, PrimitiveType, StructType, VyperType from twovyper.viper.jvmaccess import JVM from twovyper.viper.typedefs import AbstractVerificationError, ModelEntry, Sort, Term ModelTransformation = Tuple[Dict[str, str], Dict[str, VyperType]] class Model: def __init__(self, error: AbstractVerificationError, jvm: JVM, transform: Optional[ModelTransformation]): ce = error.counterexample().get() scala_model = ce.model() self._store = ce.internalStore() self._names = transform and transform[0] self._types = transform and transform[1] self._jvm = jvm model = OrderedDict() for entry in ScalaIterableWrapper(scala_model.entries()): self.extract_model_entry(entry, model) self._model = model self.values() def extract_model_entry(self, entry: ModelEntry, target: Dict[str, Any]): name = str(entry._1()) value = entry._2() if isinstance(value, self._jvm.viper.silver.verifier.SingleEntry): target[name] = str(value.value()) else: entry_val = OrderedDict() for option in ScalaIterableWrapper(value.options()): option_value = option._2() option_key = () for option_key_entry in ScalaIterableWrapper(option._1()): option_key += (str(option_key_entry),) entry_val[option_key] = str(option_value) entry_val['else'] = str(value.els()) target[name] = entry_val def values(self) -> Dict[str, str]: res = {} if self._model and self._store and self._names: store_map = self._store.values() keys = seq_to_list(store_map.keys()) for name_entry in keys: name = str(name_entry) term = store_map.get(name_entry).get() try: value = evaluate_term(self._jvm, term, self._model) except NoFittingValueException: continue transformation = self.transform_variable(name, value, term.sort()) if transformation: name, value = transformation res[name] = value return res def transform_variable(self, name: str, value: str, sort: Sort) -> Optional[Tuple[str, str]]: if name in self._names and name in self._types: vy_name = self._names[name] vy_type = self._types[name] value = str(value) return vy_name, self.transform_value(value, vy_type, sort) return None def parse_int(self, val: str) -> int: if val.startswith('(-') and val.endswith(')'): return - int(val[2:-1]) return int(val) def transform_value(self, value: str, vy_type: VyperType, sort: Sort) -> str: if isinstance(sort, self._jvm.viper.silicon.state.terms.sorts.UserSort) and str(sort.id()) == '$Int': value = get_func_value(self._model, '$unwrap<Int>', (value,)) if isinstance(vy_type, PrimitiveType) and vy_type.name == 'bool': return value.capitalize() if isinstance(vy_type, DecimalType): value = self.parse_int(value) return str(Decimal[vy_type.number_of_digits](scaled_value=value)) elif vy_type == types.VYPER_ADDRESS: value = self.parse_int(value) return f'{value:#0{40}x}' elif isinstance(vy_type, PrimitiveType): # assume int value = self.parse_int(value) return str(value) elif isinstance(vy_type, ArrayType): res = OrderedDict() length = get_func_value(self._model, SEQ_LENGTH, (value,)) parsed_length = self.parse_int(length) if parsed_length > 0: index_func_name = SEQ_INDEX + "<{}>".format(translate_sort(self._jvm, sort.elementsSort())) indices, els_index = get_func_values(self._model, index_func_name, (value,)) int_type = PrimitiveType('int') for ((index,), val) in indices: converted_index = self.transform_value(index, int_type, self.translate_type_sort(int_type)) converted_value = self.transform_value(val, vy_type.element_type, sort.elementsSort()) res[str(converted_index)] = converted_value if els_index is not None: converted_value = self.transform_value(els_index, vy_type.element_type, sort.elementsSort()) res['_'] = converted_value return "[ {} ]: {}".format(', '.join(['{} -> {}'.format(k, v) for k, v in res.items()]), parsed_length) elif isinstance(vy_type, MapType): res = {} fname = '$map_get<{}>'.format(self.translate_type_name(vy_type.value_type)) keys, els_val = get_func_values(self._model, fname, (value,)) for ((key,), val) in keys: converted_key = self.transform_value(key, vy_type.key_type, self.translate_type_sort(vy_type.key_type)) converted_value = self.transform_value(val, vy_type.value_type, self.translate_type_sort(vy_type.value_type)) res[converted_key] = converted_value if els_val is not None: converted_value = self.transform_value(els_val, vy_type.value_type, self.translate_type_sort(vy_type.value_type)) res['_'] = converted_value return "{{ {} }}".format(', '.join(['{} -> {}'.format(k, v) for k, v in res.items()])) else: return value def translate_type_name(self, vy_type: VyperType) -> str: if isinstance(vy_type, MapType): return '$Map<{}~_{}>'.format(self.translate_type_name(vy_type.key_type), self.translate_type_name(vy_type.value_type)) if isinstance(vy_type, PrimitiveType) and vy_type.name == 'bool': return 'Bool' if isinstance(vy_type, PrimitiveType): return 'Int' if isinstance(vy_type, StructType): return '$Struct' if isinstance(vy_type, ArrayType): return 'Seq<{}>'.format(self.translate_type_name(vy_type.element_type)) raise Exception(vy_type) def translate_type_sort(self, vy_type: VyperType) -> Sort: terms = self._jvm.viper.silicon.state.terms Identifier = self._jvm.viper.silicon.state.SimpleIdentifier def get_sort_object(name): return getattr(getattr(terms, 'sorts$' + name + '$'), "MODULE$") def get_sort_class(name): return getattr(terms, 'sorts$' + name) if isinstance(vy_type, MapType): name = '$Map<{}~_>'.format(self.translate_type_name(vy_type.key_type), self.translate_type_name(vy_type.value_type)) return get_sort_class('UserSort')(Identifier(name)) if isinstance(vy_type, PrimitiveType) and vy_type.name == 'bool': return get_sort_object('Bool') if isinstance(vy_type, PrimitiveType): return get_sort_object('Int') if isinstance(vy_type, StructType): return get_sort_class('UserSort')(Identifier('$Struct')) if isinstance(vy_type, ArrayType): return get_sort_class('Seq')(self.translate_type_sort(vy_type.element_type)) raise Exception(vy_type) def __str__(self): return "\n".join(f" {name} = {value}" for name, value in sorted(self.values().items())) # The following code is mostly lifted from Nagini SNAP_TO = '$SortWrappers.' SEQ_LENGTH = 'seq_t_length<Int>' SEQ_INDEX = 'seq_t_index' class ScalaIteratorWrapper: def __init__(self, iterator): self.iterator = iterator def __next__(self): if self.iterator.hasNext(): return self.iterator.next() else: raise StopIteration class ScalaIterableWrapper: def __init__(self, iterable): self.iterable = iterable def __iter__(self): return ScalaIteratorWrapper(self.iterable.toIterator()) class NoFittingValueException(Exception): pass def get_func_value(model: Dict[str, Any], name: str, args: Tuple[str, ...]) -> str: args = tuple([' '.join(a.split()) for a in args]) entry = model[name] if args == () and isinstance(entry, str): return entry res = entry.get(args) if res is not None: return res return model[name].get('else') def get_func_values(model: Dict[str, Any], name: str, args: Tuple[str, ...]) -> Tuple[List[Tuple[List[str], str]], str]: args = tuple([' '.join(a.split()) for a in args]) options = [(k[len(args):], v) for k, v in model[name].items() if k != 'else' and k[:len(args)] == args] els= model[name].get('else') return options, els def get_parts(jvm: JVM, val: str) -> List[str]: parser = getattr(getattr(jvm.viper.silver.verifier, 'ModelParser$'), 'MODULE$') res = [] for part in ScalaIterableWrapper(parser.getApplication(val)): res.append(part) return res def translate_sort(jvm: JVM, s: Sort) -> str: terms = jvm.viper.silicon.state.terms def get_sort_object(name): return getattr(terms, 'sorts$' + name + '$') def get_sort_class(name): return getattr(terms, 'sorts$' + name) if isinstance(s, get_sort_class('Set')): return 'Set<{}>'.format(translate_sort(jvm, s.elementsSort())) if isinstance(s, get_sort_class('UserSort')): return '{}'.format(s.id()) elif isinstance(s, get_sort_object('Ref')): return '$Ref' elif isinstance(s, get_sort_object('Snap')): return '$Snap' elif isinstance(s, get_sort_object('Perm')): return '$Perm' elif isinstance(s, get_sort_class('Seq')): return 'Seq<{}>'.format(translate_sort(jvm, s.elementsSort())) else: return str(s) def evaluate_term(jvm: JVM, term: Term, model: Dict[str, Any]) -> str: if isinstance(term, getattr(jvm.viper.silicon.state.terms, 'Unit$')): return '$Snap.unit' if isinstance(term, jvm.viper.silicon.state.terms.IntLiteral): return str(term) if isinstance(term, jvm.viper.silicon.state.terms.BooleanLiteral): return str(term) if isinstance(term, jvm.viper.silicon.state.terms.Null): return model['$Ref.null'] if isinstance(term, jvm.viper.silicon.state.terms.Var): key = str(term) if key not in model: raise NoFittingValueException return model[key] elif isinstance(term, jvm.viper.silicon.state.terms.App): fname = str(term.applicable().id()) + '%limited' if fname not in model: fname = str(term.applicable().id()) if fname not in model: fname = fname.replace('[', '<').replace(']', '>') args = [] for arg in ScalaIterableWrapper(term.args()): args.append(evaluate_term(jvm, arg, model)) res = get_func_value(model, fname, tuple(args)) return res if isinstance(term, jvm.viper.silicon.state.terms.Combine): p0_val = evaluate_term(jvm, term.p0(), model) p1_val = evaluate_term(jvm, term.p1(), model) return '($Snap.combine ' + p0_val + ' ' + p1_val + ')' if isinstance(term, jvm.viper.silicon.state.terms.First): sub = evaluate_term(jvm, term.p(), model) if sub.startswith('($Snap.combine '): return get_parts(jvm, sub)[1] elif isinstance(term, jvm.viper.silicon.state.terms.Second): sub = evaluate_term(jvm, term.p(), model) if sub.startswith('($Snap.combine '): return get_parts(jvm, sub)[2] elif isinstance(term, jvm.viper.silicon.state.terms.SortWrapper): sub = evaluate_term(jvm, term.t(), model) from_sort_name = translate_sort(jvm, term.t().sort()) to_sort_name = translate_sort(jvm, term.to()) return get_func_value(model, SNAP_TO + from_sort_name + 'To' + to_sort_name, (sub,)) elif isinstance(term, jvm.viper.silicon.state.terms.PredicateLookup): lookup_func_name = '$PSF.lookup_' + term.predname() toSnapTree = getattr(jvm.viper.silicon.state.terms, 'toSnapTree$') obj = getattr(toSnapTree, 'MODULE$') snap = obj.apply(term.args()) psf_value = evaluate_term(jvm, term.psf(), model) snap_value = evaluate_term(jvm, snap, model) return get_func_value(model, lookup_func_name, (psf_value, snap_value)) raise Exception(str(term))
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/model.py
model.py
import abc import logging from enum import Enum from typing import Optional, Any from jpype import JPackage from twovyper import config from twovyper.utils import list_to_seq from twovyper.viper.typedefs import Program from twovyper.viper.jvmaccess import JVM from twovyper.verification.result import VerificationResult, Success, Failure class AbstractVerifier(abc.ABC): def __init__(self): self.jvm: Optional[JVM] = None self.silver: Optional[JPackage] = None @abc.abstractmethod def _initialize(self, jvm: JVM, file: str, get_model: bool = False): pass @abc.abstractmethod def verify(self, program: Program, jvm: JVM, filename: str, get_model: bool = False) -> VerificationResult: pass class Silicon(AbstractVerifier): """ Provides access to the Silicon verifier """ def __init__(self): super().__init__() self.silicon: Optional[Any] = None def _initialize(self, jvm: JVM, filename: str, get_model: bool = False): self.jvm = jvm self.silver = jvm.viper.silver if not jvm.is_known_class(jvm.viper.silicon.Silicon): raise Exception('Silicon backend not found on classpath.') self.silicon = jvm.viper.silicon.Silicon() args = [ '--z3Exe', config.z3_path, '--disableCatchingExceptions', *(['--counterexample=native'] if get_model else []), filename ] self.silicon.parseCommandLine(list_to_seq(args, jvm)) self.silicon.start() logging.info("Initialized Silicon.") def verify(self, program: Program, jvm: JVM, filename: str, get_model: bool = False) -> VerificationResult: """ Verifies the given program using Silicon """ if self.silicon is None: self._initialize(jvm, filename, get_model) assert self.silicon is not None result = self.silicon.verify(program) if isinstance(result, self.silver.verifier.Failure): logging.info("Silicon returned with: Failure.") it = result.errors().toIterator() errors = [] while it.hasNext(): errors += [it.next()] return Failure(errors, self.jvm) else: logging.info("Silicon returned with: Success.") return Success() def __del__(self): if self.silicon is not None: self.silicon.stop() class Carbon(AbstractVerifier): """ Provides access to the Carbon verifier """ def __init__(self): super().__init__() self.carbon: Optional[Any] = None def _initialize(self, jvm: JVM, filename: str, get_model: bool = False): self.silver = jvm.viper.silver if not jvm.is_known_class(jvm.viper.carbon.CarbonVerifier): raise Exception('Carbon backend not found on classpath.') if config.boogie_path is None: raise Exception('Boogie not found.') self.carbon = jvm.viper.carbon.CarbonVerifier() args = [ '--boogieExe', config.boogie_path, '--z3Exe', config.z3_path, *(['--counterexample=variables'] if get_model else []), filename ] self.carbon.parseCommandLine(list_to_seq(args, jvm)) self.carbon.start() self.jvm = jvm logging.info("Initialized Carbon.") def verify(self, program: Program, jvm: JVM, filename: str, get_model: bool = False) -> VerificationResult: """ Verifies the given program using Carbon """ if self.carbon is None: self._initialize(jvm, filename, get_model) assert self.carbon is not None result = self.carbon.verify(program) if isinstance(result, self.silver.verifier.Failure): logging.info("Carbon returned with: Failure.") it = result.errors().toIterator() errors = [] while it.hasNext(): errors += [it.next()] return Failure(errors) else: logging.info("Carbon returned with: Success.") return Success() def __del__(self): if self.carbon is not None: self.carbon.stop() class ViperVerifier(Enum): silicon = Silicon() carbon = Carbon()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/verifier.py
verifier.py
from twovyper.ast.text import pprint ERRORS = { 'assignment.failed': lambda i: "Assignment might fail.", 'call.failed': lambda i: "Method call might fail.", 'not.wellformed': lambda i: f"Function {i.function.name} might not be well-formed.", 'call.invariant': lambda i: f"An invariant might not hold before the call {pprint(i.node)}.", 'during.call.invariant': lambda i: f"An invariant might not hold during the call {pprint(i.node)}.", 'call.check': lambda i: f"A check might not hold before the call {pprint(i.node)}.", 'private.call.check': lambda i: f"A check might not hold in the private function.", 'call.precondition': lambda i: f"The precondition of function {pprint(i.node)} might not hold.", 'call.leakcheck': lambda i: f"The leak check for call {pprint(i.node)} might not hold.", 'application.precondition': lambda i: f"The precondition of function {pprint(i.node)} might not hold.", 'exhale.failed': lambda i: "Exhale might fail.", 'inhale.failed': lambda i: "Inhale might fail.", 'if.failed': lambda i: "Conditional statement might fail.", 'while.failed': lambda i: "While statement might fail.", 'assert.failed': lambda i: "Assert might fail.", 'postcondition.violated': lambda i: f"Postcondition of {i.function.name} might not hold.", 'postcondition.not.implemented': lambda i: f"Function {i.function.name} might not correctly implement an interface.", 'precondition.violated': lambda i: f"Precondition of {i.function.name} might not hold.", 'invariant.violated': lambda i: f"Invariant not preserved by {i.function.name}.", 'loop.invariant.not.established': lambda i: f"Loop invariant not established.", 'loop.invariant.not.preserved': lambda i: f"Loop invariant not preserved.", 'check.violated': lambda i: f"A check might not hold after the body of {i.function.name}.", 'caller.private.violated': lambda i: f"A caller private expression might got changed for another caller.", 'caller.private.not.wellformed': lambda i: f"Caller private {pprint(i.node)} might not be well-formed.", 'invariant.not.wellformed': lambda i: f"Invariant {pprint(i.node)} might not be well-formed.", 'loop.invariant.not.wellformed': lambda i: f"Loop invariant {pprint(i.node)} might not be well-formed.", 'postcondition.not.wellformed': lambda i: f"(General) Postcondition {pprint(i.node)} might not be well-formed.", 'precondition.not.wellformed': lambda i: f"Precondition {pprint(i.node)} might not be well-formed.", 'interface.postcondition.not.wellformed': lambda i: f"Postcondition of {pprint(i.node)} might not be well-formed.", 'reallocate.failed': lambda i: f"Reallocate might fail.", 'create.failed': lambda i: f"Create might fail.", 'destroy.failed': lambda i: f"Destroy might fail.", 'payable.failed': lambda i: f"The function {i.function.name} is payable and must be granted to allocate resources.", 'payout.failed': lambda i: f"Resource payout might fail.", 'offer.failed': lambda i: f"Offer might fail.", 'revoke.failed': lambda i: f"Revoke might fail.", 'exchange.failed': lambda i: f"Exchange {pprint(i.node)} might fail.", 'trust.failed': lambda i: f"Trust might fail.", 'allocate.untracked.failed': lambda i: f"The allocation of untracked resources might fail.", 'leakcheck.failed': lambda i: f"Leak check for resource {i.resource.name} might fail in {i.function.name}.", 'performs.leakcheck.failed': lambda i: f"Leak check for performs clauses might fail.", 'interface.resource': lambda i: f"The resource {i.resource.name} comes from an interface " f"and therefore its address must not be 'self'.", 'fold.failed': lambda i: "Fold might fail.", 'unfold.failed': lambda i: "Unfold might fail.", 'invariant.not.preserved': lambda i: "Loop invariant might not be preserved.", 'invariant.not.established': lambda i: "Loop invariant might not hold on entry.", 'function.not.wellformed': lambda i: "Function might not be well-formed.", 'predicate.not.wellformed': lambda i: "Predicate might not be well-formed.", 'function.failed': lambda i: f"The function call {pprint(i.node)} might not succeed.", 'lemma.step.invalid': lambda i: f"A step in the lemma {i.function.name} might not hold.", 'lemma.application.invalid': lambda i: f"Cannot apply lemma {i.function.name}.", 'derived.resource.invariant.failed': lambda i: f"A property of the derived resource {i.resource.name} might not hold.", } REASONS = { 'assertion.false': lambda i: f"Assertion {pprint(i.node)} might not hold.", 'transitivity.violated': lambda i: f"It might not be transitive.", 'reflexivity.violated': lambda i: f"It might not be reflexive.", 'constant.balance': lambda i: f"It might assume constant balance.", 'division.by.zero': lambda i: f"Divisor {pprint(i.node)} might be zero.", 'seq.index.length': lambda i: f"Index {pprint(i.node)} might exceed array length.", 'seq.index.negative': lambda i: f"Index {pprint(i.node)} might be negative.", 'not.implements.interface': lambda i: f"Receiver might not implement the interface.", 'insufficient.funds': lambda i: f"There might be insufficient allocated funds.", 'not.a.creator': lambda i: f"There might not be an appropriate creator resource.", 'not.trusted': lambda i: f"Message sender might not be trusted.", 'no.offer': lambda i: f"There might not be an appropriate offer.", 'no.performs': lambda i: f"The function might not be allowed to perform this operation.", 'offer.not.injective': lambda i: f"The offer might not be injective.", 'trust.not.injective': lambda i: f"Trust might not be injective.", 'allocation.leaked': lambda i: f"Some allocation might be leaked.", 'performs.leaked': lambda i: f"The function might not perform all required operations.", 'receiver.not.injective': lambda i: f"Receiver of {pprint(i.node)} might not be injective.", 'receiver.null': lambda i: f"Receiver of {pprint(i.node)} might be null.", 'negative.permission': lambda i: f"Fraction {pprint(i.node)} might be negative.", 'insufficient.permission': lambda i: f"There might be insufficient permission to access {pprint(i.node)}.", 'function.revert': lambda i: f"The function {i.function.name} might revert.", 'resource.address.self': lambda i: f"The address of the resource might be equal to 'self'.", 'underlying.address.self': lambda i: f"The address of the underlying resource might be equal to 'self'.", 'underlying.address.constant': lambda i: f"The address of the underlying resource might got changed after initially setting it.", 'underlying.address.trust': lambda i: f"The contract might trust others in the contract of the underlying resource.", 'underlying.resource.offers': lambda i: f"The contract might have open offers using the underlying resource.", 'underlying.resource.eq': lambda i: f"The derived resource {i.resource.name} and {i.other_resource.name} " f"might have the same underlying resource.", }
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/messages.py
messages.py
from jpype import JImplements, JOverride class ViperAST: """ Provides convenient access to the classes which constitute the Viper AST. All constructors convert Python lists to Scala sequences, Python ints to Scala BigInts, and wrap Scala Option types where necessary. """ def __init__(self, jvm): self.jvm = jvm self.java = jvm.java self.scala = jvm.scala self.ast = jvm.viper.silver.ast self.ast_extensions = jvm.viper.silver.sif def getobject(package, name): return getattr(getattr(package, name + '$'), 'MODULE$') def getconst(name): return getobject(self.ast, name) self.QPs = getobject(self.ast.utility, 'QuantifiedPermissions') self.AddOp = getconst('AddOp') self.AndOp = getconst('AndOp') self.DivOp = getconst('DivOp') self.FracOp = getconst('FracOp') self.GeOp = getconst('GeOp') self.GtOp = getconst('GtOp') self.ImpliesOp = getconst('ImpliesOp') self.IntPermMulOp = getconst('IntPermMulOp') self.LeOp = getconst('LeOp') self.LtOp = getconst('LtOp') self.ModOp = getconst('ModOp') self.MulOp = getconst('MulOp') self.NegOp = getconst('NegOp') self.NotOp = getconst('NotOp') self.OrOp = getconst('OrOp') self.PermAddOp = getconst('PermAddOp') self.PermDivOp = getconst('PermDivOp') self.SubOp = getconst('SubOp') self.NoPosition = getconst('NoPosition') self.NoInfo = getconst('NoInfo') self.NoTrafos = getconst('NoTrafos') self.Int = getconst('Int') self.Bool = getconst('Bool') self.Ref = getconst('Ref') self.Perm = getconst('Perm') self.MethodWithLabelsInScope = getobject(self.ast, 'MethodWithLabelsInScope') self.BigInt = getobject(self.scala.math, 'BigInt') self.None_ = getobject(self.scala, 'None') self.seq_types = set() def is_available(self) -> bool: """ Checks if the Viper AST is available, i.e., silver is on the Java classpath. """ return self.jvm.is_known_class(self.ast.Program) def is_extension_available(self) -> bool: """ Checks if the extended AST is available, i.e., the SIF AST extension is on the Java classpath. """ return self.jvm.is_known_class(self.ast_extensions.SIFReturnStmt) def empty_seq(self): return self.scala.collection.mutable.ListBuffer() def singleton_seq(self, element): result = self.scala.collection.mutable.ArraySeq(1) result.update(0, element) return result def append(self, list, to_append): if to_append is not None: lsttoappend = self.singleton_seq(to_append) list.append(lsttoappend) def to_seq(self, py_iterable): result = self.scala.collection.mutable.ArraySeq(len(py_iterable)) for index, value in enumerate(py_iterable): result.update(index, value) return result.toList() def to_list(self, seq): result = [] iterator = seq.toIterator() while iterator.hasNext(): result.append(iterator.next()) return result def to_map(self, dict): result = self.scala.collection.immutable.HashMap() for k, v in dict.items(): result = result.updated(k, v) return result def to_big_int(self, num: int): # Python ints might not fit into a C int, therefore we use a String num_str = str(num) return self.BigInt.apply(num_str) def Program(self, domains, fields, functions, predicates, methods, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Program(self.to_seq(domains), self.to_seq(fields), self.to_seq(functions), self.to_seq(predicates), self.to_seq(methods), self.to_seq([]), position, info, self.NoTrafos) def Function(self, name, args, type, pres, posts, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo body = self.scala.Some(body) if body is not None else self.None_ return self.ast.Function(name, self.to_seq(args), type, self.to_seq(pres), self.to_seq(posts), body, position, info, self.NoTrafos) def Method(self, name, args, returns, pres, posts, locals, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo if body is None: body_with_locals = self.None_ else: body_with_locals = self.scala.Some(self.Seqn(body, position, info, locals)) method = self.MethodWithLabelsInScope return method.apply(name, self.to_seq(args), self.to_seq(returns), self.to_seq(pres), self.to_seq(posts), body_with_locals, position, info, self.NoTrafos) def Field(self, name, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Field(name, type, position, info, self.NoTrafos) def Predicate(self, name, args, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo body = self.scala.Some(body) if body is not None else self.None_ return self.ast.Predicate(name, self.to_seq(args), body, position, info, self.NoTrafos) def PredicateAccess(self, args, pred_name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PredicateAccess(self.to_seq(args), pred_name, position, info, self.NoTrafos) def PredicateAccessPredicate(self, loc, perm, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PredicateAccessPredicate(loc, perm, position, info, self.NoTrafos) def Fold(self, predicate, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Fold(predicate, position, info, self.NoTrafos) def Unfold(self, predicate, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Unfold(predicate, position, info, self.NoTrafos) def Unfolding(self, predicate, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Unfolding(predicate, expr, position, info, self.NoTrafos) def SeqType(self, element_type): self.seq_types.add(element_type) return self.ast.SeqType(element_type) def SetType(self, element_type): return self.ast.SetType(element_type) def MultisetType(self, element_type): return self.ast.MultisetType(element_type) def Domain(self, name, functions, axioms, typevars, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Domain(name, self.to_seq(functions), self.to_seq(axioms), self.to_seq(typevars), position, info, self.NoTrafos) def DomainFunc(self, name, args, type, unique, domain_name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.DomainFunc(name, self.to_seq(args), type, unique, position, info, domain_name, self.NoTrafos) def DomainAxiom(self, name, expr, domain_name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NamedDomainAxiom(name, expr, position, info, domain_name, self.NoTrafos) def DomainType(self, name, type_vars_map, type_vars): map = self.to_map(type_vars_map) seq = self.to_seq(type_vars) return self.ast.DomainType(name, map, seq) def DomainFuncApp(self, func_name, args, type_passed, position, info, domain_name, type_var_map={}): position = position or self.NoPosition info = info or self.NoInfo type_passed_func = self.to_function0(type_passed) result = self.ast.DomainFuncApp(func_name, self.to_seq(args), self.to_map(type_var_map), position, info, type_passed_func, domain_name, self.NoTrafos) return result def TypeVar(self, name): return self.ast.TypeVar(name) def MethodCall(self, method_name, args, targets, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.MethodCall(method_name, self.to_seq(args), self.to_seq(targets), position, info, self.NoTrafos) def NewStmt(self, lhs, fields, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NewStmt(lhs, self.to_seq(fields), position, info, self.NoTrafos) def Label(self, name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Label(name, self.to_seq([]), position, info, self.NoTrafos) def Goto(self, name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Goto(name, position, info, self.NoTrafos) def Seqn(self, body, position=None, info=None, locals=[]): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Seqn(self.to_seq(body), self.to_seq(locals), position, info, self.NoTrafos) def LocalVarAssign(self, lhs, rhs, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LocalVarAssign(lhs, rhs, position, info, self.NoTrafos) def FieldAssign(self, lhs, rhs, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FieldAssign(lhs, rhs, position, info, self.NoTrafos) def FieldAccess(self, receiver, field, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FieldAccess(receiver, field, position, info, self.NoTrafos) def FieldAccessPredicate(self, fieldacc, perm, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FieldAccessPredicate(fieldacc, perm, position, info, self.NoTrafos) def Old(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Old(expr, position, info, self.NoTrafos) def LabelledOld(self, expr, label, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LabelledOld(expr, label, position, info, self.NoTrafos) def Inhale(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Inhale(expr, position, info, self.NoTrafos) def Exhale(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Exhale(expr, position, info, self.NoTrafos) def InhaleExhaleExp(self, inhale, exhale, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.InhaleExhaleExp(inhale, exhale, position, info, self.NoTrafos) def Assert(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Assert(expr, position, info, self.NoTrafos) def FullPerm(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FullPerm(position, info, self.NoTrafos) def NoPerm(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NoPerm(position, info, self.NoTrafos) def WildcardPerm(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.WildcardPerm(position, info, self.NoTrafos) def FractionalPerm(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FractionalPerm(left, right, position, info, self.NoTrafos) def CurrentPerm(self, location, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.CurrentPerm(location, position, info, self.NoTrafos) def ForPerm(self, variables, access, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ForPerm(self.to_seq(variables), access, body, position, info, self.NoTrafos) def PermMinus(self, exp, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermMinus(exp, position, info, self.NoTrafos) def PermAdd(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermAdd(left, right, position, info, self.NoTrafos) def PermSub(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermSub(left, right, position, info, self.NoTrafos) def PermMul(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermMul(left, right, position, info, self.NoTrafos) def IntPermMul(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.IntPermMul(left, right, position, info, self.NoTrafos) def PermDiv(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermDiv(left, right, position, info, self.NoTrafos) def PermLtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermLtCmp(left, right, position, info, self.NoTrafos) def PermLeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermLeCmp(left, right, position, info, self.NoTrafos) def PermGtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermGtCmp(left, right, position, info, self.NoTrafos) def PermGeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermGeCmp(left, right, position, info, self.NoTrafos) def Not(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Not(expr, position, info, self.NoTrafos) def Minus(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Minus(expr, position, info, self.NoTrafos) def CondExp(self, cond, then, els, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.CondExp(cond, then, els, position, info, self.NoTrafos) def EqCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EqCmp(left, right, position, info, self.NoTrafos) def NeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NeCmp(left, right, position, info, self.NoTrafos) def GtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.GtCmp(left, right, position, info, self.NoTrafos) def GeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.GeCmp(left, right, position, info, self.NoTrafos) def LtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LtCmp(left, right, position, info, self.NoTrafos) def LeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LeCmp(left, right, position, info, self.NoTrafos) def IntLit(self, num, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.IntLit(self.to_big_int(num), position, info, self.NoTrafos) def Implies(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Implies(left, right, position, info, self.NoTrafos) def FuncApp(self, name, args, position=None, info=None, type=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FuncApp(name, self.to_seq(args), position, info, type, self.NoTrafos) def ExplicitSeq(self, elems, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ExplicitSeq(self.to_seq(elems), position, info, self.NoTrafos) def ExplicitSet(self, elems, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ExplicitSet(self.to_seq(elems), position, info, self.NoTrafos) def ExplicitMultiset(self, elems, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ExplicitMultiset(self.to_seq(elems), position, info, self.NoTrafos) def EmptySeq(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EmptySeq(type, position, info, self.NoTrafos) def EmptySet(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EmptySet(type, position, info, self.NoTrafos) def EmptyMultiset(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EmptyMultiset(type, position, info, self.NoTrafos) def LocalVarDecl(self, name, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LocalVarDecl(name, type, position, info, self.NoTrafos) def LocalVar(self, name, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LocalVar(name, type, position, info, self.NoTrafos) def Result(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Result(type, position, info, self.NoTrafos) def AnySetContains(self, elem, s, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.AnySetContains(elem, s, position, info, self.NoTrafos) def AnySetUnion(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.AnySetUnion(left, right, position, info, self.NoTrafos) def AnySetSubset(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.AnySetSubset(left, right, position, info, self.NoTrafos) def SeqAppend(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqAppend(left, right, position, info, self.NoTrafos) def SeqContains(self, elem, s, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqContains(elem, s, position, info, self.NoTrafos) def SeqLength(self, s, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqLength(s, position, info, self.NoTrafos) def SeqIndex(self, s, ind, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqIndex(s, ind, position, info, self.NoTrafos) def SeqTake(self, s, end, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqTake(s, end, position, info, self.NoTrafos) def SeqDrop(self, s, end, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqDrop(s, end, position, info, self.NoTrafos) def SeqUpdate(self, s, ind, elem, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqUpdate(s, ind, elem, position, info, self.NoTrafos) def Add(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Add(left, right, position, info, self.NoTrafos) def Sub(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Sub(left, right, position, info, self.NoTrafos) def Mul(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Mul(left, right, position, info, self.NoTrafos) def Div(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Div(left, right, position, info, self.NoTrafos) def Mod(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Mod(left, right, position, info, self.NoTrafos) def And(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.And(left, right, position, info, self.NoTrafos) def Or(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Or(left, right, position, info, self.NoTrafos) def If(self, cond, thn, els, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo thn_seqn = self.Seqn(thn, position) els_seqn = self.Seqn(els, position) return self.ast.If(cond, thn_seqn, els_seqn, position, info, self.NoTrafos) def TrueLit(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.TrueLit(position, info, self.NoTrafos) def FalseLit(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FalseLit(position, info, self.NoTrafos) def NullLit(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NullLit(position, info, self.NoTrafos) def Forall(self, variables, triggers, exp, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo if not variables: return exp res = self.ast.Forall(self.to_seq(variables), self.to_seq(triggers), exp, position, info, self.NoTrafos) if res.isPure(): return res else: desugared = self.to_list(self.QPs.desugarSourceQuantifiedPermissionSyntax(res)) result = self.TrueLit(position, info) for qp in desugared: result = self.And(result, qp, position, info) return result def Exists(self, variables, triggers, exp, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo res = self.ast.Exists(self.to_seq(variables), self.to_seq(triggers), exp, position, info, self.NoTrafos) return res def Trigger(self, exps, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Trigger(self.to_seq(exps), position, info, self.NoTrafos) def While(self, cond, invariants, locals, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo body_with_locals = self.Seqn(body, position, info, locals) return self.ast.While(cond, self.to_seq(invariants), body_with_locals, position, info, self.NoTrafos) def Let(self, variable, exp, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Let(variable, exp, body, position, info, self.NoTrafos) def from_option(self, option): if option == self.None_: return None else: return option.get() def to_function0(self, value): @JImplements(self.jvm.scala.Function0) class Function0: @JOverride def apply(self): return value return Function0() def SimpleInfo(self, comments): return self.ast.SimpleInfo(self.to_seq(comments)) def ConsInfo(self, head, tail): return self.ast.ConsInfo(head, tail) def to_position(self, expr, id: str): path = self.java.nio.file.Paths.get(expr.file, []) start = self.ast.LineColumnPosition(expr.lineno, expr.col_offset) end = self.ast.LineColumnPosition(expr.end_lineno, expr.end_col_offset) end = self.scala.Some(end) return self.ast.IdentifierPosition(path, start, end, id) def is_heap_dependent(self, expr) -> bool: """ Checks if the given expression contains an access to a heap location. Does NOT check for calls to heap-dependent functions. """ for n in [expr] + self.to_list(expr.subnodes()): if isinstance(n, self.ast.LocationAccess): return True return False # SIF extension AST nodes def Low(self, expr, comparator: str = '', type_vars_map={}, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo comp = self.scala.Some(comparator) if comparator else self.None_ type_vars_map = self.to_map(type_vars_map) return self.ast_extensions.SIFLowExp(expr, comp, type_vars_map, position, info, self.NoTrafos) def LowEvent(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast_extensions.SIFLowEventExp(position, info, self.NoTrafos)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/ast.py
ast.py
from typing import List from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.types import PrimitiveType, BoundedType from twovyper.translation import helpers from twovyper.translation.abstract import CommonTranslator from twovyper.translation.context import Context from twovyper.utils import switch from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt from twovyper.vyper import is_compatible_version class ArithmeticTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST, no_reverts: bool = False): super().__init__(viper_ast) self.no_reverts = no_reverts self._unary_arithmetic_operations = { ast.UnaryArithmeticOperator.ADD: lambda o, pos: o, ast.UnaryArithmeticOperator.SUB: self.viper_ast.Minus } self._arithmetic_ops = { ast.ArithmeticOperator.ADD: self.viper_ast.Add, ast.ArithmeticOperator.SUB: self.viper_ast.Sub, ast.ArithmeticOperator.MUL: self.viper_ast.Mul, # Note that / and % in Vyper means truncating division ast.ArithmeticOperator.DIV: lambda l, r, pos: helpers.div(viper_ast, l, r, pos), ast.ArithmeticOperator.MOD: lambda l, r, pos: helpers.mod(viper_ast, l, r, pos), ast.ArithmeticOperator.POW: lambda l, r, pos: helpers.pow(viper_ast, l, r, pos), } self._wrapped_arithmetic_ops = { ast.ArithmeticOperator.ADD: self.viper_ast.Add, ast.ArithmeticOperator.SUB: self.viper_ast.Sub, ast.ArithmeticOperator.MUL: lambda l, r, pos: helpers.w_mul(viper_ast, l, r, pos), ast.ArithmeticOperator.DIV: lambda l, r, pos: helpers.w_div(viper_ast, l, r, pos), ast.ArithmeticOperator.MOD: lambda l, r, pos: helpers.w_mod(viper_ast, l, r, pos), ast.ArithmeticOperator.POW: lambda l, r, pos: helpers.pow(viper_ast, l, r, pos), } self.non_linear_ops = { ast.ArithmeticOperator.MUL, ast.ArithmeticOperator.DIV, ast.ArithmeticOperator.MOD } def is_wrapped(self, val): return hasattr(val, 'isSubtype') and val.isSubtype(helpers.wrapped_int_type(self.viper_ast)) def is_unwrapped(self, val): return hasattr(val, 'isSubtype') and val.isSubtype(self.viper_ast.Int) def unary_arithmetic_op(self, op: ast.UnaryArithmeticOperator, arg, otype: PrimitiveType, res: List[Stmt], ctx: Context, pos=None) -> Expr: result = self._unary_arithmetic_operations[op](arg, pos) # Unary negation can only overflow if one negates MIN_INT128 if types.is_bounded(otype): assert isinstance(otype, BoundedType) self.check_overflow(result, otype, res, ctx, pos) return result # Decimals are scaled integers, i.e. the decimal 2.3 is represented as the integer # 2.3 * 10^10 = 23000000000. For addition, subtraction, and modulo the same operations # as with integers can be used. For multiplication we need to divide out one of the # scaling factors while in division we need to multiply one in. def _decimal_mul(self, lhs, rhs, pos=None, info=None) -> Expr: scaling_factor = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) mult = self.viper_ast.Mul(lhs, rhs, pos) # In decimal multiplication we divide the end result by the scaling factor return helpers.div(self.viper_ast, mult, scaling_factor, pos, info) def _wrapped_decimal_mul(self, lhs, rhs, pos=None, info=None) -> Expr: scaling_factor = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) mult = helpers.w_mul(self.viper_ast, lhs, rhs, pos) uw_mult = helpers.w_unwrap(self.viper_ast, mult, pos) rescaled_mult = helpers.div(self.viper_ast, uw_mult, scaling_factor, pos, info) return helpers.w_wrap(self.viper_ast, rescaled_mult, pos) def _decimal_div(self, lhs, rhs, pos=None, info=None) -> Expr: scaling_factor = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) # In decimal division we first multiply the lhs by the scaling factor mult = self.viper_ast.Mul(lhs, scaling_factor, pos) return helpers.div(self.viper_ast, mult, rhs, pos, info) def _wrapped_decimal_div(self, lhs, rhs, pos=None, info=None) -> Expr: scaling_factor = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) uw_lhs = helpers.w_unwrap(self.viper_ast, lhs, pos) uw_mult = self.viper_ast.Mul(uw_lhs, scaling_factor, pos) mult = helpers.w_wrap(self.viper_ast, uw_mult, pos) return helpers.w_div(self.viper_ast, mult, rhs, pos, info) def arithmetic_op(self, lhs, op: ast.ArithmeticOperator, rhs, otype: PrimitiveType, res: List[Stmt], ctx: Context, pos=None) -> Expr: ast_op = ast.ArithmeticOperator left_is_wrapped = self.is_wrapped(lhs) right_is_wrapped = self.is_wrapped(rhs) if ctx.inside_interpreted: if left_is_wrapped: left_is_wrapped = False lhs = helpers.w_unwrap(self.viper_ast, lhs, pos) if right_is_wrapped: right_is_wrapped = False rhs = helpers.w_unwrap(self.viper_ast, rhs, pos) elif ctx.inside_lemma: if not left_is_wrapped: left_is_wrapped = True lhs = helpers.w_wrap(self.viper_ast, lhs, pos) if not right_is_wrapped: right_is_wrapped = True rhs = helpers.w_wrap(self.viper_ast, rhs, pos) with switch(op, otype) as case: from twovyper.utils import _ if (case(ast_op.DIV, _) or case(ast_op.MOD, _)) and not self.no_reverts: expr = rhs if right_is_wrapped: expr = helpers.w_unwrap(self.viper_ast, rhs, pos) cond = self.viper_ast.EqCmp(expr, self.viper_ast.IntLit(0, pos), pos) self.fail_if(cond, [], res, ctx, pos) if left_is_wrapped and right_is_wrapped: # Both are wrapped if case(ast_op.MUL, types.VYPER_DECIMAL): expr = self._wrapped_decimal_mul(lhs, rhs, pos) elif case(ast_op.DIV, types.VYPER_DECIMAL): expr = self._wrapped_decimal_div(lhs, rhs, pos) else: expr = self._wrapped_arithmetic_ops[op](lhs, rhs, pos) else: if case(ast_op.MUL, types.VYPER_DECIMAL): expr = self._decimal_mul(lhs, rhs, pos) elif case(ast_op.DIV, types.VYPER_DECIMAL): expr = self._decimal_div(lhs, rhs, pos) else: expr = self._arithmetic_ops[op](lhs, rhs, pos) if types.is_bounded(otype): assert isinstance(otype, BoundedType) if is_compatible_version('<=0.1.0-beta.17') and op == ast_op.POW: # In certain versions of Vyper there was no overflow check for POW. self.check_underflow(expr, otype, res, ctx, pos) else: self.check_under_overflow(expr, otype, res, ctx, pos) return expr # Overflows and underflow checks can be disabled with the config flag 'no_overflows'. # If it is not enabled, we revert if an overflow happens. Additionally, we set the overflows # variable to true, which is used for success(if_not=overflow). # # Note that we only treat 'arbitary' bounds due to limited bit size as overflows, # getting negative unsigned values results in a normal revert. def _set_overflow_flag(self, res: List[Stmt], pos=None): overflow = helpers.overflow_var(self.viper_ast, pos).localVar() true_lit = self.viper_ast.TrueLit(pos) res.append(self.viper_ast.LocalVarAssign(overflow, true_lit, pos)) def check_underflow(self, arg, otype: BoundedType, res: List[Stmt], ctx: Context, pos=None): lower = self.viper_ast.IntLit(otype.lower, pos) lt = self.viper_ast.LtCmp(arg, lower, pos) if types.is_unsigned(otype) and not self.no_reverts: self.fail_if(lt, [], res, ctx, pos) elif not self.no_reverts and not ctx.program.config.has_option(names.CONFIG_NO_OVERFLOWS): stmts = [] self._set_overflow_flag(stmts, pos) self.fail_if(lt, stmts, res, ctx, pos) def check_overflow(self, arg, otype: BoundedType, res: List[Stmt], ctx: Context, pos=None): upper = self.viper_ast.IntLit(otype.upper, pos) gt = self.viper_ast.GtCmp(arg, upper, pos) if not self.no_reverts and not ctx.program.config.has_option(names.CONFIG_NO_OVERFLOWS): stmts = [] self._set_overflow_flag(stmts, pos) self.fail_if(gt, stmts, res, ctx, pos) def check_under_overflow(self, arg, otype: BoundedType, res: List[Stmt], ctx: Context, pos=None): # For unsigned types we need to check over and underflow separately as we treat underflows # as normal reverts if types.is_unsigned(otype) and not self.no_reverts: self.check_underflow(arg, otype, res, ctx, pos) self.check_overflow(arg, otype, res, ctx, pos) elif not self.no_reverts and not ctx.program.config.has_option(names.CONFIG_NO_OVERFLOWS): # Checking for overflow and undeflow in the same if-condition is more efficient than # introducing two branches lower = self.viper_ast.IntLit(otype.lower, pos) upper = self.viper_ast.IntLit(otype.upper, pos) lt = self.viper_ast.LtCmp(arg, lower, pos) gt = self.viper_ast.GtCmp(arg, upper, pos) cond = self.viper_ast.Or(lt, gt, pos) stmts = [] self._set_overflow_flag(stmts, pos) self.fail_if(cond, stmts, res, ctx, pos)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/arithmetic.py
arithmetic.py
from contextlib import contextmanager from collections import ChainMap, defaultdict from typing import Dict, TYPE_CHECKING, List, Any, Optional, Tuple, Callable from twovyper.ast import names from twovyper.ast.ast_nodes import Expr, Node from twovyper.ast.nodes import VyperFunction, VyperProgram from twovyper.translation import mangled if TYPE_CHECKING: from twovyper.translation.variable import TranslatedVar from twovyper.translation import LocalVarSnapshot class Context: def __init__(self): self.program: Optional[VyperProgram] = None # The program whose code is currently being translated, i.e., a VyperProgram # normally, and a VyperInterface when we translate interface specifications. self.current_program: Optional[VyperProgram] = None self.options = None # The translated types of all fields self.field_types = {} # Invariants that are known to be true and therefore don't need to be checked self.unchecked_invariants: Optional[Callable[[], List[Expr]]] = None # Transitive postconditions that are known to be true and therefore don't need to be checked self.unchecked_transitive_postconditions: Optional[Callable[[], List[Expr]]] = None # Invariants for derived resources self.derived_resources_invariants: Optional[Callable[[Optional[Node]], List[Expr]]] = None self.function: Optional[VyperFunction] = None self.is_pure_function = False self.inline_function: Optional[VyperFunction] = None self.args = {} self.locals: Dict[str, TranslatedVar] = {} self.old_locals: Dict[str, TranslatedVar] = {} # The state which is currently regarded as 'present' self.current_state = {} # The state which is currently regarded as 'old' self.current_old_state = {} self.quantified_vars: Dict[str, TranslatedVar] = {} # The actual present, old, pre, and issued states self.present_state = {} self.old_state = {} self.pre_state = {} self.issued_state = {} self.self_address = None self._break_label_counter = -1 self._continue_label_counter = -1 self.break_label = None self.continue_label = None self.success_var: Optional[TranslatedVar] = None self.revert_label = None self.result_var: Optional[TranslatedVar] = None self.return_label = None self.inside_trigger = False self.inside_inline_analysis = False self.inline_function = None self.inside_lemma = False self.inside_interpreted = False self._local_var_counter = defaultdict(lambda: -1) self.new_local_vars = [] self.loop_arrays: Dict[str, Expr] = {} self.loop_indices: Dict[str, TranslatedVar] = {} self.event_vars: Dict[str, List[Any]] = {} # And-ed conditions which must be all true when an assignment is made in a pure translator. self.pure_conds: Optional[Expr] = None # List of all assignments to the result variable # The tuple consists of an expression which is the condition under which the assignment happened and # the index of the variable (since this is SSA like, the result_var has many indices) self.pure_returns: List[Tuple[Expr, int]] = [] # List of all assignments to the success variable # The tuple consists of an expression which is the condition under which the assignment happened and # the index of the variable (since this is SSA like, the success_var has many indices) self.pure_success: List[Tuple[Expr, int]] = [] # List of all break statements in a loop # The tuple consists of an expression which is the condition under which the break statement is reached and # the dict is a snapshot of the local variables at the moment of the break statement self.pure_continues: List[Tuple[Optional[Expr], LocalVarSnapshot]] = [] # List of all continue statements in a loop # The tuple consists of an expression which is the condition under which the continue statement is reached and # the dict is a snapshot of the local variables at the moment of the continue statement self.pure_breaks: List[Tuple[Optional[Expr], LocalVarSnapshot]] = [] self._pure_var_index_counter = 1 # It has to start at 2 self._quantified_var_counter = -1 self._inline_counter = -1 self._current_inline = -1 self.inline_vias = [] self.inside_interface_call = False self.inside_derived_resource_performs = False self.inside_performs_only_interface_call = False @property def current_function(self) -> Optional[VyperFunction]: return self.function if not self.inside_inline_analysis else self.inline_function @property def all_vars(self) -> ChainMap: return ChainMap(self.quantified_vars, self.current_state, self.locals, self.args) @property def self_type(self): return self.program.fields.type @property def self_var(self): """ The variable declaration to which `self` currently refers. """ return self.current_state[names.SELF] @property def old_self_var(self): """ The variable declaration to which `old(self)` currently refers. """ return self.current_old_state[names.SELF] @property def pre_self_var(self): """ The state of `self` before the function call. """ return self.pre_state[names.SELF] @property def issued_self_var(self): """ The state of `self` when issuing the transaction. """ return self.issued_state[names.SELF] @property def msg_var(self): return self.all_vars[names.MSG] @property def block_var(self): return self.all_vars[names.BLOCK] @property def chain_var(self): return self.all_vars[names.CHAIN] @property def tx_var(self): return self.all_vars[names.TX] def new_local_var_name(self, name: str) -> str: full_name = mangled.local_var_name(self.inline_prefix, name) self._local_var_counter[full_name] += 1 new_count = self._local_var_counter[full_name] if new_count == 0: return full_name else: return f'{full_name}${new_count}' def new_quantified_var_name(self) -> str: self._quantified_var_counter += 1 return f'$q{self._quantified_var_counter}' @property def inline_prefix(self) -> str: if self._current_inline == -1: return '' else: return f'i{self._current_inline}$' def next_pure_var_index(self) -> int: self._pure_var_index_counter += 1 return self._pure_var_index_counter def _next_break_label(self) -> str: self._break_label_counter += 1 return f'break_{self._break_label_counter}' def _next_continue_label(self) -> str: self._continue_label_counter += 1 return f'continue_{self._continue_label_counter}' @contextmanager def function_scope(self): """ Should be used in a ``with`` statement. Saves the current context state of a function, then clears it for the body of the ``with`` statement and restores the previous one in the end. """ function = self.function is_pure_function = self.is_pure_function args = self.args local_variables = self.locals old_locals = self.old_locals current_state = self.current_state current_old_state = self.current_old_state quantified_vars = self.quantified_vars present_state = self.present_state old_state = self.old_state pre_state = self.pre_state issued_state = self.issued_state self_address = self.self_address _break_label_counter = self._break_label_counter _continue_label_counter = self._continue_label_counter break_label = self.break_label continue_label = self.continue_label success_var = self.success_var revert_label = self.revert_label result_var = self.result_var return_label = self.return_label inside_trigger = self.inside_trigger inside_inline_analysis = self.inside_inline_analysis inline_function = self.inline_function local_var_counter = self._local_var_counter new_local_vars = self.new_local_vars quantified_var_counter = self._quantified_var_counter inline_counter = self._inline_counter current_inline = self._current_inline inline_vias = self.inline_vias.copy() loop_arrays = self.loop_arrays loop_indices = self.loop_indices event_vars = self.event_vars pure_conds = self.pure_conds pure_returns = self.pure_returns pure_success = self.pure_success pure_var_index_counter = self._pure_var_index_counter pure_continues = self.pure_continues pure_breaks = self.pure_breaks inside_interface_call = self.inside_interface_call inside_derived_resource_performs = self.inside_derived_resource_performs self.function = None self.is_pure_function = False self.args = {} self.locals = {} self.old_locals = {} self.current_state = {} self.current_old_state = {} self.quantified_vars = {} self.present_state = {} self.old_state = {} self.pre_state = {} self.issued_state = {} self._break_label_counter = -1 self._continue_label_counter = -1 self.break_label = None self.continue_label = None self.success_var = None self.revert_label = None self.result_var = None self.return_label = None self.inside_trigger = False self.inside_inline_analysis = False self.inline_function = None self._local_var_counter = defaultdict(lambda: -1) self.new_local_vars = [] self._quantified_var_counter = -1 self._inline_counter = -1 self._current_inline = -1 self.loop_arrays = {} self.loop_indices = {} self.event_vars = {} self.pure_conds = None self.pure_returns = [] self.pure_success = [] self._pure_var_index_counter = 1 self.pure_continues = [] self.pure_breaks = [] self.inside_interface_call = False self.inside_derived_resource_performs = False yield self.function = function self.is_pure_function = is_pure_function self.args = args self.locals = local_variables self.old_locals = old_locals self.current_state = current_state self.current_old_state = current_old_state self.quantified_vars = quantified_vars self.present_state = present_state self.old_state = old_state self.pre_state = pre_state self.issued_state = issued_state self.self_address = self_address self._break_label_counter = _break_label_counter self._continue_label_counter = _continue_label_counter self.break_label = break_label self.continue_label = continue_label self.success_var = success_var self.revert_label = revert_label self.result_var = result_var self.return_label = return_label self.inside_trigger = inside_trigger self.inside_inline_analysis = inside_inline_analysis self.inline_function = inline_function self._local_var_counter = local_var_counter self.new_local_vars = new_local_vars self._quantified_var_counter = quantified_var_counter self._inline_counter = inline_counter self._current_inline = current_inline self.inline_vias = inline_vias self.loop_arrays = loop_arrays self.loop_indices = loop_indices self.event_vars = event_vars self.pure_conds = pure_conds self.pure_returns = pure_returns self.pure_success = pure_success self._pure_var_index_counter = pure_var_index_counter self.pure_continues = pure_continues self.pure_breaks = pure_breaks self.inside_interface_call = inside_interface_call self.inside_derived_resource_performs = inside_derived_resource_performs @contextmanager def quantified_var_scope(self): quantified_vars = self.quantified_vars.copy() quantified_var_counter = self._quantified_var_counter self._quantified_var_counter = -1 yield self.quantified_vars = quantified_vars self._quantified_var_counter = quantified_var_counter @contextmanager def inside_trigger_scope(self): inside_trigger = self.inside_trigger self.inside_trigger = True yield self.inside_trigger = inside_trigger @contextmanager def inline_scope(self, via, function: Optional[VyperFunction] = None): success_var = self.success_var result_var = self.result_var self.result_var = None return_label = self.return_label self.return_label = None local_vars = self.locals.copy() self.locals = {names.MSG: local_vars[names.MSG], names.BLOCK: local_vars[names.BLOCK], names.CHAIN: local_vars[names.CHAIN], names.TX: local_vars[names.TX]} args = self.args.copy() old_inline = self._current_inline self._inline_counter += 1 self._current_inline = self._inline_counter inline_vias = self.inline_vias.copy() self.inline_vias.append(via) inside_inline_analysis = self.inside_inline_analysis self.inside_inline_analysis = True inline_function = self.inline_function self.inline_function = function yield self.success_var = success_var self.result_var = result_var self.return_label = return_label self.locals = local_vars self.args = args self._current_inline = old_inline self.inline_vias = inline_vias self.inside_inline_analysis = inside_inline_analysis self.inline_function = inline_function @contextmanager def interface_call_scope(self): result_var = self.result_var self.result_var = None success_var = self.success_var self.success_var = None local_vars = self.locals.copy() old_inline = self._current_inline self._inline_counter += 1 self._current_inline = self._inline_counter inside_interface_call = self.inside_interface_call self.inside_interface_call = True yield self.result_var = result_var self.success_var = success_var self.locals = local_vars self._current_inline = old_inline self.inside_interface_call = inside_interface_call @contextmanager def derived_resource_performs_scope(self): inside_derived_resource_performs = self.inside_derived_resource_performs self.inside_derived_resource_performs = True inside_interface_call = self.inside_interface_call self.inside_interface_call = False yield self.inside_derived_resource_performs = inside_derived_resource_performs self.inside_interface_call = inside_interface_call @contextmanager def program_scope(self, program: VyperProgram): old_program: VyperProgram = self.current_program self.current_program = program args = None if self.function and not self.inside_inline_analysis: interfaces = [name for name, interface in old_program.interfaces.items() if interface.file == program.file] implemented_interfaces = [interface.name for interface in old_program.implements] if any(interface in implemented_interfaces for interface in interfaces): args = self.args other_func: VyperFunction = program.functions.get(self.function.name) if other_func: assert len(other_func.args) == len(args) self.args = {} for (name, _), (_, var) in zip(other_func.args.items(), args.items()): self.args[name] = var yield self.current_program = old_program if args: self.args = args @contextmanager def state_scope(self, present_state, old_state): current_state = self.current_state.copy() current_old_state = self.current_old_state.copy() self.current_state = present_state self.current_old_state = old_state local_vars = self.locals.copy() yield self.current_state = current_state self.current_old_state = current_old_state self.locals = local_vars @contextmanager def allocated_scope(self, allocated): current_state = self.current_state.copy() self.current_state[mangled.ALLOCATED] = allocated yield self.current_state = current_state @contextmanager def self_address_scope(self, address): old_self_address = self.self_address self.self_address = address yield self.self_address = old_self_address @contextmanager def break_scope(self): break_label = self.break_label self.break_label = self._next_break_label() pure_break = self.pure_breaks self.pure_breaks = [] yield self.break_label = break_label self.pure_breaks = pure_break @contextmanager def continue_scope(self): continue_label = self.continue_label self.continue_label = self._next_continue_label() pure_continue = self.pure_continues self.pure_continues = [] yield self.continue_label = continue_label self.pure_continues = pure_continue @contextmanager def old_local_variables_scope(self, old_locals): prev_old_locals = self.old_locals self.old_locals = old_locals yield self.old_locals = prev_old_locals @contextmanager def new_local_scope(self): event_vars = self.event_vars yield self.event_vars = event_vars @contextmanager def lemma_scope(self, is_inside=True): inside_lemma = self.inside_lemma self.inside_lemma = is_inside yield self.inside_lemma = inside_lemma @contextmanager def interpreted_scope(self, is_inside=True): inside_interpreted = self.inside_interpreted self.inside_interpreted = is_inside yield self.inside_interpreted = inside_interpreted
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/context.py
context.py
from functools import reduce from typing import List, Optional, Tuple, Union from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.nodes import Resource from twovyper.translation import helpers from twovyper.translation.abstract import NodeTranslator from twovyper.translation.context import Context from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt class ResourceTranslator(NodeTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) @property def specification_translator(self): from twovyper.translation.specification import SpecificationTranslator return SpecificationTranslator(self.viper_ast) def underlying_wei_resource(self, ctx, pos=None) -> Expr: _, expr = self._resource(names.UNDERLYING_WEI, [], ctx, pos) return expr def resource(self, name: str, args: List[Expr], ctx: Context, pos=None) -> Expr: self_address = ctx.self_address or helpers.self_address(self.viper_ast) args = list(args) args.append(self_address) _, expr = self._resource(name, args, ctx, pos) return expr def _resource(self, name: str, args: List[Expr], ctx: Context, pos=None) -> Tuple[Resource, Expr]: resources = ctx.program.resources.get(name) assert resources is not None and len(resources) > 0 resource = ctx.current_program.own_resources.get(name, resources[0]) return resource, helpers.struct_init(self.viper_ast, args, resource.type, pos) def creator_resource(self, resource: Expr, _: Context, pos=None) -> Expr: creator_resource_type = helpers.creator_resource().type return helpers.struct_init(self.viper_ast, [resource], creator_resource_type, pos) def translate(self, resource: Optional[ast.Node], res: List[Stmt], ctx: Context, return_resource=False) -> Union[Expr, Tuple[Resource, Expr]]: if resource: resource, expr = super().translate(resource, res, ctx) else: self_address = ctx.self_address or helpers.self_address(self.viper_ast) resource, expr = self._resource(names.WEI, [self_address], ctx) if return_resource: return resource, expr else: return expr def translate_resources_for_quantified_expr(self, resources: List[Tuple[str, Resource]], ctx: Context, pos=None, translate_underlying=False, args_idx_start=0): counter = args_idx_start translated_resource_with_args_and_type_assumption = [] for name, resource in resources: type_assumptions = [] args = [] for idx, arg_type in enumerate(resource.type.member_types.values()): viper_type = self.specification_translator.type_translator.translate(arg_type, ctx) arg = self.viper_ast.LocalVarDecl(f'$arg{idx}${counter}', viper_type, pos) counter += 1 args.append(arg) arg_var = arg.localVar() type_assumptions.extend(self.specification_translator.type_translator .type_assumptions(arg_var, arg_type, ctx)) type_cond = reduce(lambda l, r: self.viper_ast.And(l, r, pos), type_assumptions, self.viper_ast.TrueLit()) if translate_underlying: assert isinstance(resource.type, types.DerivedResourceType) if resource.name == names.WEI: t_resource = self.underlying_wei_resource(ctx) else: stmts = [] underlying_address = self.specification_translator.translate( resource.underlying_address, stmts, ctx) assert not stmts t_resource = helpers.struct_init( self.viper_ast, [arg.localVar() for arg in args] + [underlying_address], resource.type.underlying_resource, pos) else: t_resource = self.resource(name, [arg.localVar() for arg in args], ctx) translated_resource_with_args_and_type_assumption.append((t_resource, args, type_cond)) return translated_resource_with_args_and_type_assumption def translate_with_underlying(self, top_node: Optional[ast.FunctionCall], res: List[Stmt], ctx: Context, return_resource=False) -> Union[Tuple[Expr, Expr], Tuple[Resource, Expr, Expr]]: if top_node: resource_node = top_node.resource underlying_resource_node = top_node.underlying_resource resource, expr = self.translate(resource_node, res, ctx, True) underlying_resource_expr = self.translate(underlying_resource_node, res, ctx) else: resource, expr = self.translate(None, res, ctx, True) underlying_resource_expr = self.underlying_wei_resource(ctx) if return_resource: return resource, expr, underlying_resource_expr else: return expr, underlying_resource_expr def translate_exchange(self, exchange: Optional[ast.Exchange], res: Stmt, ctx: Context, return_resource=False) -> Tuple[Union[Expr, Tuple[Resource, Expr]], Union[Expr, Tuple[Resource, Expr]]]: if not exchange: wei_resource = self.translate(None, res, ctx, return_resource) return wei_resource, wei_resource left = self.translate(exchange.left, res, ctx, return_resource) right = self.translate(exchange.right, res, ctx, return_resource) return left, right def translate_Name(self, node: ast.Name, _: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if node.id == names.UNDERLYING_WEI: return self._resource(node.id, [], ctx, pos) else: self_address = ctx.self_address or helpers.self_address(self.viper_ast) return self._resource(node.id, [self_address], ctx, pos) def translate_FunctionCall(self, node: ast.FunctionCall, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if node.name == names.CREATOR: resource = self.translate(node.args[0], res, ctx) return None, self.creator_resource(resource, ctx, pos) elif node.resource: address = self.specification_translator.translate(node.resource, res, ctx) else: address = ctx.self_address or helpers.self_address(self.viper_ast) args = [self.specification_translator.translate(arg, res, ctx) for arg in node.args] args.append(address) return self._resource(node.name, args, ctx, pos) def translate_Attribute(self, node: ast.Attribute, _: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) assert isinstance(node.value, ast.Name) interface = ctx.current_program.interfaces[node.value.id] with ctx.program_scope(interface): self_address = ctx.self_address or helpers.self_address(self.viper_ast) return self._resource(node.attr, [self_address], ctx, pos) def translate_ReceiverCall(self, node: ast.ReceiverCall, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if isinstance(node.receiver, ast.Name): interface = ctx.current_program.interfaces[node.receiver.id] address = ctx.self_address or helpers.self_address(self.viper_ast) elif isinstance(node.receiver, ast.Subscript): assert isinstance(node.receiver.value, ast.Attribute) assert isinstance(node.receiver.value.value, ast.Name) interface_name = node.receiver.value.value.id interface = ctx.current_program.interfaces[interface_name] address = self.specification_translator.translate(node.receiver.index, res, ctx) else: assert False with ctx.program_scope(interface): args = [self.specification_translator.translate(arg, res, ctx) for arg in node.args] args.append(address) return self._resource(node.name, args, ctx, pos) def translate_Subscript(self, node: ast.Subscript, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) other_address = self.specification_translator.translate(node.index, res, ctx) if isinstance(node.value, ast.Attribute): assert isinstance(node.value.value, ast.Name) interface = ctx.current_program.interfaces[node.value.value.id] with ctx.program_scope(interface): return self._resource(node.value.attr, [other_address], ctx, pos) elif isinstance(node.value, ast.Name): return self._resource(node.value.id, [other_address], ctx, pos) else: assert False
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/resource.py
resource.py
from functools import reduce from itertools import chain from typing import List from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.nodes import VyperFunction, VyperVar from twovyper.translation import helpers, mangled from twovyper.translation.context import Context from twovyper.translation.function import FunctionTranslator from twovyper.translation.pure_statement import PureStatementTranslator from twovyper.translation.pure_translators import PureTranslatorMixin, PureTypeTranslator from twovyper.translation.variable import TranslatedPureIndexedVar, TranslatedVar from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Function, Expr class PureFunctionTranslator(PureTranslatorMixin, FunctionTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.statement_translator = PureStatementTranslator(viper_ast) self.type_translator = PureTypeTranslator(viper_ast) def translate(self, function: VyperFunction, ctx: Context) -> Function: with ctx.function_scope(): pos = self.to_position(function.node, ctx) ctx.function = function ctx.is_pure_function = True args = {name: self._translate_pure_non_local_var(var, ctx) for name, var in function.args.items()} state = {names.SELF: TranslatedVar(names.SELF, mangled.present_state_var_name(names.SELF), types.AnyStructType(), self.viper_ast, pos)} ctx.present_state = state ctx.old_state = ctx.present_state ctx.pre_state = ctx.present_state ctx.issued_state = ctx.present_state ctx.current_state = ctx.present_state ctx.current_old_state = ctx.present_state ctx.args = args.copy() ctx.locals = {} ctx.success_var = TranslatedPureIndexedVar(names.SUCCESS, mangled.SUCCESS_VAR, types.VYPER_BOOL, self.viper_ast) ctx.return_label = None ctx.revert_label = None ctx.result_var = TranslatedPureIndexedVar(names.RESULT, mangled.RESULT_VAR, function.type.return_type, self.viper_ast) body = [] # State type assumptions for state_var in ctx.present_state.values(): type_assumptions = self.type_translator.type_assumptions(state_var.local_var(ctx), state_var.type, ctx) body.extend(type_assumptions) # Assume type assumptions for self address self_address = helpers.self_address(self.viper_ast) self_address_ass = self.type_translator.type_assumptions(self_address, types.VYPER_ADDRESS, ctx) body.extend(self_address_ass) # Assume type assumptions for arguments for var in function.args.values(): local_var = args[var.name].local_var(ctx) assumptions = self.type_translator.type_assumptions(local_var, var.type, ctx) body.extend(assumptions) # If we do not encounter an exception we will return success ctx.success_var.new_idx() body.append(self.viper_ast.EqCmp(ctx.success_var.local_var(ctx), self.viper_ast.TrueLit())) self.statement_translator.translate_stmts(function.node.body, body, ctx) viper_struct_type = helpers.struct_type(self.viper_ast) function_result = self.viper_ast.Result(viper_struct_type) def partial_unfinished_cond_expression(cond_and_idx): cond, idx = cond_and_idx def unfinished_cond_expression(expr): val = helpers.struct_get_idx(self.viper_ast, function_result, idx, viper_type, pos) return self.viper_ast.CondExp(cond, val, expr) return unfinished_cond_expression # Generate success variable viper_type = self.viper_ast.Bool unfinished_cond_expressions = list(map(partial_unfinished_cond_expression, ctx.pure_success)) value = reduce(lambda expr, func: func(expr), reversed(unfinished_cond_expressions), self.viper_ast.TrueLit()) # Set success variable at slot 0 success_var = helpers.struct_pure_get_success(self.viper_ast, function_result, pos) success_cond_expr = self.viper_ast.CondExp(value, self.viper_ast.TrueLit(), self.viper_ast.FalseLit()) body.append(self.viper_ast.EqCmp(success_var, success_cond_expr)) # Generate result variable viper_type = self.viper_ast.Bool default_value = self.viper_ast.TrueLit() if function.type.return_type: viper_type = self.type_translator.translate(function.type.return_type, ctx) default_value = self.type_translator.default_value(function.node, function.type.return_type, body, ctx) unfinished_cond_expressions = list(map(partial_unfinished_cond_expression, ctx.pure_returns)) value = reduce(lambda expr, func: func(expr), reversed(unfinished_cond_expressions), default_value) # Set result variable at slot 1 result_var = helpers.struct_pure_get_result(self.viper_ast, function_result, viper_type, pos) body.append(self.viper_ast.EqCmp(result_var, value)) # Arguments have to be TranslatedVar. Therefore, transform the non-local TranslatedPureIndexedVar to # local TranslatedVar. arg_transform = [] new_args = {} for arg_name, arg in args.items(): assert isinstance(arg, TranslatedPureIndexedVar) if not arg.is_local: lhs = arg.local_var(ctx) new_arg = TranslatedVar(arg.name, arg.mangled_name, arg.type, arg.viper_ast, arg.pos, arg.info, is_local=True) rhs = new_arg.local_var(ctx) arg_transform.append(self.viper_ast.EqCmp(lhs, rhs)) new_args[arg_name] = new_arg body = arg_transform + body args_list = [arg.var_decl(ctx) for arg in chain(state.values(), new_args.values())] viper_name = mangled.pure_function_name(function.name) function = self.viper_ast.Function(viper_name, args_list, helpers.struct_type(self.viper_ast), [], body, None, pos) return function def _translate_pure_non_local_var(self, var: VyperVar, ctx: Context): pos = self.to_position(var.node, ctx) name = mangled.local_var_name(ctx.inline_prefix, var.name) return TranslatedPureIndexedVar(var.name, name, var.type, self.viper_ast, pos, is_local=False) def inline(self, call: ast.ReceiverCall, args: List[Expr], res: List[Expr], ctx: Context) -> Expr: return self._call_pure(call, args, res, ctx)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/pure_function.py
pure_function.py
from twovyper.ast import names # Constants for names in translated AST INIT = names.INIT SELF = names.SELF CONTRACTS = '$contracts' ALLOCATED = '$allocated' OFFERED = '$offered' TRUSTED = '$trusted' ALLOCATION = '$allocation' OFFER = '$offer' TRUST = '$trust' CREATOR = '$creator' CREATOR_RESOURCE = '$resource' ORIGINAL_MSG = '$original_msg' PERFORMS = '$performs' MSG = names.MSG BLOCK = names.BLOCK CHAIN = names.CHAIN TX = names.TX SENT_FIELD = '$sent' RECEIVED_FIELD = '$received' SELFDESTRUCT_FIELD = '$selfdestruct' RESULT_VAR = '$res' SUCCESS_VAR = '$succ' OVERFLOW = '$overflow' OUT_OF_GAS = '$out_of_gas' FAILED = '$failed' CALLER = '$caller' FIRST_PUBLIC_STATE = '$first_public_state' END_LABEL = 'end' RETURN_LABEL = 'return' REVERT_LABEL = 'revert' BLOCKCHAIN_DOMAIN = '$Blockchain' BLOCKCHAIN_BLOCKHASH = '$blockhash' BLOCKCHAIN_METHOD_ID = '$method_id' BLOCKCHAIN_KECCAK256 = '$keccak256' BLOCKCHAIN_SHA256 = '$sha256' BLOCKCHAIN_ECRECOVER = '$ecrecover' BLOCKCHAIN_ECADD = '$ecadd' BLOCKCHAIN_ECMUL = '$ecmul' CONTRACT_DOMAIN = '$Contract' SELF_ADDRESS = '$self_address' IMPLEMENTS = '$implements' MATH_DOMAIN = '$Math' MATH_SIGN = '$sign' MATH_DIV = '$div' MATH_MOD = '$mod' MATH_POW = '$pow' MATH_SQRT = '$sqrt' MATH_FLOOR = '$floor' MATH_CEIL = '$ceil' MATH_SHIFT = '$shift' MATH_BITWISE_NOT = '$bitwise_not' MATH_BITWISE_AND = '$bitwise_and' MATH_BITWISE_OR = '$bitwise_or' MATH_BITWISE_XOR = '$bitwise_xor' WRAPPED_INT_DOMAIN = '$Int' WRAPPED_INT_WRAP = '$wrap' WRAPPED_INT_UNWRAP = '$unwrap' WRAPPED_INT_MUL = '$w_mul' WRAPPED_INT_MOD = '$w_mod' WRAPPED_INT_DIV = '$w_div' ARRAY_DOMAIN = '$Array' ARRAY_INT_DOMAIN = '$ArrayInt' ARRAY_ELEMENT_VAR = '$E' ARRAY_INIT = '$array_init' MAP_DOMAIN = '$Map' MAP_INT_DOMAIN = '$MapInt' MAP_KEY_VAR = '$K' MAP_VALUE_VAR = '$V' MAP_INIT = '$map_init' MAP_EQ = '$map_eq' MAP_GET = '$map_get' MAP_SET = '$map_set' MAP_SUM = '$map_sum' STRUCT_DOMAIN = '$Struct' STRUCT_OPS_DOMAIN = '$StructOps' STRUCT_OPS_VALUE_VAR = '$T' STRUCT_LOC = '$struct_loc' STRUCT_GET = '$struct_get' STRUCT_SET = '$struct_set' STRUCT_TYPE_LOC = -1 STRUCT_INIT_DOMAIN = '$StructInit' RANGE_DOMAIN = '$Range' RANGE_RANGE = '$range' RANGE_SUM = '$range_sum' CONVERT_DOMAIN = '$Convert' CONVERT_BYTES32_TO_SIGNED_INT = '$bytes32_to_signed_int' CONVERT_BYTES32_TO_UNSIGNED_INT = '$bytes32_to_unsigned_int' CONVERT_SIGNED_INT_TO_BYTES32 = '$signed_int_to_bytes32' CONVERT_UNSIGNED_INT_TO_BYTES32 = '$unsigned_int_to_bytes32' CONVERT_PAD32 = '$pad32' IMPLEMENTS_DOMAIN = '$Implements' TRANSITIVITY_CHECK = '$transitivity_check' REFLEXIVITY_CHECK = '$reflexivity_check' FORCED_ETHER_CHECK = '$forced_ether_check' PURE_SUCCESS = '$pure$success_get' PURE_RESULT = '$pure$return_get' TRUST_NO_ONE = '$trust_no_one' NO_OFFERS = '$no_offers' def method_name(vyper_name: str) -> str: return f'f${vyper_name}' def struct_name(vyper_struct_name: str, kind: str) -> str: return f's${kind}${vyper_struct_name}' def struct_type_tag(vyper_struct_name: str, kind: str) -> int: name = struct_name(vyper_struct_name, kind) return int.from_bytes(name.encode('utf-8'), 'big') def struct_init_name(vyper_struct_name: str, kind: str) -> str: return f'{struct_name(vyper_struct_name, kind)}$init' def struct_eq_name(vyper_struct_name: str, kind: str) -> str: return f'{struct_name(vyper_struct_name, kind)}$eq' def interface_name(vyper_interface_name: str) -> str: return f'i${vyper_interface_name}' def interface_function_name(vyper_iname: str, vyper_fname: str) -> str: return f'{interface_name(vyper_iname)}${vyper_fname}' def ghost_function_name(vyper_iname: str, vyper_fname: str) -> str: return f'g${interface_name(vyper_iname)}${vyper_fname}' def pure_function_name(vyper_name: str) -> str: return f'p${vyper_name}' def lemma_name(vyper_name: str) -> str: return f'lemma${vyper_name}' def axiom_name(viper_name: str) -> str: return f'{viper_name}$ax' def event_name(vyper_name: str) -> str: return f'e${vyper_name}' def accessible_name(vyper_name: str) -> str: return f'$accessible${vyper_name}' def lock_name(vyper_name: str) -> str: return f'n${vyper_name}' def present_state_var_name(name: str) -> str: return name def old_state_var_name(name: str) -> str: return f'$old_{name}' def pre_old_state_var_name(name: str) -> str: return f'$pre_old_{name}' def pre_state_var_name(name: str) -> str: return f'$pre_{name}' def issued_state_var_name(name: str) -> str: return f'$issued_{name}' def local_var_name(inline_prefix: str, vyper_name: str) -> str: if vyper_name in {names.SELF, names.MSG, names.BLOCK}: prefix = '' else: prefix = 'l$' return f'{prefix}{inline_prefix}{vyper_name}' def quantifier_var_name(vyper_name: str) -> str: return f'q${vyper_name}' def model_var_name(*components: str) -> str: return f'm${"$".join(components)}' def performs_predicate_name(vyper_name: str) -> str: return f'{PERFORMS}${vyper_name}'
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/mangled.py
mangled.py
from functools import reduce from typing import Optional, List from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.types import ( VyperType, PrimitiveType, MapType, ArrayType, TupleType, AnyStructType, StructType, ContractType, InterfaceType ) from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt, Type from twovyper.translation.abstract import CommonTranslator from twovyper.translation.context import Context from twovyper.translation import helpers, mangled class TypeTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) wrapped_int_type = helpers.wrapped_int_type(self.viper_ast) self.wrapped_type_dict = { types.VYPER_BOOL: viper_ast.Bool, types.VYPER_INT128: wrapped_int_type, types.VYPER_UINT256: wrapped_int_type, types.VYPER_DECIMAL: wrapped_int_type, types.VYPER_ADDRESS: viper_ast.Int, types.VYPER_BYTE: viper_ast.Int, types.NON_NEGATIVE_INT: viper_ast.Int } self.type_dict = { types.VYPER_BOOL: viper_ast.Bool, types.VYPER_INT128: viper_ast.Int, types.VYPER_UINT256: viper_ast.Int, types.VYPER_DECIMAL: viper_ast.Int, types.VYPER_ADDRESS: viper_ast.Int, types.VYPER_BYTE: viper_ast.Int, types.NON_NEGATIVE_INT: viper_ast.Int } def translate(self, type: VyperType, ctx: Context, is_local=True) -> Type: if isinstance(type, PrimitiveType): if is_local: return self.type_dict[type] else: return self.wrapped_type_dict[type] elif isinstance(type, MapType): key_type = self.translate(type.key_type, ctx) value_type = self.translate(type.value_type, ctx) return helpers.map_type(self.viper_ast, key_type, value_type) elif isinstance(type, ArrayType): element_type = self.translate(type.element_type, ctx) return helpers.array_type(self.viper_ast, element_type) elif isinstance(type, (AnyStructType, StructType)): return helpers.struct_type(self.viper_ast) elif isinstance(type, (ContractType, InterfaceType)): return self.translate(types.VYPER_ADDRESS, ctx) elif isinstance(type, TupleType): return helpers.struct_type(self.viper_ast) else: assert False def default_value(self, node: Optional[ast.Node], type: VyperType, res: List[Stmt], ctx: Context, is_local=True) -> Expr: pos = self.no_position() if node is None else self.to_position(node, ctx) if type is types.VYPER_BOOL: return self.viper_ast.FalseLit(pos) elif isinstance(type, PrimitiveType): if is_local: return self.viper_ast.IntLit(0, pos) else: return helpers.w_wrap(self.viper_ast, self.viper_ast.IntLit(0, pos), pos) elif isinstance(type, MapType): key_type = self.translate(type.key_type, ctx) value_type = self.translate(type.value_type, ctx) value_default = self.default_value(node, type.value_type, res, ctx) return helpers.map_init(self.viper_ast, value_default, key_type, value_type, pos) elif isinstance(type, ArrayType): sizes = [type.size] curr_type = type while isinstance(curr_type.element_type, ArrayType): # noinspection PyUnresolvedReferences sizes.append(curr_type.element_type.size) curr_type = curr_type.element_type element_type = self.translate(curr_type.element_type, ctx) if type.is_strict: result = self.default_value(node, curr_type.element_type, res, ctx) result_type = element_type for size in sizes: result = helpers.array_init(self.viper_ast, result, size, result_type, pos) result_type = helpers.array_type(self.viper_ast, result_type) return result else: return helpers.empty_array(self.viper_ast, element_type, pos) elif isinstance(type, StructType): init_args = {} for name, member_type in type.member_types.items(): idx = type.member_indices[name] val = self.default_value(node, member_type, res, ctx) init_args[idx] = val args = [init_args[i] for i in range(len(init_args))] return helpers.struct_init(self.viper_ast, args, type, pos) elif isinstance(type, (ContractType, InterfaceType)): return self.default_value(node, types.VYPER_ADDRESS, res, ctx) elif isinstance(type, TupleType): return helpers.havoc_var(self.viper_ast, helpers.struct_type(self.viper_ast), ctx) else: assert False def type_assumptions(self, node, type: VyperType, ctx: Context) -> List[Expr]: """ Computes the assumptions for either array length or number bounds of nested structures. If mode == 0: constructs bounds If mode == 1: constructs array lengths """ def construct(type, node): ret = [] # If we encounter a bounded primitive type we add the following assumption: # x >= lower # x <= upper # where x is said integer if types.is_bounded(type): lower = self.viper_ast.IntLit(type.lower) upper = self.viper_ast.IntLit(type.upper) lcmp = self.viper_ast.LeCmp(lower, node) ucmp = self.viper_ast.LeCmp(node, upper) # If the no_overflows config option is enabled, we only assume non-negativity for uints if ctx.program.config.has_option(names.CONFIG_NO_OVERFLOWS): if types.is_unsigned(type): bounds = lcmp else: bounds = self.viper_ast.TrueLit() else: bounds = self.viper_ast.And(lcmp, ucmp) ret.append(bounds) elif type == types.NON_NEGATIVE_INT: lower = self.viper_ast.IntLit(0) lcmp = self.viper_ast.LeCmp(lower, node) ret.append(lcmp) # If we encounter a map, we add the following assumptions: # forall k: Key :: construct(map_get(k)) # forall k: Key :: map_get(k) <= map_sum() # where constuct constructs the assumption for the values contained # in the map (may be empty) elif isinstance(type, MapType): key_type = self.translate(type.key_type, ctx) value_type = self.translate(type.value_type, ctx) quant_var_name = ctx.new_quantified_var_name() quant_decl = self.viper_ast.LocalVarDecl(quant_var_name, key_type) quant = quant_decl.localVar() new_node = helpers.map_get(self.viper_ast, node, quant, key_type, value_type) trigger = self.viper_ast.Trigger([new_node]) sub_ret = construct(type.value_type, new_node) for r in sub_ret: quantifier = self.viper_ast.Forall([quant_decl], [trigger], r) ret.append(quantifier) if types.is_unsigned(type.value_type): mp_sum = helpers.map_sum(self.viper_ast, node, key_type) r = self.viper_ast.LeCmp(new_node, mp_sum) quantifier = self.viper_ast.Forall([quant_decl], [trigger], r) ret.append(quantifier) # If we encounter an array, we add the follwing assumptions: # |array| == array_size # forall i: Int :: 0 <= i && i < |array| ==> construct(array[i]) # where construct recursively constructs the assumptions for nested arrays and maps elif isinstance(type, ArrayType): array_len = self.viper_ast.SeqLength(node) size = self.viper_ast.IntLit(type.size) if type.is_strict: comp = self.viper_ast.EqCmp(array_len, size) else: comp = self.viper_ast.LeCmp(array_len, size) ret.append(comp) quant_var_name = ctx.new_quantified_var_name() quant_decl = self.viper_ast.LocalVarDecl(quant_var_name, self.viper_ast.Int) quant = quant_decl.localVar() new_node = helpers.array_get(self.viper_ast, node, quant, type.element_type) trigger = self.viper_ast.Trigger([new_node]) leq = self.viper_ast.LeCmp(self.viper_ast.IntLit(0), quant) le = self.viper_ast.LtCmp(quant, self.viper_ast.SeqLength(node)) bounds = self.viper_ast.And(leq, le) sub_ret = construct(type.element_type, new_node) for r in sub_ret: implies = self.viper_ast.Implies(bounds, r) quantifier = self.viper_ast.Forall([quant_decl], [trigger], implies) ret.append(quantifier) elif isinstance(type, (ContractType, InterfaceType)): return construct(types.VYPER_ADDRESS, node) # If we encounter a struct type we simply add the necessary assumptions for # all struct members # Additionally, we add an assumption about the type tag elif isinstance(type, StructType): for member_name, member_type in type.member_types.items(): viper_type = self.translate(member_type, ctx) get = helpers.struct_get(self.viper_ast, node, member_name, viper_type, type) ret.extend(construct(member_type, get)) type_tag = self.viper_ast.IntLit(mangled.struct_type_tag(type.name, type.kind)) get_tag = helpers.struct_type_tag(self.viper_ast, node) ret.append(self.viper_ast.EqCmp(get_tag, type_tag)) return ret with ctx.quantified_var_scope(): return construct(type, node) def array_bounds_check(self, array, index, res: List[Stmt], ctx: Context): leq = self.viper_ast.LeCmp(self.viper_ast.IntLit(0), index) le = self.viper_ast.LtCmp(index, self.viper_ast.SeqLength(array)) cond = self.viper_ast.Not(self.viper_ast.And(leq, le)) self.fail_if(cond, [], res, ctx) def comparator(self, type: VyperType, ctx: Context): # For msg, block, chain, tx we don't generate an equality function, as they are immutable anyway if isinstance(type, StructType) and type not in names.ENV_VARIABLES: return mangled.struct_eq_name(type.name, type.kind), {} elif isinstance(type, MapType): key_type = self.translate(type.key_type, ctx) value_type = self.translate(type.value_type, ctx) type_map = helpers._map_type_var_map(self.viper_ast, key_type, value_type) return mangled.MAP_EQ, type_map else: return None def eq(self, left, right, type: VyperType, ctx: Context, pos=None) -> Expr: if isinstance(type, StructType): return helpers.struct_eq(self.viper_ast, left, right, type, pos) elif isinstance(type, MapType): key_type = self.translate(type.key_type, ctx) value_type = self.translate(type.value_type, ctx) return helpers.map_eq(self.viper_ast, left, right, key_type, value_type, pos) elif isinstance(type, TupleType): cond = None for idx, element_type in enumerate(type.element_types): viper_type = self.translate(element_type, ctx) left_element = helpers.struct_get_idx(self.viper_ast, left, idx, viper_type, pos) right_element = helpers.struct_get_idx(self.viper_ast, right, idx, viper_type, pos) element_cond = self.viper_ast.EqCmp(left_element, right_element, pos) cond = self.viper_ast.And(cond, element_cond, pos) if cond else element_cond return cond else: return self.viper_ast.EqCmp(left, right, pos) def neq(self, left, right, type: VyperType, ctx: Context, pos=None) -> Expr: if isinstance(type, StructType): return self.viper_ast.Not(helpers.struct_eq(self.viper_ast, left, right, type, pos), pos) elif isinstance(type, MapType): key_type = self.translate(type.key_type, ctx) value_type = self.translate(type.value_type, ctx) map_eq = helpers.map_eq(self.viper_ast, left, right, key_type, value_type, pos) return self.viper_ast.Not(map_eq, pos) elif isinstance(type, TupleType): cond = None for idx, element_type in enumerate(type.element_types): viper_type = self.translate(element_type, ctx) left_element = helpers.struct_get_idx(self.viper_ast, left, idx, viper_type, pos) right_element = helpers.struct_get_idx(self.viper_ast, right, idx, viper_type, pos) element_cond = self.viper_ast.NeCmp(left_element, right_element, pos) cond = self.viper_ast.Or(cond, element_cond, pos) if cond else element_cond return cond else: return self.viper_ast.NeCmp(left, right, pos)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/type.py
type.py
from typing import Any, Dict, List, Iterable from twovyper.ast import ast_nodes as ast from twovyper.ast.visitors import NodeVisitor from twovyper.translation.context import Context from twovyper.verification import error_manager from twovyper.verification.error import ErrorInfo, ModelTransformation, Via from twovyper.verification.rules import Rule from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt from twovyper.viper.typedefs import Position, Info class CommonTranslator: def __init__(self, viper_ast: ViperAST): self.viper_ast = viper_ast def _register_potential_error(self, node, ctx: Context, rules: Rule = None, vias: List[Via] = [], modelt: ModelTransformation = None, values: Dict[str, Any] = {}) -> str: # Inline vias are in reverse order, as the outermost is first, # and successive vias are appended. For the error output, changing # the order makes more sense. inline_vias = list(reversed(ctx.inline_vias)) values = {'function': ctx.function, **values} error_info = ErrorInfo(node, inline_vias + vias, modelt, values) id = error_manager.add_error_information(error_info, rules) return id def to_position(self, node: ast.Node, ctx: Context, rules: Rule = None, vias: List[Via] = [], modelt: ModelTransformation = None, values: Dict[str, Any] = {}) -> Position: """ Extracts the position from a node, assigns an ID to the node and stores the node and the position in the context for it. """ id = self._register_potential_error(node, ctx, rules, vias, modelt, values) return self.viper_ast.to_position(node, id) def no_position(self) -> Position: return self.viper_ast.NoPosition def to_info(self, comments: List[str]) -> Info: """ Wraps the given comments into an Info object. """ if comments: return self.viper_ast.SimpleInfo(comments) else: return self.viper_ast.NoInfo def no_info(self) -> Info: return self.to_info([]) def fail_if(self, cond: Expr, stmts: List[Stmt], res: List[Stmt], ctx: Context, pos=None, info=None): body = [*stmts, self.viper_ast.Goto(ctx.revert_label, pos)] res.append(self.viper_ast.If(cond, body, [], pos, info)) def seqn_with_info(self, stmts: [Stmt], comment: str, res: List[Stmt]): if stmts: info = self.to_info([comment]) res.append(self.viper_ast.Seqn(stmts, info=info)) class NodeTranslator(NodeVisitor, CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) @property def method_name(self) -> str: return 'translate' def translate(self, node: ast.Node, res: List[Stmt], ctx: Context): return self.visit(node, res, ctx) def visit_nodes(self, nodes: Iterable[ast.Node], *args): ret = [] for node in nodes: ret += self.visit(node, *args) return ret def generic_visit(self, node: ast.Node, *args): raise AssertionError(f"Node of type {type(node)} not supported.")
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/abstract.py
abstract.py
from typing import List, Optional from twovyper.ast import ast_nodes as ast, types from twovyper.ast.types import StructType, VYPER_BOOL, VYPER_UINT256 from twovyper.exceptions import UnsupportedException from twovyper.translation import helpers, LocalVarSnapshot from twovyper.translation.context import Context from twovyper.translation.pure_translators import PureTranslatorMixin, PureExpressionTranslator, \ PureArithmeticTranslator, PureSpecificationTranslator, PureTypeTranslator from twovyper.translation.statement import AssignmentTranslator, StatementTranslator from twovyper.translation.variable import TranslatedPureIndexedVar from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr class PureStatementTranslator(PureTranslatorMixin, StatementTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.expression_translator = PureExpressionTranslator(viper_ast) self.assignment_translator = _AssignmentTranslator(viper_ast) self.arithmetic_translator = PureArithmeticTranslator(viper_ast) self.specification_translator = PureSpecificationTranslator(viper_ast) self.type_translator = PureTypeTranslator(viper_ast) self.viper_struct_type = helpers.struct_type(self.viper_ast) self.function_result = self.viper_ast.Result(self.viper_struct_type) def visit(self, node, *args): if not node.is_ghost_code: super().visit(node, *args) def translate_stmts(self, stmts: List[ast.Stmt], res: List[Expr], ctx: Context): for s in stmts: self.translate(s, res, ctx) def translate_AnnAssign(self, node: ast.AnnAssign, res: List[Expr], ctx: Context): pos = self.to_position(node, ctx) self._add_local_var(node.target, ctx) lhs = ctx.all_vars[node.target.id] if node.value is None: vyper_type = node.target.type rhs = self.type_translator.default_value(None, vyper_type, res, ctx) elif types.is_numeric(node.value.type): rhs = self.expression_translator.translate_top_level_expression(node.value, res, ctx) else: # Ignore the $wrap information, if the node is not numeric rhs = self.expression_translator.translate(node.value, res, ctx) if self.arithmetic_translator.is_wrapped(rhs): if types.is_numeric(node.value.type): lhs.new_idx() lhs.is_local = False else: rhs = helpers.w_unwrap(self.viper_ast, rhs) assign = self.viper_ast.EqCmp(lhs.local_var(ctx, pos), rhs, pos) expr = self.viper_ast.Implies(ctx.pure_conds, assign, pos) if ctx.pure_conds else assign res.append(expr) def translate_Log(self, node: ast.Log, res: List[Expr], ctx: Context): assert False def translate_Raise(self, node: ast.Raise, res: List[Expr], ctx: Context): pos = self.to_position(node, ctx) self.fail_if(self.viper_ast.TrueLit(pos), [], res, ctx, pos) ctx.pure_conds = self.viper_ast.FalseLit(pos) def translate_Assert(self, node: ast.Assert, res: List[Expr], ctx: Context): pos = self.to_position(node, ctx) expr = self.expression_translator.translate(node.test, res, ctx) cond = self.viper_ast.Not(expr, pos) self.fail_if(cond, [], res, ctx, pos) def translate_Return(self, node: ast.Return, res: List[Expr], ctx: Context): assert node.value assert isinstance(ctx.result_var, TranslatedPureIndexedVar) assert isinstance(ctx.success_var, TranslatedPureIndexedVar) pos = self.to_position(node, ctx) expr = self.expression_translator.translate_top_level_expression(node.value, res, ctx) if (self.arithmetic_translator.is_unwrapped(ctx.result_var.local_var(ctx)) and self.arithmetic_translator.is_wrapped(expr)): expr = helpers.w_unwrap(self.viper_ast, expr) ctx.result_var.new_idx() assign = self.viper_ast.EqCmp(ctx.result_var.local_var(ctx), expr, pos) expr = self.viper_ast.Implies(ctx.pure_conds, assign, pos) if ctx.pure_conds else assign res.append(expr) cond = ctx.pure_conds or self.viper_ast.TrueLit(pos) ctx.pure_returns.append((cond, ctx.result_var.evaluate_idx(ctx))) ctx.pure_success.append((cond, ctx.success_var.evaluate_idx(ctx))) def translate_If(self, node: ast.If, res: List[Expr], ctx: Context): pre_locals = self._local_variable_snapshot(ctx) pre_conds = ctx.pure_conds pos = self.to_position(node, ctx) cond = self.expression_translator.translate(node.test, res, ctx) cond_var = TranslatedPureIndexedVar('cond', 'cond', VYPER_BOOL, self.viper_ast, pos) assign = self.viper_ast.EqCmp(cond_var.local_var(ctx), cond, pos) expr = self.viper_ast.Implies(ctx.pure_conds, assign, pos) if ctx.pure_conds else assign res.append(expr) cond_local_var = cond_var.local_var(ctx) # "Then" branch with ctx.new_local_scope(): # Update condition ctx.pure_conds = self.viper_ast.And(pre_conds, cond_local_var, pos) if pre_conds else cond_local_var with self.assignment_translator.assume_everything_has_wrapped_information(): self.translate_stmts(node.body, res, ctx) # Get current state of local variable state after "then"-branch then_locals = self._local_variable_snapshot(ctx) # Reset indices of local variables in context self._reset_variable_to_snapshot(pre_locals, ctx) # "Else" branch with ctx.new_local_scope(): # Update condition negated_local_var = self.viper_ast.Not(cond_local_var, pos) ctx.pure_conds = self.viper_ast.And(pre_conds, negated_local_var, pos) if pre_conds else negated_local_var with self.assignment_translator.assume_everything_has_wrapped_information(): self.translate_stmts(node.orelse, res, ctx) # Get current state of local variable state after "else"-branch else_locals = self._local_variable_snapshot(ctx) # Update condition ctx.pure_conds = pre_conds # Merge variable changed in the "then" or "else" branch self._merge_snapshots(cond_local_var, then_locals, else_locals, res, ctx) def translate_For(self, node: ast.For, res: List[Expr], ctx: Context): pos = self.to_position(node, ctx) pre_conds = ctx.pure_conds self._add_local_var(node.target, ctx) loop_var_name = node.target.id loop_var = ctx.locals[loop_var_name] assert isinstance(loop_var, TranslatedPureIndexedVar) array = self.expression_translator.translate_top_level_expression(node.iter, res, ctx) loop_var.is_local = False array_var = TranslatedPureIndexedVar('array', 'array', node.iter.type, self.viper_ast, pos, is_local=False) res.append(self.viper_ast.EqCmp(array_var.local_var(ctx), array, pos)) array_local_var = array_var.local_var(ctx) times = node.iter.type.size lpos = self.to_position(node.target, ctx) rpos = self.to_position(node.iter, ctx) if times > 0: has_numeric_array = types.is_numeric(node.target.type) loop_invariants = ctx.function.loop_invariants.get(node) if loop_invariants: # loop-array expression ctx.loop_arrays[loop_var_name] = array_local_var # New variable loop-idx loop_idx_var = TranslatedPureIndexedVar('idx', 'idx', VYPER_UINT256, self.viper_ast, pos) ctx.loop_indices[loop_var_name] = loop_idx_var loop_idx_local_var = loop_idx_var.local_var(ctx) # Havoc used variables loop_used_var = {} for var_name in ctx.function.analysis.loop_used_names.get(loop_var_name, []): if var_name == loop_var_name: continue var = ctx.locals.get(var_name) if var and isinstance(var, TranslatedPureIndexedVar): # Create new variable mangled_name = ctx.new_local_var_name(var.name) new_var = TranslatedPureIndexedVar(var.name, mangled_name, var.type, var.viper_ast, var.pos, var.info, var.is_local) copy_expr = self.viper_ast.EqCmp(new_var.local_var(ctx), var.local_var(ctx), rpos) res.append(copy_expr) loop_used_var[var.name] = new_var # Havoc old var var.new_idx() var.is_local = False # Assume loop 0 <= index < |array| loop_idx_ge_zero = self.viper_ast.GeCmp(loop_idx_local_var, self.viper_ast.IntLit(0), rpos) times_lit = self.viper_ast.IntLit(times) loop_idx_lt_array_size = self.viper_ast.LtCmp(loop_idx_local_var, times_lit, rpos) loop_idx_assumption = self.viper_ast.And(loop_idx_ge_zero, loop_idx_lt_array_size, rpos) res.append(loop_idx_assumption) # Set loop variable to array[index] array_at = self.viper_ast.SeqIndex(array_local_var, loop_idx_local_var, rpos) if has_numeric_array: array_at = helpers.w_wrap(self.viper_ast, array_at) set_loop_var = self.viper_ast.EqCmp(loop_var.local_var(ctx), array_at, lpos) res.append(set_loop_var) with ctx.old_local_variables_scope(loop_used_var): with ctx.state_scope(ctx.current_state, ctx.current_state): for loop_invariant in loop_invariants: cond_pos = self.to_position(loop_invariant, ctx) inv = self.specification_translator.translate_pre_or_postcondition(loop_invariant, res, ctx) inv_var = TranslatedPureIndexedVar('inv', 'inv', VYPER_BOOL, self.viper_ast, cond_pos) inv_local_var = inv_var.local_var(ctx) assign = self.viper_ast.EqCmp(inv_local_var, inv, cond_pos) expr = self.viper_ast.Implies(pre_conds, assign, cond_pos) if pre_conds else assign res.append(expr) ctx.pure_conds = self.viper_ast.And(ctx.pure_conds, inv_local_var, pos)\ if ctx.pure_conds else inv_local_var # Store state before loop body pre_locals = self._local_variable_snapshot(ctx) pre_loop_iteration_conds = ctx.pure_conds # Loop Body with ctx.break_scope(): with ctx.continue_scope(): with self.assignment_translator.assume_everything_has_wrapped_information(): with ctx.new_local_scope(): self.translate_stmts(node.body, res, ctx) ctx.pure_conds = pre_loop_iteration_conds # After loop body increase idx loop_idx_inc = self.viper_ast.Add(loop_idx_local_var, self.viper_ast.IntLit(1), pos) loop_idx_var.new_idx() loop_idx_local_var = loop_idx_var.local_var(ctx) res.append(self.viper_ast.EqCmp(loop_idx_local_var, loop_idx_inc, pos)) # Break if we reached the end of the array we iterate over loop_idx_eq_times = self.viper_ast.EqCmp(loop_idx_local_var, times_lit, pos) cond_var = TranslatedPureIndexedVar('cond', 'cond', VYPER_BOOL, self.viper_ast, pos) cond_local_var = cond_var.local_var(ctx) res.append(self.viper_ast.EqCmp(cond_local_var, loop_idx_eq_times, pos)) break_cond = self.viper_ast.And(ctx.pure_conds, cond_local_var, pos)\ if ctx.pure_conds else cond_local_var ctx.pure_breaks.append((break_cond, self._local_variable_snapshot(ctx))) # Assume that only one of the breaks happened only_one_break_cond = self._xor_conds([x for x, _ in ctx.pure_breaks]) assert only_one_break_cond is not None if pre_conds is None: res.append(only_one_break_cond) else: res.append(self.viper_ast.Implies(pre_conds, only_one_break_cond)) # Merge snapshots prev_snapshot = pre_locals for cond, snapshot in reversed(ctx.pure_breaks): prev_snapshot = self._merge_snapshots(cond, snapshot, prev_snapshot, res, ctx) else: # Unroll loop if we have no loop invariants pre_loop_locals = self._local_variable_snapshot(ctx) with ctx.break_scope(): for i in range(times): pre_loop_iteration_conds = ctx.pure_conds with ctx.continue_scope(): idx = self.viper_ast.IntLit(i, lpos) array_at = self.viper_ast.SeqIndex(array_local_var, idx, rpos) if has_numeric_array: array_at = helpers.w_wrap(self.viper_ast, array_at) loop_var.new_idx() var_set = self.viper_ast.EqCmp(loop_var.local_var(ctx), array_at, lpos) res.append(var_set) pre_it_locals = self._local_variable_snapshot(ctx) with self.assignment_translator.assume_everything_has_wrapped_information(): with ctx.new_local_scope(): self.translate_stmts(node.body, res, ctx) post_it_locals = self._local_variable_snapshot(ctx) ctx.pure_continues.append((ctx.pure_conds, post_it_locals)) prev_snapshot = pre_it_locals for cond, snapshot in reversed(ctx.pure_continues): prev_snapshot = self._merge_snapshots(cond, snapshot, prev_snapshot, res, ctx) ctx.pure_conds = pre_loop_iteration_conds post_loop_locals = self._local_variable_snapshot(ctx) ctx.pure_breaks.append((ctx.pure_conds, post_loop_locals)) prev_snapshot = pre_loop_locals for cond, snapshot in reversed(ctx.pure_breaks): prev_snapshot = self._merge_snapshots(cond, snapshot, prev_snapshot, res, ctx) ctx.pure_conds = pre_conds def translate_Break(self, node: ast.Break, res: List[Expr], ctx: Context): ctx.pure_breaks.append((ctx.pure_conds, self._local_variable_snapshot(ctx))) ctx.pure_conds = self.viper_ast.FalseLit() def translate_Continue(self, node: ast.Continue, res: List[Expr], ctx: Context): ctx.pure_continues.append((ctx.pure_conds, self._local_variable_snapshot(ctx))) ctx.pure_conds = self.viper_ast.FalseLit() def translate_Pass(self, node: ast.Pass, res: List[Expr], ctx: Context): pass def _add_local_var(self, node: ast.Name, ctx: Context): """ Adds the local variable to the context. """ pos = self.to_position(node, ctx) variable_name = node.id mangled_name = ctx.new_local_var_name(variable_name) var = TranslatedPureIndexedVar(variable_name, mangled_name, node.type, self.viper_ast, pos) ctx.locals[variable_name] = var def _xor_conds(self, conds: List[Expr]) -> Optional[Expr]: xor_cond = None for i in range(len(conds)): prev = None for idx, cond in enumerate(conds): and_cond = cond if idx == i else self.viper_ast.Not(cond) prev = self.viper_ast.And(prev, and_cond) if prev else and_cond xor_cond = self.viper_ast.Or(xor_cond, prev) if xor_cond else prev return xor_cond @staticmethod def _local_variable_snapshot(ctx) -> LocalVarSnapshot: return dict(((name, (var.evaluate_idx(ctx), var.local_var(ctx), var.is_local)) for name, var in ctx.locals.items() if isinstance(var, TranslatedPureIndexedVar))) @staticmethod def _reset_variable_to_snapshot(snapshot: LocalVarSnapshot, ctx): for name in snapshot.keys(): var = ctx.locals[name] assert isinstance(var, TranslatedPureIndexedVar) var.idx, _, var.is_local = snapshot[name] def _merge_snapshots(self, merge_cond: Optional[Expr], first_snapshot: LocalVarSnapshot, second_snapshot: LocalVarSnapshot, res: List[Expr], ctx: Context) -> LocalVarSnapshot: res_snapshot = {} names = set(first_snapshot.keys()) | set(second_snapshot.keys()) for name in names: first_idx_and_var = first_snapshot.get(name) second_idx_and_var = second_snapshot.get(name) if first_idx_and_var and second_idx_and_var: then_idx, then_var, then_is_local = first_idx_and_var else_idx, else_var, else_is_local = second_idx_and_var var = ctx.locals[name] assert isinstance(var, TranslatedPureIndexedVar) if else_idx != then_idx: var.new_idx() var.is_local = then_is_local and else_is_local cond = merge_cond or self.viper_ast.TrueLit() expr = self.viper_ast.CondExp(cond, then_var, else_var) assign = self.viper_ast.EqCmp(var.local_var(ctx), expr) res.append(assign) res_snapshot[name] = (var.evaluate_idx(ctx), var.local_var(ctx), var.is_local) else: res_snapshot[name] = first_idx_and_var or second_idx_and_var return res_snapshot class _AssignmentTranslator(PureTranslatorMixin, AssignmentTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.expression_translator = PureExpressionTranslator(viper_ast) self.type_translator = PureTypeTranslator(viper_ast) @property def method_name(self) -> str: return 'assign_to' def assign_to(self, node: ast.Node, value: Expr, res: List[Expr], ctx: Context): return self.visit(node, value, res, ctx) def generic_visit(self, node, *args): assert False def assign_to_Name(self, node: ast.Name, value: Expr, res: List[Expr], ctx: Context): pos = self.to_position(node, ctx) var = ctx.locals.get(node.id) w_value = value if var: if isinstance(var, TranslatedPureIndexedVar): var.new_idx() if (types.is_numeric(node.type) and not var.is_local and self.expression_translator.arithmetic_translator.is_unwrapped(value)): w_value = helpers.w_wrap(self.viper_ast, value) elif (types.is_numeric(node.type) and var.is_local and self.expression_translator.arithmetic_translator.is_wrapped(value)): var.is_local = False elif (types.is_numeric(node.type) and self._always_wrap and var.is_local and self.expression_translator.arithmetic_translator.is_unwrapped(value)): var.is_local = False w_value = helpers.w_wrap(self.viper_ast, value) elif (not types.is_numeric(node.type) and self.expression_translator.arithmetic_translator.is_wrapped(value)): w_value = helpers.w_unwrap(self.viper_ast, value) lhs = self.expression_translator.translate(node, res, ctx) assign = self.viper_ast.EqCmp(lhs, w_value, pos) expr = self.viper_ast.Implies(ctx.pure_conds, assign, pos) if ctx.pure_conds else assign res.append(expr) def assign_to_Attribute(self, node: ast.Attribute, value: Expr, res: List[Expr], ctx: Context): assert isinstance(node.value.type, StructType) return super().assign_to_Attribute(node, value, res, ctx) def assign_to_ReceiverCall(self, node: ast.ReceiverCall, value, ctx: Context): raise UnsupportedException(node, "Assignments to calls are not supported.")
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/pure_statement.py
pure_statement.py
from functools import reduce from typing import Callable, List, Union from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.nodes import VyperProgram from twovyper.translation import helpers, mangled from twovyper.translation.abstract import CommonTranslator from twovyper.translation.context import Context from twovyper.translation.model import ModelTranslator from twovyper.translation.resource import ResourceTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedVar from twovyper.verification import rules from twovyper.verification.rules import Rule from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt, Trigger class AllocationTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.model_translator = ModelTranslator(viper_ast) self.resource_translator = ResourceTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) @property def specification_translator(self): from twovyper.translation.specification import SpecificationTranslator return SpecificationTranslator(self.viper_ast) def _quantifier(self, expr: Expr, _: List[Trigger], ctx: Context, pos=None) -> Expr: type_assumptions = [] qvars = [] for var in ctx.quantified_vars.values(): type_assumptions.extend(self.type_translator.type_assumptions(var.local_var(ctx, pos), var.type, ctx)) qvars.append(var.var_decl(ctx)) cond = reduce(lambda a, b: self.viper_ast.And(a, b, pos), type_assumptions, self.viper_ast.TrueLit(pos)) # TODO: select good triggers return self.viper_ast.Forall(qvars, [], self.viper_ast.Implies(cond, expr, pos), pos) def get_allocated_map(self, allocated: Expr, resource: Expr, ctx: Context, pos=None) -> Expr: """ Returns the allocated map for a resource. """ allocated_type = helpers.allocated_type() key_type = self.type_translator.translate(allocated_type.key_type, ctx) value_type = self.type_translator.translate(allocated_type.value_type, ctx) map_get = helpers.map_get(self.viper_ast, allocated, resource, key_type, value_type, pos) return map_get def set_allocated_map(self, allocated: Expr, resource: Expr, new_value: Expr, ctx: Context, pos=None) -> Expr: allocated_type = helpers.allocated_type() key_type = self.type_translator.translate(allocated_type.key_type, ctx) value_type = self.type_translator.translate(allocated_type.value_type, ctx) return helpers.map_set(self.viper_ast, allocated, resource, new_value, key_type, value_type, pos) def get_allocated(self, allocated: Expr, resource: Expr, address: Expr, ctx: Context, pos=None) -> Expr: allocated_type = helpers.allocated_type() key_type = self.type_translator.translate(allocated_type.value_type.key_type, ctx) value_type = self.type_translator.translate(allocated_type.value_type.value_type, ctx) allocated_map = self.get_allocated_map(allocated, resource, ctx, pos) map_get = helpers.map_get(self.viper_ast, allocated_map, address, key_type, value_type, pos) return map_get def get_offered_map(self, offered: Expr, from_resource: Expr, to_resource: Expr, ctx: Context, pos=None) -> Expr: """ Returns the offered map for a pair of resources. """ offered_type = helpers.offered_type() key1_type = self.type_translator.translate(offered_type.key_type, ctx) value1_type = self.type_translator.translate(offered_type.value_type, ctx) offered1 = helpers.map_get(self.viper_ast, offered, from_resource, key1_type, value1_type, pos) key2_type = self.type_translator.translate(offered_type.value_type.key_type, ctx) value2_type = self.type_translator.translate(offered_type.value_type.value_type, ctx) map_get = helpers.map_get(self.viper_ast, offered1, to_resource, key2_type, value2_type, pos) return map_get def set_offered_map(self, offered: Expr, from_resource: Expr, to_resource: Expr, new_value: Expr, ctx: Context, pos=None) -> Expr: offered_type = helpers.offered_type() outer_key_type = self.type_translator.translate(offered_type.key_type, ctx) outer_value_type = self.type_translator.translate(offered_type.value_type, ctx) inner_key_type = self.type_translator.translate(offered_type.value_type.key_type, ctx) inner_value_type = self.type_translator.translate(offered_type.value_type.value_type, ctx) inner_map = helpers.map_get(self.viper_ast, offered, from_resource, outer_key_type, outer_value_type, pos) new_inner = helpers.map_set(self.viper_ast, inner_map, to_resource, new_value, inner_key_type, inner_value_type, pos) return helpers.map_set(self.viper_ast, offered, from_resource, new_inner, outer_key_type, outer_value_type, pos) def get_offered(self, offered: Expr, from_resource: Expr, to_resource: Expr, from_val: Expr, to_val: Expr, from_addr: Expr, to_addr: Expr, ctx: Context, pos=None) -> Expr: offered_type = helpers.offered_type() offered_map = self.get_offered_map(offered, from_resource, to_resource, ctx, pos) offer = helpers.offer(self.viper_ast, from_val, to_val, from_addr, to_addr, pos) key_type = self.type_translator.translate(offered_type.value_type.value_type.key_type, ctx) value_type = self.type_translator.translate(offered_type.value_type.value_type.value_type, ctx) map_get = helpers.map_get(self.viper_ast, offered_map, offer, key_type, value_type, pos) return map_get def set_offered(self, offered: Expr, from_resource: Expr, to_resource: Expr, from_val: Expr, to_val: Expr, from_addr: Expr, to_addr: Expr, new_value: Expr, ctx: Context, pos=None) -> Expr: offered_type = helpers.offered_type() offered_map = self.get_offered_map(offered, from_resource, to_resource, ctx, pos) key_type = self.type_translator.translate(offered_type.value_type.value_type.key_type, ctx) value_type = self.type_translator.translate(offered_type.value_type.value_type.value_type, ctx) offer = helpers.offer(self.viper_ast, from_val, to_val, from_addr, to_addr, pos) set_offered = helpers.map_set(self.viper_ast, offered_map, offer, new_value, key_type, value_type, pos) return self.set_offered_map(offered, from_resource, to_resource, set_offered, ctx, pos) def get_trusted_map(self, trusted: Expr, where: Expr, ctx: Context, pos=None): trusted_type = helpers.trusted_type() key_type = self.type_translator.translate(trusted_type.key_type, ctx) value_type = self.type_translator.translate(trusted_type.value_type, ctx) return helpers.map_get(self.viper_ast, trusted, where, key_type, value_type, pos) def get_trusted(self, trusted: Expr, where: Expr, address: Expr, by_address: Expr, ctx: Context, pos=None) -> Expr: """ Returns the trusted map for a pair of addresses. """ trusted_type = helpers.trusted_type() key1_type = self.type_translator.translate(trusted_type.key_type, ctx) value1_type = self.type_translator.translate(trusted_type.value_type, ctx) trusted1 = helpers.map_get(self.viper_ast, trusted, where, key1_type, value1_type, pos) key2_type = self.type_translator.translate(trusted_type.value_type.key_type, ctx) value2_type = self.type_translator.translate(trusted_type.value_type.value_type, ctx) trusted2 = helpers.map_get(self.viper_ast, trusted1, address, key2_type, value2_type, pos) key3_type = self.type_translator.translate(trusted_type.value_type.value_type.key_type, ctx) value3_type = self.type_translator.translate(trusted_type.value_type.value_type.value_type, ctx) map_get = helpers.map_get(self.viper_ast, trusted2, by_address, key3_type, value3_type, pos) return map_get def set_trusted(self, trusted: Expr, where: Expr, address: Expr, by_address: Expr, new_value: Expr, ctx: Context, pos=None) -> Expr: trusted_type = helpers.trusted_type() key1_type = self.type_translator.translate(trusted_type.key_type, ctx) value1_type = self.type_translator.translate(trusted_type.value_type, ctx) middle_map = helpers.map_get(self.viper_ast, trusted, where, key1_type, value1_type, pos) key2_type = self.type_translator.translate(trusted_type.value_type.key_type, ctx) value2_type = self.type_translator.translate(trusted_type.value_type.value_type, ctx) inner_map = helpers.map_get(self.viper_ast, middle_map, address, key2_type, value2_type, pos) key3_type = self.type_translator.translate(trusted_type.value_type.value_type.key_type, ctx) value3_type = self.type_translator.translate(trusted_type.value_type.value_type.value_type, ctx) new_inner = helpers.map_set(self.viper_ast, inner_map, by_address, new_value, key3_type, value3_type, pos) new_middle = helpers.map_set(self.viper_ast, middle_map, address, new_inner, key2_type, value2_type, pos) return helpers.map_set(self.viper_ast, trusted, where, new_middle, key1_type, value1_type, pos) def _check_allocation(self, node: ast.Node, resource: Expr, address: Expr, value: Expr, rule: Rule, res: List[Stmt], ctx: Context, pos=None): """ Checks that `address` has at least `amount` of `resource` allocated to them. """ if ctx.inside_interface_call: return allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx, pos) get_alloc = self.get_allocated(allocated, resource, address, ctx, pos) cond = self.viper_ast.LeCmp(value, get_alloc, pos) if ctx.quantified_vars: trigger = self.viper_ast.Trigger([get_alloc], pos) cond = self._quantifier(cond, [trigger], ctx, pos) modelt = self.model_translator.save_variables(res, ctx, pos) apos = self.to_position(node, ctx, rule, modelt=modelt) res.append(self.viper_ast.Assert(cond, apos)) def _check_creator(self, node: ast.Node, creator_resource: Expr, address: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): """ Checks that `address` is allowed to create `amount` resources by checking that the allocated amount of `creator_resource` is positive if `amount` > 0 """ zero = self.viper_ast.IntLit(0, pos) one = self.viper_ast.IntLit(1, pos) gtz = self.viper_ast.GtCmp(amount, zero, pos) cond = self.viper_ast.CondExp(gtz, one, zero, pos) rule = rules.CREATE_FAIL_NOT_A_CREATOR self._check_allocation(node, creator_resource, address, cond, rule, res, ctx, pos) def _check_from_agrees(self, node: ast.Node, from_resource: Expr, to_resource: Expr, from_val: Expr, to_val: Expr, from_addr: Expr, to_addr: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): """ Checks that `from_addr` offered to exchange `from_val` for `to_val` to `to_addr`. """ if ctx.inside_interface_call: return offered = ctx.current_state[mangled.OFFERED].local_var(ctx, pos) modelt = self.model_translator.save_variables(res, ctx, pos) get_offered = self.get_offered(offered, from_resource, to_resource, from_val, to_val, from_addr, to_addr, ctx, pos) cond = self.viper_ast.LeCmp(amount, get_offered, pos) apos = self.to_position(node, ctx, rules.EXCHANGE_FAIL_NO_OFFER, modelt=modelt) res.append(self.viper_ast.Assert(cond, apos)) def _change_allocation(self, resource: Expr, address: Expr, value: Expr, increase: bool, res: List[Stmt], ctx: Context, pos=None): allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx, pos) get_alloc = self.get_allocated(allocated, resource, address, ctx, pos) func = self.viper_ast.Add if increase else self.viper_ast.Sub new_value = func(get_alloc, value, pos) key_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) value_type = self.type_translator.translate(types.VYPER_WEI_VALUE, ctx) alloc_map = self.get_allocated_map(allocated, resource, ctx, pos) set_alloc = helpers.map_set(self.viper_ast, alloc_map, address, new_value, key_type, value_type, pos) set_alloc_map = self.set_allocated_map(allocated, resource, set_alloc, ctx, pos) alloc_assign = self.viper_ast.LocalVarAssign(allocated, set_alloc_map, pos) res.append(alloc_assign) def _foreach_change_allocation(self, resource: Expr, address: Expr, amount: Expr, op: Callable[[Expr, Expr, Expr], Expr], res: List[Stmt], ctx: Context, pos=None): allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx, pos) self._inhale_allocation(resource, address, amount, res, ctx, pos) allocated_type = self.type_translator.translate(helpers.allocated_type(), ctx) fresh_allocated_name = ctx.new_local_var_name(names.ALLOCATED) fresh_allocated_decl = self.viper_ast.LocalVarDecl(fresh_allocated_name, allocated_type, pos) ctx.new_local_vars.append(fresh_allocated_decl) fresh_allocated = fresh_allocated_decl.localVar() # Assume the values of the new map qaddr = self.viper_ast.LocalVarDecl('$a', self.viper_ast.Int, pos) qaddr_var = qaddr.localVar() qres = self.viper_ast.LocalVarDecl('$r', helpers.struct_type(self.viper_ast), pos) qres_var = qres.localVar() fresh_allocated_get = self.get_allocated(fresh_allocated, qres_var, qaddr_var, ctx, pos) old_allocated_get = self.get_allocated(allocated, qres_var, qaddr_var, ctx, pos) allocation_pred = helpers.allocation_predicate(self.viper_ast, qres_var, qaddr_var, pos) perm = self.viper_ast.CurrentPerm(allocation_pred, pos) expr = op(fresh_allocated_get, old_allocated_get, perm) trigger = self.viper_ast.Trigger([fresh_allocated_get], pos) quant = self.viper_ast.Forall([qaddr, qres], [trigger], expr, pos) assume = self.viper_ast.Inhale(quant, pos) res.append(assume) # Set the new allocated allocated_assign = self.viper_ast.LocalVarAssign(allocated, fresh_allocated, pos) res.append(allocated_assign) # Heap clean-up self._exhale_allocation(res, ctx, pos) def _inhale_allocation(self, resource: Expr, address: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): allocation = helpers.allocation_predicate(self.viper_ast, resource, address, pos) perm = self.viper_ast.IntPermMul(amount, self.viper_ast.FullPerm(pos), pos) acc_allocation = self.viper_ast.PredicateAccessPredicate(allocation, perm, pos) trigger = self.viper_ast.Trigger([allocation], pos) quant = self._quantifier(acc_allocation, [trigger], ctx, pos) # TODO: rule res.append(self.viper_ast.Inhale(quant, pos)) def _exhale_allocation(self, res: List[Stmt], _: Context, pos=None): # We use an implication with a '> none' because of a bug in Carbon (TODO: issue #171) where it isn't possible # to exhale no permissions under a quantifier. qres = self.viper_ast.LocalVarDecl('$r', helpers.struct_type(self.viper_ast), pos) qaddr = self.viper_ast.LocalVarDecl('$a', self.viper_ast.Int, pos) allocation = helpers.allocation_predicate(self.viper_ast, qres.localVar(), qaddr.localVar(), pos) perm = self.viper_ast.CurrentPerm(allocation, pos) cond = self.viper_ast.GtCmp(perm, self.viper_ast.NoPerm(pos), pos) acc_allocation = self.viper_ast.PredicateAccessPredicate(allocation, perm, pos) trigger = self.viper_ast.Trigger([allocation], pos) quant = self.viper_ast.Forall([qres, qaddr], [trigger], self.viper_ast.Implies(cond, acc_allocation, pos), pos) # TODO: rule res.append(self.viper_ast.Exhale(quant, pos)) def _exhale_trust(self, res: List[Stmt], _: Context, pos=None): # We use an implication with a '> none' because of a bug in Carbon (TODO: issue #171) where it isn't possible # to exhale no permissions under a quantifier. qwhere = self.viper_ast.LocalVarDecl('$where', self.viper_ast.Int, pos) qwhom = self.viper_ast.LocalVarDecl('$whom', self.viper_ast.Int, pos) qwho = self.viper_ast.LocalVarDecl('$who', self.viper_ast.Int, pos) trust = helpers.trust_predicate(self.viper_ast, qwhere.localVar(), qwhom.localVar(), qwho.localVar(), pos) perm = self.viper_ast.CurrentPerm(trust, pos) cond = self.viper_ast.GtCmp(perm, self.viper_ast.NoPerm(pos), pos) acc_allocation = self.viper_ast.PredicateAccessPredicate(trust, perm, pos) trigger = self.viper_ast.Trigger([trust], pos) quant = self.viper_ast.Forall([qwhere, qwhom, qwho], [trigger], self.viper_ast.Implies(cond, acc_allocation, pos), pos) # TODO: rule res.append(self.viper_ast.Exhale(quant, pos)) def _set_offered(self, from_resource: Expr, to_resource: Expr, from_val: Expr, to_val: Expr, from_addr: Expr, to_addr: Expr, new_value: Expr, res: List[Stmt], ctx: Context, pos=None): offered = ctx.current_state[mangled.OFFERED].local_var(ctx, pos) set_offered = self.set_offered(offered, from_resource, to_resource, from_val, to_val, from_addr, to_addr, new_value, ctx, pos) offered_assign = self.viper_ast.LocalVarAssign(offered, set_offered, pos) res.append(offered_assign) def _change_offered(self, from_resource: Expr, to_resource: Expr, from_val: Expr, to_val: Expr, from_addr: Expr, to_addr: Expr, amount: Expr, increase: bool, res: List[Stmt], ctx: Context, pos=None): offered = ctx.current_state[mangled.OFFERED].local_var(ctx, pos) get_offered = self.get_offered(offered, from_resource, to_resource, from_val, to_val, from_addr, to_addr, ctx, pos) func = self.viper_ast.Add if increase else self.viper_ast.Sub new_value = func(get_offered, amount, pos) self._set_offered(from_resource, to_resource, from_val, to_val, from_addr, to_addr, new_value, res, ctx, pos) def _foreach_change_offered(self, from_resource: Expr, to_resource: Expr, from_value: Expr, to_value: Expr, from_owner: Expr, to_owner: Expr, times: Expr, op: Callable[[Expr, Expr, Expr], Expr], res: List[Stmt], ctx: Context, pos=None): offered = ctx.current_state[mangled.OFFERED].local_var(ctx, pos) self._inhale_offers(from_resource, to_resource, from_value, to_value, from_owner, to_owner, times, res, ctx, pos) # Declare the new offered offered_type = self.type_translator.translate(helpers.offered_type(), ctx) fresh_offered_name = ctx.new_local_var_name(names.OFFERED) fresh_offered_decl = self.viper_ast.LocalVarDecl(fresh_offered_name, offered_type, pos) ctx.new_local_vars.append(fresh_offered_decl) fresh_offered = fresh_offered_decl.localVar() # Assume the values of the new map qvar_types = 2 * [helpers.struct_type(self.viper_ast)] + 4 * [self.viper_ast.Int] qvars = [self.viper_ast.LocalVarDecl(f'$arg{i}', t, pos) for i, t in enumerate(qvar_types)] qlocals = [var.localVar() for var in qvars] fresh_offered_get = self.get_offered(fresh_offered, *qlocals, ctx, pos) old_offered_get = self.get_offered(offered, *qlocals, ctx, pos) offer_pred = helpers.offer_predicate(self.viper_ast, *qlocals, pos) perm = self.viper_ast.CurrentPerm(offer_pred, pos) expr = op(fresh_offered_get, old_offered_get, perm) trigger = self.viper_ast.Trigger([fresh_offered_get], pos) quant = self.viper_ast.Forall(qvars, [trigger], expr, pos) assume = self.viper_ast.Inhale(quant, pos) res.append(assume) # Assume the no_offers stayed the same for all others qvar_types = 1 * [helpers.struct_type(self.viper_ast)] + 1 * [self.viper_ast.Int] qvars = [self.viper_ast.LocalVarDecl(f'$arg{i}', t, pos) for i, t in enumerate(qvar_types)] qlocals = [var.localVar() for var in qvars] context_qvars = [qvar.local_var(ctx) for qvar in ctx.quantified_vars.values()] fresh_no_offers = helpers.no_offers(self.viper_ast, fresh_offered, *qlocals, pos) old_no_offers = helpers.no_offers(self.viper_ast, offered, *qlocals, pos) nodes_in_from_resource = self.viper_ast.to_list(from_resource) if any(qvar in nodes_in_from_resource for qvar in context_qvars): resource_eq = self.viper_ast.TrueLit() else: resource_eq = self.viper_ast.EqCmp(qlocals[0], from_resource, pos) nodes_in_from_owner = self.viper_ast.to_list(from_owner) if any(qvar in nodes_in_from_owner for qvar in context_qvars): address_eq = self.viper_ast.TrueLit() else: address_eq = self.viper_ast.EqCmp(qlocals[1], from_owner, pos) cond = self.viper_ast.Not(self.viper_ast.And(resource_eq, address_eq, pos), pos) expr = self.viper_ast.EqCmp(fresh_no_offers, old_no_offers, pos) expr = self.viper_ast.Implies(cond, expr, pos) trigger = self.viper_ast.Trigger([fresh_no_offers], pos) quant = self.viper_ast.Forall(qvars, [trigger], expr, pos) assume = self.viper_ast.Inhale(quant, pos) res.append(assume) # Set the new offered offered_assign = self.viper_ast.LocalVarAssign(offered, fresh_offered, pos) res.append(offered_assign) # Heap clean-up self._exhale_offers(res, ctx, pos) def _inhale_offers(self, from_resource: Expr, to_resource: Expr, from_val: Expr, to_val: Expr, from_addr: Expr, to_addr: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): offer = helpers.offer_predicate(self.viper_ast, from_resource, to_resource, from_val, to_val, from_addr, to_addr, pos) perm = self.viper_ast.IntPermMul(amount, self.viper_ast.FullPerm(pos), pos) acc_offer = self.viper_ast.PredicateAccessPredicate(offer, perm, pos) trigger = self.viper_ast.Trigger([offer], pos) quant = self._quantifier(acc_offer, [trigger], ctx, pos) # TODO: rule res.append(self.viper_ast.Inhale(quant, pos)) def _exhale_offers(self, res: List[Stmt], _: Context, pos=None): # We clean up the heap by exhaling all permissions to offer. # exhale forall a, b, c, d: Int :: perm(offer(a, b, c, d)) > none ==> # acc(offer(a, b, c, d), perm(offer(a, b, c, d))) # We use an implication with a '> none' because of a bug in Carbon (TODO: issue #171) where it isn't possible # to exhale no permissions under a quantifier. qvar_types = 2 * [helpers.struct_type(self.viper_ast)] + 4 * [self.viper_ast.Int] qvars = [self.viper_ast.LocalVarDecl(f'$arg{i}', t, pos) for i, t in enumerate(qvar_types)] qvars_locals = [var.localVar() for var in qvars] offer = helpers.offer_predicate(self.viper_ast, *qvars_locals, pos) perm = self.viper_ast.CurrentPerm(offer, pos) cond = self.viper_ast.GtCmp(perm, self.viper_ast.NoPerm(pos), pos) acc_offer = self.viper_ast.PredicateAccessPredicate(offer, perm, pos) trigger = self.viper_ast.Trigger([offer], pos) quant = self.viper_ast.Forall(qvars, [trigger], self.viper_ast.Implies(cond, acc_offer, pos), pos) # TODO: rule res.append(self.viper_ast.Exhale(quant, pos)) def _if_non_zero_values(self, fun: Callable[[List[Stmt]], None], amounts: Union[List[Expr], Expr], res: List[Stmt], ctx: Context, pos=None): then = [] fun(then) zero = self.viper_ast.IntLit(0, pos) if isinstance(amounts, list): amount_checks = [self.viper_ast.NeCmp(amount, zero, pos) for amount in amounts] is_not_zero = reduce(self.viper_ast.And, amount_checks) if amount_checks else self.viper_ast.TrueLit() else: is_not_zero = self.viper_ast.NeCmp(amounts, zero, pos) if ctx.quantified_vars: quantified_vars = [q_var.var_decl(ctx) for q_var in ctx.quantified_vars.values()] is_not_zero = self.viper_ast.Forall(quantified_vars, [], is_not_zero) res.extend(helpers.flattened_conditional(self.viper_ast, is_not_zero, then, [], pos)) def _check_trusted_if_non_zero_amount(self, node: ast.Node, address: Expr, by_address: Expr, amounts: Union[List[Expr], Expr], rule: rules.Rule, res: List[Stmt], ctx: Context, pos=None): """ Only check trusted if all values are non-zero. """ self._if_non_zero_values(lambda l: self._check_trusted(node, address, by_address, rule, l, ctx, pos), amounts, res, ctx, pos) def _check_trusted(self, node: ast.Node, address: Expr, by_address: Expr, rule: rules.Rule, res: List[Stmt], ctx: Context, pos=None): if ctx.inside_interface_call: return where = ctx.self_address or helpers.self_address(self.viper_ast, pos) trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx, pos) get_trusted = self.get_trusted(trusted, where, address, by_address, ctx, pos) eq = self.viper_ast.EqCmp(address, by_address, pos) cond = self.viper_ast.Or(eq, get_trusted, pos) if ctx.quantified_vars: trigger = self.viper_ast.Trigger([get_trusted], pos) cond = self._quantifier(cond, [trigger], ctx, pos) modelt = self.model_translator.save_variables(res, ctx, pos) combined_rule = rules.combine(rules.NOT_TRUSTED_FAIL, rule) apos = self.to_position(node, ctx, combined_rule, modelt=modelt) res.append(self.viper_ast.Assert(cond, apos)) def _change_trusted(self, address: Expr, by_address: Expr, new_value: Expr, res: List[Stmt], ctx: Context, pos=None): where = ctx.self_address or helpers.self_address(self.viper_ast, pos) trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx, pos) set_trusted = self.set_trusted(trusted, where, address, by_address, new_value, ctx, pos) trusted_assign = self.viper_ast.LocalVarAssign(trusted, set_trusted, pos) res.append(trusted_assign) def _foreach_change_trusted(self, address: Expr, by_address: Expr, new_value: Expr, res: List[Stmt], ctx: Context, pos=None): where = ctx.self_address or helpers.self_address(self.viper_ast, pos) trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx, pos) self._inhale_trust(where, address, by_address, res, ctx, pos) trusted_type = self.type_translator.translate(helpers.trusted_type(), ctx) fresh_trusted_name = ctx.new_local_var_name(names.TRUSTED) fresh_trusted_decl = self.viper_ast.LocalVarDecl(fresh_trusted_name, trusted_type, pos) ctx.new_local_vars.append(fresh_trusted_decl) fresh_trusted = fresh_trusted_decl.localVar() # Assume the values of the new map qaddr = self.viper_ast.LocalVarDecl('$a', self.viper_ast.Int, pos) qaddr_var = qaddr.localVar() qby = self.viper_ast.LocalVarDecl('$b', self.viper_ast.Int, pos) qby_var = qby.localVar() qwhere = self.viper_ast.LocalVarDecl('$c', self.viper_ast.Int, pos) qwhere_var = qwhere.localVar() fresh_trusted_get = self.get_trusted(fresh_trusted, qwhere_var, qaddr_var, qby_var, ctx, pos) old_trusted_get = self.get_trusted(trusted, qwhere_var, qaddr_var, qby_var, ctx, pos) trust_pred = helpers.trust_predicate(self.viper_ast, qwhere_var, qaddr_var, qby_var, pos) perm = self.viper_ast.CurrentPerm(trust_pred, pos) gtz = self.viper_ast.PermGtCmp(perm, self.viper_ast.NoPerm(pos), pos) cond = self.viper_ast.CondExp(gtz, new_value, old_trusted_get, pos) eq = self.viper_ast.EqCmp(fresh_trusted_get, cond, pos) trigger = self.viper_ast.Trigger([fresh_trusted_get], pos) quant = self.viper_ast.Forall([qaddr, qby, qwhere], [trigger], eq, pos) assume = self.viper_ast.Inhale(quant, pos) res.append(assume) # Assume the trust_no_one stayed the same for all others qvar_types = [self.viper_ast.Int, self.viper_ast.Int] qvars = [self.viper_ast.LocalVarDecl(f'$arg{i}', t, pos) for i, t in enumerate(qvar_types)] qlocals = [var.localVar() for var in qvars] context_qvars = [qvar.local_var(ctx) for qvar in ctx.quantified_vars.values()] fresh_trust_no_one = helpers.trust_no_one(self.viper_ast, fresh_trusted, *qlocals, pos) old_trust_no_one = helpers.trust_no_one(self.viper_ast, trusted, *qlocals, pos) nodes_in_by_address = self.viper_ast.to_list(by_address) if any(qvar in nodes_in_by_address for qvar in context_qvars): by_address_eq = self.viper_ast.TrueLit() else: by_address_eq = self.viper_ast.EqCmp(qlocals[0], by_address, pos) nodes_in_where = self.viper_ast.to_list(where) if any(qvar in nodes_in_where for qvar in context_qvars): where_eq = self.viper_ast.TrueLit() else: where_eq = self.viper_ast.EqCmp(qlocals[1], where, pos) cond = self.viper_ast.Not(self.viper_ast.And(by_address_eq, where_eq, pos), pos) expr = self.viper_ast.EqCmp(fresh_trust_no_one, old_trust_no_one, pos) expr = self.viper_ast.Implies(cond, expr, pos) trigger = self.viper_ast.Trigger([fresh_trust_no_one], pos) quant = self.viper_ast.Forall(qvars, [trigger], expr, pos) assume = self.viper_ast.Inhale(quant, pos) res.append(assume) # Set the new trusted trusted_assign = self.viper_ast.LocalVarAssign(trusted, fresh_trusted, pos) res.append(trusted_assign) # Heap clean-up self._exhale_trust(res, ctx, pos) def _inhale_trust(self, where: Expr, address: Expr, by_address: Expr, res: List[Stmt], ctx: Context, pos=None): trust = helpers.trust_predicate(self.viper_ast, where, address, by_address, pos) perm = self.viper_ast.FullPerm(pos) acc_trust = self.viper_ast.PredicateAccessPredicate(trust, perm, pos) trigger = self.viper_ast.Trigger([trust], pos) quant = self._quantifier(acc_trust, [trigger], ctx, pos) # TODO: rule res.append(self.viper_ast.Inhale(quant, pos)) def _performs_acc_predicate(self, function: str, args: List[Expr], ctx: Context, pos=None) -> Expr: pred = helpers.performs_predicate(self.viper_ast, function, args, pos) cond = self.viper_ast.PredicateAccessPredicate(pred, self.viper_ast.FullPerm(pos), pos) if ctx.quantified_vars: cond = self._quantifier(cond, [], ctx, pos) return cond def _exhale_performs_if_non_zero_amount(self, node: ast.Node, function: str, args: List[Expr], amounts: Union[List[Expr], Expr], rule: Rule, res: List[Stmt], ctx: Context, pos=None): self._if_non_zero_values(lambda l: self._exhale_performs(node, function, args, rule, l, ctx, pos), amounts, res, ctx, pos) def _exhale_performs(self, node: ast.Node, function: str, args: List[Expr], rule: Rule, res: List[Stmt], ctx: Context, pos=None): if ctx.program.config.has_option(names.CONFIG_NO_PERFORMS): return if ctx.inside_interface_call: return pred_access_pred = self._performs_acc_predicate(function, args, ctx, pos) modelt = self.model_translator.save_variables(res, ctx, pos) combined_rule = rules.combine(rules.NO_PERFORMS_FAIL, rule) apos = self.to_position(node, ctx, combined_rule, modelt=modelt) res.append(self.viper_ast.Exhale(pred_access_pred, apos)) def check_performs(self, node: ast.Node, function: str, args: List[Expr], amounts: Union[List[Expr], Expr], rule: Rule, res: List[Stmt], ctx: Context, pos=None): self._exhale_performs_if_non_zero_amount(node, function, args, amounts, rule, res, ctx, pos) def allocate_derived(self, node: ast.Node, resource: Expr, address: Expr, actor: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): with ctx.self_address_scope(helpers.self_address(self.viper_ast)): self._check_trusted_if_non_zero_amount(node, actor, address, amount, rules.PAYABLE_FAIL, res, ctx, pos) self.allocate(resource, address, amount, res, ctx, pos) self.check_performs(node, names.RESOURCE_PAYABLE, [resource, address, amount], [amount], rules.PAYABLE_FAIL, res, ctx, pos) def allocate(self, resource: Expr, address: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): """ Adds `amount` allocation to the allocation map entry of `address`. """ self._change_allocation(resource, address, amount, True, res, ctx, pos) def reallocate(self, node: ast.Node, resource: Expr, frm: Expr, to: Expr, amount: Expr, actor: Expr, res: List[Stmt], ctx: Context, pos=None): """ Checks that `from` has sufficient allocation and then moves `amount` allocation from `frm` to `to`. """ stmts = [] self._exhale_performs_if_non_zero_amount(node, names.REALLOCATE, [resource, frm, to, amount], amount, rules.REALLOCATE_FAIL, stmts, ctx, pos) self._check_trusted_if_non_zero_amount(node, actor, frm, amount, rules.REALLOCATE_FAIL, stmts, ctx, pos) self._check_allocation(node, resource, frm, amount, rules.REALLOCATE_FAIL_INSUFFICIENT_FUNDS, stmts, ctx, pos) self._change_allocation(resource, frm, amount, False, stmts, ctx, pos) self._change_allocation(resource, to, amount, True, stmts, ctx, pos) self.seqn_with_info(stmts, "Reallocate", res) def deallocate_wei(self, node: ast.Node, address: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): no_derived_wei = ctx.program.config.has_option(names.CONFIG_NO_DERIVED_WEI) if no_derived_wei: resource, underlying_resource = None, self.resource_translator.underlying_wei_resource(ctx) else: resource, underlying_resource = self.resource_translator.translate_with_underlying(None, res, ctx) self_address = ctx.self_address or helpers.self_address(self.viper_ast) self.interface_performed(node, names.REALLOCATE, [underlying_resource, self_address, address, amount], amount, res, ctx, pos) if no_derived_wei: return self.deallocate_derived(node, resource, underlying_resource, address, amount, res, ctx, pos) def deallocate_derived(self, node: ast.Node, resource: Expr, underlying_resource: Expr, address: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None): """ Checks that `address` has sufficient allocation and then removes `amount` allocation from the allocation map entry of `address`. """ stmts = [] const_one = self.viper_ast.IntLit(1, pos) self._exhale_performs_if_non_zero_amount(node, names.RESOURCE_PAYOUT, [resource, address, amount], amount, rules.PAYOUT_FAIL, stmts, ctx, pos) offer_check_stmts = [] def check_offer(then): self._check_from_agrees(node, resource, underlying_resource, const_one, const_one, address, address, amount, then, ctx, pos) self._change_offered(resource, underlying_resource, const_one, const_one, address, address, amount, False, then, ctx, pos) self._if_non_zero_values(check_offer, amount, offer_check_stmts, ctx, pos) # Only check that there was an offer, if someone else than a trusted address performs the deallocation msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) where = ctx.self_address or helpers.self_address(self.viper_ast, pos) trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx, pos) is_trusted_address = self.get_trusted(trusted, where, msg_sender, address, ctx, pos) is_itself = self.viper_ast.EqCmp(msg_sender, address, pos) is_trusted_address = self.viper_ast.Or(is_itself, is_trusted_address, pos) not_trusted_address = self.viper_ast.Not(is_trusted_address, pos) stmts.extend(helpers.flattened_conditional(self.viper_ast, not_trusted_address, offer_check_stmts, [], pos)) self._check_allocation(node, resource, address, amount, rules.REALLOCATE_FAIL_INSUFFICIENT_FUNDS, stmts, ctx, pos) self._change_allocation(resource, address, amount, False, stmts, ctx, pos) self.seqn_with_info(stmts, "Deallocate", res) def create(self, node: ast.Node, resource: Expr, frm: Expr, to: Expr, amount: Expr, actor: Expr, is_init: bool, res: List[Stmt], ctx: Context, pos=None): stmts = [] self._exhale_performs_if_non_zero_amount(node, names.CREATE, [resource, frm, to, amount], amount, rules.CREATE_FAIL, stmts, ctx, pos) # The initializer is allowed to create all resources unchecked. if not is_init: def check(then): self._check_trusted(node, actor, frm, rules.CREATE_FAIL, then, ctx, pos) creator_resource = self.resource_translator.creator_resource(resource, ctx, pos) self._check_creator(node, creator_resource, frm, amount, then, ctx, pos) self._if_non_zero_values(check, amount, res, ctx, pos) if ctx.quantified_vars: def op(fresh: Expr, old: Expr, perm: Expr) -> Expr: write = self.viper_ast.FullPerm(pos) fresh_mul = self.viper_ast.IntPermMul(fresh, write, pos) old_mul = self.viper_ast.IntPermMul(old, write, pos) perm_add = self.viper_ast.PermAdd(old_mul, perm, pos) return self.viper_ast.EqCmp(fresh_mul, perm_add, pos) self._foreach_change_allocation(resource, to, amount, op, stmts, ctx, pos) else: self.allocate(resource, to, amount, stmts, ctx, pos) self.seqn_with_info(stmts, "Create", res) def destroy(self, node: ast.Node, resource: Expr, address: Expr, amount: Expr, actor: Expr, res: List[Stmt], ctx: Context, pos=None): """ Checks that `address` has sufficient allocation and then removes `amount` allocation from the allocation map entry of `address`. """ stmts = [] self._exhale_performs_if_non_zero_amount(node, names.DESTROY, [resource, address, amount], amount, rules.DESTROY_FAIL, stmts, ctx, pos) self._check_trusted_if_non_zero_amount(node, actor, address, amount, rules.DESTROY_FAIL, stmts, ctx, pos) self._check_allocation(node, resource, address, amount, rules.DESTROY_FAIL_INSUFFICIENT_FUNDS, stmts, ctx, pos) if ctx.quantified_vars: def op(fresh: Expr, old: Expr, perm: Expr) -> Expr: write = self.viper_ast.FullPerm(pos) fresh_mul = self.viper_ast.IntPermMul(fresh, write, pos) old_mul = self.viper_ast.IntPermMul(old, write, pos) perm_sub = self.viper_ast.PermSub(old_mul, perm, pos) return self.viper_ast.EqCmp(fresh_mul, perm_sub, pos) self._foreach_change_allocation(resource, address, amount, op, stmts, ctx, pos) else: self._change_allocation(resource, address, amount, False, stmts, ctx, pos) return self.seqn_with_info(stmts, "Destroy", res) def _allocation_leak_check(self, node: ast.Node, rule: Rule, res: List[Stmt], ctx: Context, pos=None): """ Checks that the invariant knows about all ether allocated to the individual addresses, i.e., that given only the invariant and the state it is known for each address how much of the ether is allocated to them. """ # To do a leak check we create a fresh allocation map, assume the invariants for the current state and # the fresh map and then check that the fresh map only specified from the invariants is equal to the # actual map. This ensures that the invariant fully specifies the allocation map. spec_translator = self.specification_translator allocated = ctx.current_state[mangled.ALLOCATED] new_allocated_name = ctx.new_local_var_name(mangled.ALLOCATED) fresh_allocated = TranslatedVar(mangled.ALLOCATED, new_allocated_name, allocated.type, self.viper_ast, pos) ctx.new_local_vars.append(fresh_allocated.var_decl(ctx)) fresh_allocated_var = fresh_allocated.local_var(ctx, pos) # Assume type assumptions for fresh_allocated allocated_ass = self.type_translator.type_assumptions(fresh_allocated_var, fresh_allocated.type, ctx) allocated_assumptions = [self.viper_ast.Inhale(c) for c in allocated_ass] allocated_info_msg = "Assume type assumptions for fresh allocated" self.seqn_with_info(allocated_assumptions, allocated_info_msg, res) with ctx.allocated_scope(fresh_allocated): # We assume the invariant with the current state as the old state because the current allocation # should be known from the current state, not the old state. For example, the invariant # allocated() == old(allocated()) # should be illegal. with ctx.state_scope(ctx.current_state, ctx.current_state): for inv in ctx.unchecked_invariants(): res.append(self.viper_ast.Inhale(inv)) # As an optimization we only assume invariants that mention allocated(), all other invariants # are already known since we only changed the allocation map to a fresh one contracts: List[VyperProgram] = [ctx.program.interfaces[i.name] for i in ctx.program.implements] contracts.append(ctx.program) for contract in contracts: with ctx.program_scope(contract): for inv in ctx.current_program.analysis.allocated_invariants: ppos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) expr = spec_translator.translate_invariant(inv, res, ctx, True) res.append(self.viper_ast.Inhale(expr, ppos)) modelt = self.model_translator.save_variables(res, ctx, pos) # We create the following check for each resource r: # forall a: address, arg0, arg1, ... :: <type_assumptions> ==> # allocated[r(arg0, arg1, ...)](a) == fresh_allocated[r(arg0, arg1, ...)](a) address = self.viper_ast.LocalVarDecl('$a', self.viper_ast.Int, pos) address_var = address.localVar() address_assumptions = self.type_translator.type_assumptions(address_var, types.VYPER_ADDRESS, ctx) interface_names = [t.name for t in ctx.program.implements] interfaces = [ctx.program.interfaces[name] for name in interface_names] own_resources = [(name, resource) for name, resource in ctx.program.own_resources.items() # Do not make a leak check for the underlying wei resource if name != names.UNDERLYING_WEI] for i in interfaces: interface_resources = [(name, resource) for name, resource in i.own_resources.items() # Do not make a leak check for the underlying wei resource if name != names.UNDERLYING_WEI] own_resources.extend(interface_resources) for name, resource in own_resources: type_assumptions = address_assumptions.copy() args = [] for idx, arg_type in enumerate(resource.type.member_types.values()): viper_type = self.type_translator.translate(arg_type, ctx) arg = self.viper_ast.LocalVarDecl(f'$arg{idx}', viper_type, pos) args.append(arg) arg_var = arg.localVar() type_assumptions.extend(self.type_translator.type_assumptions(arg_var, arg_type, ctx)) cond = reduce(lambda l, r: self.viper_ast.And(l, r, pos), type_assumptions) t_resource = self.resource_translator.resource(name, [arg.localVar() for arg in args], ctx) allocated_get = self.get_allocated(allocated.local_var(ctx, pos), t_resource, address_var, ctx, pos) fresh_allocated_get = self.get_allocated(fresh_allocated_var, t_resource, address_var, ctx, pos) allocated_eq = self.viper_ast.EqCmp(allocated_get, fresh_allocated_get, pos) trigger = self.viper_ast.Trigger([allocated_get, fresh_allocated_get], pos) assertion = self.viper_ast.Forall([address, *args], [trigger], self.viper_ast.Implies(cond, allocated_eq, pos), pos) if ctx.function.name == names.INIT: # Leak check only has to hold if __init__ succeeds succ = ctx.success_var.local_var(ctx, pos) assertion = self.viper_ast.Implies(succ, assertion, pos) apos = self.to_position(node, ctx, rule, modelt=modelt, values={'resource': resource}) res.append(self.viper_ast.Assert(assertion, apos)) def _performs_leak_check(self, node: ast.Node, res: List[Stmt], ctx: Context, pos=None): if not ctx.program.config.has_option(names.CONFIG_NO_PERFORMS): struct_t = helpers.struct_type(self.viper_ast) int_t = self.viper_ast.Int bool_t = self.viper_ast.Bool predicate_types = { names.CREATE: [struct_t, int_t, int_t, int_t], names.DESTROY: [struct_t, int_t, int_t], names.REALLOCATE: [struct_t, int_t, int_t, int_t], # ALLOW_TO_DECOMPOSE is modelled as an offer and therefore needs no leak check names.OFFER: [struct_t, struct_t, int_t, int_t, int_t, int_t, int_t], names.REVOKE: [struct_t, struct_t, int_t, int_t, int_t, int_t], names.EXCHANGE: [struct_t, struct_t, int_t, int_t, int_t, int_t, int_t], names.TRUST: [int_t, int_t, bool_t], names.ALLOCATE_UNTRACKED: [struct_t, int_t], names.RESOURCE_PAYABLE: [struct_t, int_t, int_t], names.RESOURCE_PAYOUT: [struct_t, int_t, int_t], } modelt = self.model_translator.save_variables(res, ctx, pos) for function, arg_types in predicate_types.items(): # We could use forperm instead, but Carbon doesn't support multiple variables # in forperm (TODO: issue #243) quant_decls = [self.viper_ast.LocalVarDecl(f'$a{idx}', t, pos) for idx, t in enumerate(arg_types)] quant_vars = [decl.localVar() for decl in quant_decls] pred = helpers.performs_predicate(self.viper_ast, function, quant_vars, pos) succ = ctx.success_var.local_var(ctx, pos) perm = self.viper_ast.CurrentPerm(pred, pos) cond = self.viper_ast.Implies(succ, self.viper_ast.EqCmp(perm, self.viper_ast.NoPerm(pos), pos), pos) trigger = self.viper_ast.Trigger([pred], pos) quant = self.viper_ast.Forall(quant_decls, [trigger], cond, pos) apos = self.to_position(node, ctx, rules.PERFORMS_LEAK_CHECK_FAIL, modelt=modelt) res.append(self.viper_ast.Assert(quant, apos)) def function_leak_check(self, res: List[Stmt], ctx: Context, pos=None): self._allocation_leak_check(ctx.function.node or ctx.program.node, rules.ALLOCATION_LEAK_CHECK_FAIL, res, ctx, pos) self._performs_leak_check(ctx.function.node or ctx.program.node, res, ctx, pos) def send_leak_check(self, node: ast.Node, res: List[Stmt], ctx: Context, pos=None): self._allocation_leak_check(node, rules.CALL_LEAK_CHECK_FAIL, res, ctx, pos) def offer(self, node: ast.Node, from_resource: Expr, to_resource: Expr, from_value: Expr, to_value: Expr, from_owner: Expr, to_owner: Expr, times: Expr, actor: Expr, res: List[Stmt], ctx: Context, pos=None): stmts = [] self._exhale_performs_if_non_zero_amount(node, names.OFFER, [from_resource, to_resource, from_value, to_value, from_owner, to_owner, times], [from_value, times], rules.OFFER_FAIL, stmts, ctx, pos) self._check_trusted_if_non_zero_amount(node, actor, from_owner, [from_value, times], rules.OFFER_FAIL, stmts, ctx, pos) if ctx.quantified_vars: # We are translating a # foreach({x1: t1, x2: t2, ...}, offer(e1(x1, x2, ...), e2(x1, x2, ...), to=e3(x1, x2, ...), times=t)) # To do that, we first inhale the offer predicate # inhale forall x1: t1, x2: t2, ... :: acc(offer(e1(...), e2(...), ..., e3(...)), t * write) # For all offers we inhaled some permission to we then set the 'times' entries in a new map to the # sum of the old map entries and the current permissions to the respective offer. # assume forall $i, $j, $a, $b: Int :: # fresh_offered[{$i, $j, $a, $b}] * write == old_offered[...] * write + perm(offer($i, $j, $a, $b)) def op(fresh: Expr, old: Expr, perm: Expr) -> Expr: write = self.viper_ast.FullPerm(pos) fresh_mul = self.viper_ast.IntPermMul(fresh, write, pos) old_mul = self.viper_ast.IntPermMul(old, write, pos) perm_add = self.viper_ast.PermAdd(old_mul, perm, pos) return self.viper_ast.EqCmp(fresh_mul, perm_add, pos) self._foreach_change_offered(from_resource, to_resource, from_value, to_value, from_owner, to_owner, times, op, stmts, ctx, pos) else: self._change_offered(from_resource, to_resource, from_value, to_value, from_owner, to_owner, times, True, stmts, ctx, pos) self.seqn_with_info(stmts, "Offer", res) def allow_to_decompose(self, node: ast.Node, resource: Expr, underlying_resource: Expr, owner: Expr, amount: Expr, actor: Expr, res: List[Stmt], ctx: Context, pos=None): stmts = [] const_one = self.viper_ast.IntLit(1, pos) self._exhale_performs_if_non_zero_amount(node, names.OFFER, [resource, underlying_resource, const_one, const_one, owner, owner, amount], amount, rules.OFFER_FAIL, stmts, ctx, pos) self._check_trusted_if_non_zero_amount(node, actor, owner, amount, rules.OFFER_FAIL, stmts, ctx, pos) self._set_offered(resource, underlying_resource, const_one, const_one, owner, owner, amount, stmts, ctx, pos) self.seqn_with_info(stmts, "Allow to decompose", res) def revoke(self, node: ast.Node, from_resource: Expr, to_resource: Expr, from_value: Expr, to_value: Expr, from_owner: Expr, to_owner: Expr, actor: Expr, res: List[Stmt], ctx: Context, pos=None): stmts = [] self._exhale_performs_if_non_zero_amount(node, names.REVOKE, [from_resource, to_resource, from_value, to_value, from_owner, to_owner], from_value, rules.REVOKE_FAIL, stmts, ctx, pos) self._check_trusted_if_non_zero_amount(node, actor, from_owner, from_value, rules.REVOKE_FAIL, stmts, ctx, pos) if ctx.quantified_vars: # We are translating a # foreach({x1: t1, x2: t2, ...}, revoke(e1(x1, x2, ...), e2(x1, x2, ...), to=e3(x1, x2, ...))) # To do that, we first inhale the offer predicate # inhale forall x1: t1, x2: t2, ... :: offer(e1(...), e2(...), ..., e3(...)) # For all offers we inhaled some permission to we then set the 'times' entries to zero in a # new map, all others stay the same. assume forall $i, $j, $a, $b: Int :: # fresh_offered[{$i, $j, $a, $b}] == perm(offer($i, $j, $a, $b)) > none ? 0 : old_offered[...] one = self.viper_ast.IntLit(1, pos) def op(fresh: Expr, old: Expr, perm: Expr) -> Expr: gez = self.viper_ast.GtCmp(perm, self.viper_ast.NoPerm(pos), pos) cond_expr = self.viper_ast.CondExp(gez, self.viper_ast.IntLit(0, pos), old, pos) return self.viper_ast.EqCmp(fresh, cond_expr, pos) self._foreach_change_offered(from_resource, to_resource, from_value, to_value, from_owner, to_owner, one, op, stmts, ctx, pos) else: zero = self.viper_ast.IntLit(0, pos) self._set_offered(from_resource, to_resource, from_value, to_value, from_owner, to_owner, zero, stmts, ctx, pos) self.seqn_with_info(stmts, "Revoke", res) def exchange(self, node: ast.Node, resource1: Expr, resource2: Expr, value1: Expr, value2: Expr, owner1: Expr, owner2: Expr, times: Expr, res: List[Stmt], ctx: Context, pos=None): stmts = [] self._exhale_performs_if_non_zero_amount(node, names.EXCHANGE, [resource1, resource2, value1, value2, owner1, owner2, times], [self.viper_ast.Add(value1, value2), times], rules.EXCHANGE_FAIL, stmts, ctx, pos) def check_owner_1(then): # If value1 == 0, owner1 will definitely agree, else we check that they offered the exchange, and # decreases the offer map by the amount of exchanges we do self._check_from_agrees(node, resource1, resource2, value1, value2, owner1, owner2, times, then, ctx, pos) self._change_offered(resource1, resource2, value1, value2, owner1, owner2, times, False, then, ctx, pos) self._if_non_zero_values(check_owner_1, [value1, times], stmts, ctx, pos) def check_owner_2(then): # We do the same for owner2 self._check_from_agrees(node, resource2, resource1, value2, value1, owner2, owner1, times, then, ctx, pos) self._change_offered(resource2, resource1, value2, value1, owner2, owner1, times, False, then, ctx, pos) self._if_non_zero_values(check_owner_2, [value2, times], stmts, ctx, pos) amount1 = self.viper_ast.Mul(times, value1) self._check_allocation(node, resource1, owner1, amount1, rules.EXCHANGE_FAIL_INSUFFICIENT_FUNDS, stmts, ctx, pos) amount2 = self.viper_ast.Mul(times, value2) self._check_allocation(node, resource2, owner2, amount2, rules.EXCHANGE_FAIL_INSUFFICIENT_FUNDS, stmts, ctx, pos) # owner1 gives up amount1 of resource1 self._change_allocation(resource1, owner1, amount1, False, stmts, ctx, pos) # owner1 gets amount2 of resource2 self._change_allocation(resource2, owner1, amount2, True, stmts, ctx, pos) # owner2 gives up amount2 of resource2 self._change_allocation(resource2, owner2, amount2, False, stmts, ctx, pos) # owner2 gets amount1 of resource1 self._change_allocation(resource1, owner2, amount1, True, stmts, ctx, pos) self.seqn_with_info(stmts, "Exchange", res) def trust(self, node: ast.Node, address: Expr, from_address: Expr, new_value: Expr, res: List[Stmt], ctx: Context, pos=None): stmts = [] self._exhale_performs(node, names.TRUST, [address, from_address, new_value], rules.TRUST_FAIL, stmts, ctx, pos) if ctx.quantified_vars: self._foreach_change_trusted(address, from_address, new_value, stmts, ctx, pos) else: self._change_trusted(address, from_address, new_value, stmts, ctx, pos) self.seqn_with_info(stmts, "Trust", res) def allocate_untracked(self, node: ast.Node, resource: Expr, address: Expr, balance: Expr, res: List[Stmt], ctx: Context, pos=None): stmts = [] self._exhale_performs(node, names.ALLOCATE_UNTRACKED, [resource, address], rules.ALLOCATE_UNTRACKED_FAIL, stmts, ctx, pos) difference = self.allocation_difference_to_balance(balance, resource, ctx, pos) self.allocate(resource, address, difference, stmts, ctx, pos) self.seqn_with_info(stmts, "Allocate untracked wei", res) def allocation_difference_to_balance(self, balance: Expr, resource: Expr, ctx: Context, pos=None): allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx) allocated_map = self.get_allocated_map(allocated, resource, ctx, pos) key_type = self.type_translator.translate(helpers.allocated_type().value_type.key_type, ctx) allocated_sum = helpers.map_sum(self.viper_ast, allocated_map, key_type, pos) difference = self.viper_ast.Sub(balance, allocated_sum, pos) return difference def performs(self, _: ast.Node, resource_function_name: str, args: List[Expr], amount_args: Union[List[Expr], Expr], res: List[Stmt], ctx: Context, pos=None): pred = self._performs_acc_predicate(resource_function_name, args, ctx, pos) # TODO: rule self._if_non_zero_values(lambda l: l.append(self.viper_ast.Inhale(pred, pos)), amount_args, res, ctx, pos) def interface_performed(self, node: ast.Node, resource_function_name: str, args: List[Expr], amount_args: Union[List[Expr], Expr], res: List[Stmt], ctx: Context, pos=None): pred_access_pred = self._performs_acc_predicate(resource_function_name, args, ctx, pos) # Only exhale if we have enough "perm" (Redeclaration of performs is optional) pred = helpers.performs_predicate(self.viper_ast, resource_function_name, args, pos) perm = self.viper_ast.CurrentPerm(pred, pos) write = self.viper_ast.FullPerm(pos) enough_perm = self.viper_ast.GeCmp(perm, write, pos) # Only exhale if the address is not self and the resource is potentially an "own resource" address = None if isinstance(node, ast.FunctionCall) and node.name in names.GHOST_STATEMENTS: interface_files = [ctx.program.interfaces[impl.name].file for impl in ctx.program.implements] address, resource = self.location_address_of_performs(node, res, ctx, pos, return_resource=True) if resource is not None and (resource.file is None # It is okay to declare performs for wei # It is okay to declare performs for own private resources or resource.file == ctx.program.file # It is okay to redeclare performs with resources not in interfaces # this contract implements or resource.file not in interface_files): address = None if address is not None: self_address = helpers.self_address(self.viper_ast) address_cond = self.viper_ast.NeCmp(address, self_address, pos) else: address_cond = self.viper_ast.TrueLit(pos) cond = self.viper_ast.And(enough_perm, address_cond) cond_pred = self.viper_ast.CondExp(cond, pred_access_pred, self.viper_ast.TrueLit(), pos) # TODO: rule self._if_non_zero_values(lambda l: l.append(self.viper_ast.Exhale(cond_pred, pos)), amount_args, res, ctx, pos) def location_address_of_performs(self, node: ast.FunctionCall, res: List[Stmt], ctx: Context, pos=None, return_resource=False): if node.name == names.TRUST: res = ctx.self_address or helpers.self_address(self.viper_ast, pos), None elif node.name == names.FOREACH: body = node.args[-1] assert isinstance(body, ast.FunctionCall) res = self.location_address_of_performs(body, res, ctx, pos, True) else: # All other allocation functions have a resource with the location if isinstance(node.resource, ast.Exchange): (resource, t_resource), _ = self.resource_translator.translate_exchange( node.resource, res, ctx, True) elif node.resource is not None: resource, t_resource = self.resource_translator.translate(node.resource, res, ctx, True) elif ctx.program.config.has_option(names.CONFIG_NO_DERIVED_WEI): resource, t_resource = None, self.resource_translator.underlying_wei_resource(ctx) else: resource, t_resource = self.resource_translator.translate(None, res, ctx, True) resource_args = self.viper_ast.to_list(t_resource.getArgs()) if resource_args: res = resource_args.pop(), resource else: res = None, resource if return_resource: return res return res[0]
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/allocation.py
allocation.py
from typing import List from twovyper.ast.types import VYPER_BOOL from twovyper.translation.abstract import CommonTranslator from twovyper.translation.arithmetic import ArithmeticTranslator from twovyper.translation.context import Context from twovyper.translation.expression import ExpressionTranslator from twovyper.translation.specification import SpecificationTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedPureIndexedVar from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt class PureTranslatorMixin(CommonTranslator): def seqn_with_info(self, expressions: [Expr], comment: str, res: List[Expr]): res.extend(expressions) def fail_if(self, cond: Expr, stmts: List[Stmt], res: List[Expr], ctx: Context, pos=None, info=None): assert isinstance(ctx.success_var, TranslatedPureIndexedVar) cond_var = TranslatedPureIndexedVar('cond', 'cond', VYPER_BOOL, self.viper_ast, pos, info) cond_local_var = cond_var.local_var(ctx) assign = self.viper_ast.EqCmp(cond_local_var, cond, pos, info) expr = self.viper_ast.Implies(ctx.pure_conds, assign, pos, info) if ctx.pure_conds else assign res.append(expr) # Fail if the condition is true fail_cond = self.viper_ast.And(ctx.pure_conds, cond_local_var, pos, info) if ctx.pure_conds else cond_local_var old_success_idx = ctx.success_var.evaluate_idx(ctx) ctx.success_var.new_idx() assign = self.viper_ast.EqCmp(ctx.success_var.local_var(ctx), self.viper_ast.FalseLit(), pos, info) expr = self.viper_ast.Implies(ctx.pure_conds, assign, pos, info) if ctx.pure_conds else assign res.append(expr) ctx.pure_success.append((fail_cond, ctx.success_var.evaluate_idx(ctx))) ctx.success_var.idx = old_success_idx # If we did not fail, we know that the condition is not true negated_local_var = self.viper_ast.Not(cond_local_var, pos, info) ctx.pure_conds = self.viper_ast.And(ctx.pure_conds, negated_local_var, pos, info)\ if ctx.pure_conds else negated_local_var class PureArithmeticTranslator(PureTranslatorMixin, ArithmeticTranslator): pass class PureExpressionTranslator(PureTranslatorMixin, ExpressionTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.arithmetic_translator = PureArithmeticTranslator(viper_ast, self.no_reverts) self.type_translator = PureTypeTranslator(viper_ast) @property def spec_translator(self): return PureSpecificationTranslator(self.viper_ast) @property def function_translator(self): from twovyper.translation.pure_function import PureFunctionTranslator return PureFunctionTranslator(self.viper_ast) class PureSpecificationTranslator(PureTranslatorMixin, SpecificationTranslator): pass class PureTypeTranslator(PureTranslatorMixin, TypeTranslator): pass
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/pure_translators.py
pure_translators.py
from functools import reduce from itertools import chain from typing import List, Optional, Tuple, Callable from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.arithmetic import Decimal from twovyper.ast.nodes import VyperFunction, VyperInterface, VyperVar, VyperEvent, VyperProgram from twovyper.ast.types import MapType, ArrayType, StructType, AddressType, ContractType, InterfaceType from twovyper.exceptions import UnsupportedException from twovyper.translation import mangled from twovyper.translation import helpers from twovyper.translation.context import Context from twovyper.translation.abstract import NodeTranslator from twovyper.translation.allocation import AllocationTranslator from twovyper.translation.arithmetic import ArithmeticTranslator from twovyper.translation.balance import BalanceTranslator from twovyper.translation.model import ModelTranslator from twovyper.translation.resource import ResourceTranslator from twovyper.translation.state import StateTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedVar from twovyper.translation.wrapped_viper_ast import WrappedViperAST from twovyper.utils import switch, first_index from twovyper.verification import rules from twovyper.verification.error import Via from twovyper.verification.model import ModelTransformation from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt # noinspection PyUnusedLocal class ExpressionTranslator(NodeTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.allocation_translator = AllocationTranslator(viper_ast) self.arithmetic_translator = ArithmeticTranslator(viper_ast, self.no_reverts) self.balance_translator = BalanceTranslator(viper_ast) self.model_translator = ModelTranslator(viper_ast) self.resource_translator = ResourceTranslator(viper_ast) self.state_translator = StateTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) self._bool_ops = { ast.BoolOperator.AND: self.viper_ast.And, ast.BoolOperator.OR: self.viper_ast.Or, ast.BoolOperator.IMPLIES: self.viper_ast.Implies } self._comparison_ops = { ast.ComparisonOperator.LT: self.viper_ast.LtCmp, ast.ComparisonOperator.LTE: self.viper_ast.LeCmp, ast.ComparisonOperator.GTE: self.viper_ast.GeCmp, ast.ComparisonOperator.GT: self.viper_ast.GtCmp } def translate_top_level_expression(self, node: ast.Expr, res: List[Stmt], ctx: Context): """ A top level expression is an expression directly used in a statement. Generally, we do not need to $wrap inside of a top level expression. Therefore, we only keep the information if some expressions got unwrapped inside this expression and if this expression could get wrapped. If both is true, only then we wrap this expression again. Doing this, prevents the $wrap($unwrap($wrap($unwrap(...))) chain during translation. If we are inside an interpreted scope, we do not wrap the result again. """ if isinstance(self.viper_ast, WrappedViperAST) and not ctx.inside_interpreted: self.viper_ast.unwrapped_some_expressions = False result = self.translate(node, res, ctx) if self.viper_ast.unwrapped_some_expressions: if types.is_numeric(node.type) and self.arithmetic_translator.is_unwrapped(result): result = helpers.w_wrap(self.viper_ast, result) return result else: return self.translate(node, res, ctx) @property def no_reverts(self) -> bool: return False @property def spec_translator(self): from twovyper.translation.specification import SpecificationTranslator return SpecificationTranslator(self.viper_ast) @property def function_translator(self): from twovyper.translation.function import FunctionTranslator return FunctionTranslator(self.viper_ast) def translate_Num(self, node: ast.Num, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if isinstance(node.n, int): if node.type == types.VYPER_BYTES32: bts = node.n.to_bytes(32, byteorder='big') elems = [self.viper_ast.IntLit(b, pos) for b in bts] return self.viper_ast.ExplicitSeq(elems, pos) else: return self.viper_ast.IntLit(node.n, pos) elif isinstance(node.n, Decimal): return self.viper_ast.IntLit(node.n.scaled_value, pos) else: assert False def translate_Bool(self, node: ast.Bool, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) return self.viper_ast.TrueLit(pos) if node.value else self.viper_ast.FalseLit(pos) def translate_Name(self, node: ast.Name, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if node.id == names.SELF and (node.type == types.VYPER_ADDRESS or isinstance(node.type, (ContractType, InterfaceType))): return ctx.self_address or helpers.self_address(self.viper_ast, pos) elif ctx.inside_inline_analysis and node.id not in ctx.all_vars: # Generate new local variable variable_name = node.id mangled_name = ctx.new_local_var_name(variable_name) var = TranslatedVar(variable_name, mangled_name, node.type, self.viper_ast, pos) ctx.locals[variable_name] = var ctx.new_local_vars.append(var.var_decl(ctx)) return ctx.all_vars[node.id].local_var(ctx, pos) def translate_ArithmeticOp(self, node: ast.ArithmeticOp, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if node.op in self.arithmetic_translator.non_linear_ops: # Since we need the information if an expression was wrapped, we can treat this expressions as top-level. left = self.translate_top_level_expression(node.left, res, ctx) right = self.translate_top_level_expression(node.right, res, ctx) else: left = self.translate(node.left, res, ctx) right = self.translate(node.right, res, ctx) return self.arithmetic_translator.arithmetic_op(left, node.op, right, node.type, res, ctx, pos) def translate_BoolOp(self, node: ast.BoolOp, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) left = self.translate(node.left, res, ctx) op = self._bool_ops[node.op] right = self.translate(node.right, res, ctx) return op(left, right, pos) def translate_Not(self, node: ast.Not, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) operand = self.translate(node.operand, res, ctx) return self.viper_ast.Not(operand, pos) def translate_UnaryArithmeticOp(self, node: ast.UnaryArithmeticOp, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) operand = self.translate(node.operand, res, ctx) return self.arithmetic_translator.unary_arithmetic_op(node.op, operand, node.type, res, ctx, pos) def translate_IfExpr(self, node: ast.IfExpr, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) test = self.translate(node.test, res, ctx) body = self.translate(node.body, res, ctx) orelse = self.translate(node.orelse, res, ctx) return self.viper_ast.CondExp(test, body, orelse, pos) def translate_Comparison(self, node: ast.Comparison, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) lhs = self.translate(node.left, res, ctx) op = self._comparison_ops[node.op] rhs = self.translate(node.right, res, ctx) return op(lhs, rhs, pos) def translate_Containment(self, node: ast.Containment, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) value = self.translate(node.value, res, ctx) expr_list = self.translate(node.list, res, ctx) if node.op == ast.ContainmentOperator.IN: return helpers.array_contains(self.viper_ast, value, expr_list, pos) elif node.op == ast.ContainmentOperator.NOT_IN: return helpers.array_not_contains(self.viper_ast, value, expr_list, pos) else: assert False def translate_Equality(self, node: ast.Equality, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) lhs = self.translate(node.left, res, ctx) rhs = self.translate(node.right, res, ctx) if node.op == ast.EqualityOperator.EQ: return self.type_translator.eq(lhs, rhs, node.left.type, ctx, pos) elif node.op == ast.EqualityOperator.NEQ: return self.type_translator.neq(lhs, rhs, node.left.type, ctx, pos) else: assert False def translate_Attribute(self, node: ast.Attribute, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) # We don't support precise gas calculations, so we just return an unknown # non-negative value if node.attr == names.MSG_GAS and node.value.type == types.MSG_TYPE: gas_name = ctx.new_local_var_name('gas') gas_type = self.type_translator.translate(types.VYPER_UINT256, ctx) gas = self.viper_ast.LocalVarDecl(gas_name, gas_type, pos) ctx.new_local_vars.append(gas) zero = self.viper_ast.IntLit(0, pos) geq = self.viper_ast.GeCmp(gas.localVar(), zero, pos) res.append(self.viper_ast.Inhale(geq, pos)) return gas.localVar() expr = self.translate(node.value, res, ctx) if isinstance(node.value.type, StructType): # The value is a struct struct_type = node.value.type struct = expr else: # The value is an address struct_type = AddressType() contracts = ctx.current_state[mangled.CONTRACTS].local_var(ctx) key_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) value_type = helpers.struct_type(self.viper_ast) struct = helpers.map_get(self.viper_ast, contracts, expr, key_type, value_type) viper_type = self.type_translator.translate(node.type, ctx) get = helpers.struct_get(self.viper_ast, struct, node.attr, viper_type, struct_type, pos) return get def translate_Subscript(self, node: ast.Subscript, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) value = self.translate(node.value, res, ctx) index = self.translate(node.index, res, ctx) node_type = node.value.type if isinstance(node_type, MapType): key_type = self.type_translator.translate(node_type.key_type, ctx) value_type = self.type_translator.translate(node_type.value_type, ctx) call = helpers.map_get(self.viper_ast, value, index, key_type, value_type, pos) elif isinstance(node_type, ArrayType): if not self.no_reverts: self.type_translator.array_bounds_check(value, index, res, ctx) element_type = self.type_translator.translate(node_type.element_type, ctx) call = helpers.array_get(self.viper_ast, value, index, element_type, pos) else: assert False return call def translate_List(self, node: ast.List, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if not node.elements: viper_type = self.type_translator.translate(node.type.element_type, ctx) return self.viper_ast.EmptySeq(viper_type, pos) else: elems = [self.translate(e, res, ctx) for e in node.elements] return self.viper_ast.ExplicitSeq(elems, pos) def translate_Str(self, node: ast.Str, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if not node.s: viper_type = self.type_translator.translate(node.type.element_type, ctx) return self.viper_ast.EmptySeq(viper_type, pos) else: elems = [self.viper_ast.IntLit(e, pos) for e in bytes(node.s, 'utf-8')] return self.viper_ast.ExplicitSeq(elems, pos) def translate_Bytes(self, node: ast.Bytes, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) if not node.s: viper_type = self.type_translator.translate(node.type.element_type, ctx) return self.viper_ast.EmptySeq(viper_type, pos) else: elems = [self.viper_ast.IntLit(e, pos) for e in node.s] return self.viper_ast.ExplicitSeq(elems, pos) def translate_Tuple(self, node: ast.Tuple, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) new_ret = helpers.havoc_var(self.viper_ast, helpers.struct_type(self.viper_ast), ctx) for idx, element in enumerate(node.elements): viper_type = self.type_translator.translate(element.type, ctx) value = self.translate(element, res, ctx) new_ret = helpers.struct_set_idx(self.viper_ast, new_ret, value, idx, viper_type, pos) return new_ret def translate_FunctionCall(self, node: ast.FunctionCall, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) name = node.name is_min = (name == names.MIN) is_max = (name == names.MAX) if is_min or is_max: lhs = self.translate(node.args[0], res, ctx) rhs = self.translate(node.args[1], res, ctx) op = self.viper_ast.GtCmp if is_max else self.viper_ast.LtCmp comp = op(lhs, rhs, pos) return self.viper_ast.CondExp(comp, lhs, rhs, pos) elif name == names.ADDMOD or name == names.MULMOD: op1 = self.translate(node.args[0], res, ctx) op2 = self.translate(node.args[1], res, ctx) mod = self.translate(node.args[2], res, ctx) cond = self.viper_ast.EqCmp(mod, self.viper_ast.IntLit(0, pos), pos) self.fail_if(cond, [], res, ctx, pos) operation = self.viper_ast.Add if name == names.ADDMOD else self.viper_ast.Mul op_res = operation(op1, op2, pos) return helpers.mod(self.viper_ast, op_res, mod, pos) elif name == names.SQRT: arg = self.translate(node.args[0], res, ctx) zero = self.viper_ast.IntLit(0, pos) lt = self.viper_ast.LtCmp(arg, zero, pos) self.fail_if(lt, [], res, ctx, pos) sqrt = helpers.sqrt(self.viper_ast, arg, pos) return sqrt elif name == names.FLOOR or name == names.CEIL: # Let s be the scaling factor, then # floor(d) == d < 0 ? (d - (s - 1)) / s : d / s # ceil(d) == d < 0 ? d / s : (d + s - 1) / s arg = self.translate(node.args[0], res, ctx) scaling_factor = node.args[0].type.scaling_factor if name == names.FLOOR: expr = helpers.floor(self.viper_ast, arg, scaling_factor, pos) elif name == names.CEIL: expr = helpers.ceil(self.viper_ast, arg, scaling_factor, pos) else: assert False return expr elif name == names.SHIFT: arg = self.translate(node.args[0], res, ctx) shift = self.translate(node.args[1], res, ctx) return helpers.shift(self.viper_ast, arg, shift, pos) elif name in [names.BITWISE_AND, names.BITWISE_OR, names.BITWISE_XOR]: a = self.translate(node.args[0], res, ctx) b = self.translate(node.args[1], res, ctx) funcs = { names.BITWISE_AND: helpers.bitwise_and, names.BITWISE_OR: helpers.bitwise_or, names.BITWISE_XOR: helpers.bitwise_xor } return funcs[name](self.viper_ast, a, b, pos) elif name == names.BITWISE_NOT: arg = self.translate(node.args[0], res, ctx) return helpers.bitwise_not(self.viper_ast, arg, pos) elif name == names.AS_WEI_VALUE: arg = self.translate(node.args[0], res, ctx) second_arg = node.args[1] assert isinstance(second_arg, ast.Str) unit = second_arg.s unit_pos = self.to_position(second_arg, ctx) multiplier = next(v for k, v in names.ETHER_UNITS.items() if unit in k) multiplier_lit = self.viper_ast.IntLit(multiplier, unit_pos) num = self.viper_ast.Mul(arg, multiplier_lit, pos) if types.is_bounded(node.type): self.arithmetic_translator.check_under_overflow(num, node.type, res, ctx, pos) return num elif name == names.AS_UNITLESS_NUMBER: return self.translate(node.args[0], res, ctx) elif name == names.LEN: arr = self.translate(node.args[0], res, ctx) return helpers.array_length(self.viper_ast, arr, pos) elif name == names.RANGE: if len(node.args) == 1: start = self.viper_ast.IntLit(0, pos) end = self.translate(node.args[0], res, ctx) else: start = self.translate(node.args[0], res, ctx) end = self.translate(node.args[1], res, ctx) return helpers.range(self.viper_ast, start, end, pos) elif name == names.CONCAT: concats = [self.translate(arg, res, ctx) for arg in node.args] def concat(arguments): argument, *tail = arguments if not tail: return argument else: return self.viper_ast.SeqAppend(argument, concat(tail), pos) return concat(concats) elif name == names.EXTRACT32: b = self.translate(node.args[0], res, ctx) b_len = helpers.array_length(self.viper_ast, b, pos) zero = self.viper_ast.IntLit(0, pos) start = self.translate(node.args[1], res, ctx) lit_32 = self.viper_ast.IntLit(32, pos) end = self.viper_ast.Add(lit_32, start, pos) # General revert conditions start_is_negative = self.viper_ast.LtCmp(start, zero, pos) seq_too_small = self.viper_ast.LtCmp(b_len, end, pos) cond = self.viper_ast.Or(start_is_negative, seq_too_small) self.fail_if(cond, [], res, ctx, pos) # Convert byte list to desired type b_sliced = self.viper_ast.SeqTake(b, end, pos) b_sliced = self.viper_ast.SeqDrop(b_sliced, start, pos) b_bytes32 = helpers.pad32(self.viper_ast, b_sliced, pos) with switch(node.type) as case: if case(types.VYPER_BYTES32): i = b_bytes32 elif case(types.VYPER_INT128): i = helpers.convert_bytes32_to_signed_int(self.viper_ast, b_bytes32, pos) self.arithmetic_translator.check_under_overflow(i, types.VYPER_INT128, res, ctx, pos) elif case(types.VYPER_ADDRESS): i = helpers.convert_bytes32_to_unsigned_int(self.viper_ast, b_bytes32, pos) self.arithmetic_translator.check_under_overflow(i, types.VYPER_ADDRESS, res, ctx, pos) else: assert False return i elif name == names.EMPTY: return self.type_translator.default_value(node, node.type, res, ctx) elif name == names.CONVERT: from_type = node.args[0].type to_type = node.type arg = self.translate(node.args[0], res, ctx) if isinstance(from_type, ArrayType) and from_type.element_type == types.VYPER_BYTE: if from_type.size > 32: raise UnsupportedException(node, 'Unsupported type converison.') # If we convert a byte array to some type, we simply pad it to a bytes32 and # proceed as if we had been given a bytes32 arg = helpers.pad32(self.viper_ast, arg, pos) from_type = types.VYPER_BYTES32 zero = self.viper_ast.IntLit(0, pos) one = self.viper_ast.IntLit(1, pos) zero_list = [0] * 32 one_list = [0] * 31 + [1] zero_array = self.viper_ast.ExplicitSeq([self.viper_ast.IntLit(i, pos) for i in zero_list], pos) one_array = self.viper_ast.ExplicitSeq([self.viper_ast.IntLit(i, pos) for i in one_list], pos) with switch(from_type, to_type) as case: from twovyper.utils import _ # If both types are equal (e.g. if we convert a literal) we simply # return the argument if case(_, _, where=from_type == to_type): return arg # --------------------- bool -> ? --------------------- # If we convert from a bool we translate True as 1 and False as 0 elif case(types.VYPER_BOOL, types.VYPER_DECIMAL): d_one = 1 * types.VYPER_DECIMAL.scaling_factor d_one_lit = self.viper_ast.IntLit(d_one, pos) return helpers.w_wrap(self.viper_ast, self.viper_ast.CondExp(arg, d_one_lit, zero, pos)) elif case(types.VYPER_BOOL, types.VYPER_BYTES32): return self.viper_ast.CondExp(arg, one_array, zero_array, pos) elif case(types.VYPER_BOOL, _, where=types.is_numeric(to_type)): return helpers.w_wrap(self.viper_ast, self.viper_ast.CondExp(arg, one, zero, pos)) elif case(types.VYPER_BOOL, _): return self.viper_ast.CondExp(arg, one, zero, pos) # --------------------- ? -> bool --------------------- # If we convert to a bool we check for zero elif case(types.VYPER_BYTES32, types.VYPER_BOOL): return self.viper_ast.NeCmp(arg, zero_array, pos) elif case(_, types.VYPER_BOOL): return self.viper_ast.NeCmp(arg, zero, pos) # --------------------- decimal -> ? --------------------- elif case(types.VYPER_DECIMAL, types.VYPER_INT128): s = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) return helpers.div(self.viper_ast, arg, s, pos) elif case(types.VYPER_DECIMAL, types.VYPER_UINT256): s = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) div = helpers.div(self.viper_ast, arg, s, pos) self.arithmetic_translator.check_underflow(div, to_type, res, ctx, pos) return div elif case(types.VYPER_DECIMAL, types.VYPER_BYTES32): return helpers.convert_signed_int_to_bytes32(self.viper_ast, arg, pos) # --------------------- int128 -> ? --------------------- elif case(types.VYPER_INT128, types.VYPER_DECIMAL): s = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) return self.viper_ast.Mul(arg, s, pos) # When converting a signed number to an unsigned number we revert if # the argument is negative elif case(types.VYPER_INT128, types.VYPER_UINT256): self.arithmetic_translator.check_underflow(arg, to_type, res, ctx, pos) return arg elif case(types.VYPER_INT128, types.VYPER_BYTES32): return helpers.convert_signed_int_to_bytes32(self.viper_ast, arg, pos) # --------------------- uint256 -> ? --------------------- elif case(types.VYPER_UINT256, types.VYPER_DECIMAL): s = self.viper_ast.IntLit(types.VYPER_DECIMAL.scaling_factor, pos) mul = self.viper_ast.Mul(arg, s, pos) self.arithmetic_translator.check_overflow(mul, to_type, res, ctx, pos) return mul # If we convert an unsigned to a signed value we simply return # the argument, given that it fits elif case(types.VYPER_UINT256, types.VYPER_INT128): self.arithmetic_translator.check_overflow(arg, to_type, res, ctx, pos) return arg elif case(types.VYPER_UINT256, types.VYPER_BYTES32): return helpers.convert_unsigned_int_to_bytes32(self.viper_ast, arg, pos) # --------------------- bytes32 -> ? --------------------- elif case(types.VYPER_BYTES32, types.VYPER_DECIMAL) or case(types.VYPER_BYTES32, types.VYPER_INT128): i = helpers.convert_bytes32_to_signed_int(self.viper_ast, arg, pos) self.arithmetic_translator.check_under_overflow(i, to_type, res, ctx, pos) return i elif case(types.VYPER_BYTES32, types.VYPER_UINT256): # uint256 and bytes32 have the same size, so no overflow check is necessary return helpers.convert_bytes32_to_unsigned_int(self.viper_ast, arg, pos) else: raise UnsupportedException(node, 'Unsupported type converison.') elif name == names.KECCAK256: arg = self.translate(node.args[0], res, ctx) return helpers.keccak256(self.viper_ast, arg, pos) elif name == names.SHA256: arg = self.translate(node.args[0], res, ctx) return helpers.sha256(self.viper_ast, arg, pos) elif name == names.BLOCKHASH: arg = self.translate(node.args[0], res, ctx) block = ctx.block_var.local_var(ctx) number_type = self.type_translator.translate(types.BLOCK_TYPE.member_types[names.BLOCK_NUMBER], ctx) block_number = helpers.struct_get(self.viper_ast, block, names.BLOCK_NUMBER, number_type, types.BLOCK_TYPE, pos) # Only the last 256 blocks (before the current block) are available in blockhash, else we revert lt = self.viper_ast.LtCmp(arg, block_number, pos) last_256 = self.viper_ast.Sub(block_number, self.viper_ast.IntLit(256, pos), pos) ge = self.viper_ast.GeCmp(arg, last_256, pos) cond = self.viper_ast.Not(self.viper_ast.And(lt, ge, pos), pos) self.fail_if(cond, [], res, ctx, pos) return helpers.blockhash(self.viper_ast, arg, ctx, pos) elif name == names.METHOD_ID: arg = self.translate(node.args[0], res, ctx) return helpers.method_id(self.viper_ast, arg, node.type.size, pos) elif name == names.ECRECOVER: args = [self.translate(arg, res, ctx) for arg in node.args] return helpers.ecrecover(self.viper_ast, args, pos) elif name == names.ECADD or name == names.ECMUL: args = [self.translate(arg, res, ctx) for arg in node.args] fail_var_name = ctx.new_local_var_name('$fail') fail_var_decl = self.viper_ast.LocalVarDecl(fail_var_name, self.viper_ast.Bool, pos) ctx.new_local_vars.append(fail_var_decl) fail_var = fail_var_decl.localVar() self.fail_if(fail_var, [], res, ctx, pos) if name == names.ECADD: return helpers.ecadd(self.viper_ast, args, pos) else: return helpers.ecmul(self.viper_ast, args, pos) elif name == names.SELFDESTRUCT: to = self.translate(node.args[0], res, ctx) self_var = ctx.self_var.local_var(ctx) self_type = ctx.self_type balance = self.balance_translator.get_balance(self_var, ctx, pos) if ctx.program.config.has_option(names.CONFIG_ALLOCATION): self.allocation_translator.deallocate_wei(node, to, balance, res, ctx, pos) val = self.viper_ast.TrueLit(pos) member = mangled.SELFDESTRUCT_FIELD viper_type = self.type_translator.translate(self_type.member_types[member], ctx) sset = helpers.struct_set(self.viper_ast, self_var, val, member, viper_type, self_type, pos) res.append(self.viper_ast.LocalVarAssign(self_var, sset, pos)) self.balance_translator.increase_sent(to, balance, res, ctx, pos) zero = self.viper_ast.IntLit(0, pos) bset = self.balance_translator.set_balance(self_var, zero, ctx, pos) res.append(self.viper_ast.LocalVarAssign(self_var, bset, pos)) res.append(self.viper_ast.Goto(ctx.return_label, pos)) return None elif name == names.ASSERT_MODIFIABLE: cond = self.translate(node.args[0], res, ctx) not_cond = self.viper_ast.Not(cond, pos) self.fail_if(not_cond, [], res, ctx, pos) return None elif name == names.SEND: to = self.translate(node.args[0], res, ctx) amount = self.translate(node.args[1], res, ctx) _, expr = self._translate_external_call(node, to, amount, False, res, ctx) return expr elif name == names.RAW_CALL: # Translate the callee address to = self.translate(node.args[0], res, ctx) # Translate the data expression (bytes) _ = self.translate(node.args[1], res, ctx) amount = self.viper_ast.IntLit(0, pos) is_static = False for kw in node.keywords: arg = self.translate(kw.value, res, ctx) if kw.name == names.RAW_CALL_VALUE: amount = arg elif kw.name == names.RAW_CALL_IS_STATIC_CALL: assert isinstance(kw.value, ast.Bool) is_static = kw.value.value _, call = self._translate_external_call(node, to, amount, is_static, res, ctx) return call elif name == names.RAW_LOG: _ = self.translate(node.args[0], res, ctx) _ = self.translate(node.args[1], res, ctx) # Since we don't know what raw_log logs, any event could have been emitted. # Therefore we create a fresh var and do # if var == 0: # log.event1(...) # elif var == 1: # log.event2(...) # ... # for all events to indicate that at most one event has been emitted. var_name = ctx.new_local_var_name('$a') var_decl = self.viper_ast.LocalVarDecl(var_name, self.viper_ast.Int, pos) ctx.new_local_vars.append(var_decl) var = var_decl.localVar() for idx, event in enumerate(ctx.program.events.values()): condition = self.viper_ast.EqCmp(var, self.viper_ast.IntLit(idx, pos), pos) args = [] for arg_type in event.type.arg_types: arg_name = ctx.new_local_var_name('$arg') arg_type = self.type_translator.translate(arg_type, ctx) arg = self.viper_ast.LocalVarDecl(arg_name, arg_type, pos) ctx.new_local_vars.append(arg) args.append(arg.localVar()) log_event = [] self.log_event(event, args, log_event, ctx, pos) res.append(self.viper_ast.If(condition, log_event, [], pos)) return None elif name == names.CREATE_FORWARDER_TO: at = self.translate(node.args[0], res, ctx) if node.keywords: amount = self.translate(node.keywords[0].value, res, ctx) if ctx.program.config.has_option(names.CONFIG_ALLOCATION): msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) self.allocation_translator.deallocate_wei(node, msg_sender, amount, res, ctx, pos) self.balance_translator.check_balance(amount, res, ctx, pos) self.balance_translator.increase_sent(at, amount, res, ctx, pos) self.balance_translator.decrease_balance(amount, res, ctx, pos) new_name = ctx.new_local_var_name('$new') viper_type = self.type_translator.translate(node.type, ctx) new_var_decl = self.viper_ast.LocalVarDecl(new_name, viper_type, pos) ctx.new_local_vars.append(new_var_decl) new_var = new_var_decl.localVar() eq_zero = self.viper_ast.EqCmp(new_var, self.viper_ast.IntLit(0, pos), pos) self.fail_if(eq_zero, [], res, ctx, pos) return new_var # This is a struct initializer elif len(node.args) == 1 and isinstance(node.args[0], ast.Dict): first_arg = node.args[0] assert isinstance(first_arg, ast.Dict) exprs = {} for key, value in zip(first_arg.keys, first_arg.values): value_expr = self.translate(value, res, ctx) idx = node.type.member_indices[key.id] exprs[idx] = value_expr init_args = [exprs[i] for i in range(len(exprs))] init = helpers.struct_init(self.viper_ast, init_args, node.type, pos) return init # This is a contract / interface initializer elif name in ctx.current_program.contracts or name in ctx.current_program.interfaces: return self.translate(node.args[0], res, ctx) elif name in names.GHOST_STATEMENTS: return self.spec_translator.translate_ghost_statement(node, res, ctx) else: assert False def translate_ReceiverCall(self, node: ast.ReceiverCall, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) name = node.name args = [self.translate(arg, res, ctx) for arg in node.args] rec_type = node.receiver.type if isinstance(rec_type, types.SelfType): call_result = self.function_translator.inline(node, args, res, ctx) return call_result elif isinstance(rec_type, (ContractType, InterfaceType)): to = self.translate(node.receiver, res, ctx) val_idx = first_index(lambda n: n.name == names.RAW_CALL_VALUE, node.keywords) if val_idx >= 0: amount = self.translate(node.keywords[val_idx].value, res, ctx) else: amount = None if isinstance(rec_type, ContractType): const = rec_type.function_modifiers[node.name] == names.CONSTANT pure = rec_type.function_modifiers[node.name] == names.PURE _, call_result = self._translate_external_call(node, to, amount, const or pure, res, ctx) else: interface = ctx.program.interfaces[rec_type.name] function = interface.functions[name] const = function.is_constant() # If the function is payable, but no ether is sent, revert # If the function is not payable, but ether is sent, revert zero = self.viper_ast.IntLit(0, pos) if function.is_payable(): cond = self.viper_ast.LeCmp(amount, zero, pos) if amount else self.viper_ast.TrueLit(pos) else: cond = self.viper_ast.NeCmp(amount, zero, pos) if amount else self.viper_ast.FalseLit(pos) self.fail_if(cond, [], res, ctx, pos) known = (interface, function, args) succ, call_result = self._translate_external_call(node, to, amount, const, res, ctx, known) return call_result else: assert isinstance(node.receiver, ast.Name) if node.receiver.id == names.LOG: event = ctx.program.events[name] self.log_event(event, args, res, ctx, pos) return None elif node.receiver.id == names.LEMMA: lemma = ctx.program.lemmas[node.name] mangled_name = mangled.lemma_name(node.name) call_pos = self.to_position(lemma.node, ctx) via = Via('lemma', call_pos) pos = self.to_position(node, ctx, vias=[via], rules=rules.LEMMA_FAIL, values={'function': lemma}) args = [self.translate_top_level_expression(arg, res, ctx) for arg in node.args] for idx, arg_var in enumerate(lemma.args.values()): if types.is_numeric(arg_var.type): if self.arithmetic_translator.is_unwrapped(args[idx]): args[idx] = helpers.w_wrap(self.viper_ast, args[idx], pos) viper_ast = self.viper_ast if isinstance(viper_ast, WrappedViperAST): viper_ast = viper_ast.viper_ast return viper_ast.FuncApp(mangled_name, args, pos, type=self.viper_ast.Bool) else: assert False def assert_caller_private(self, modelt: ModelTransformation, res: List[Stmt], ctx: Context, vias: List[Via] = None): for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): with ctx.state_scope(ctx.current_state, ctx.current_old_state): for caller_private in interface.caller_private: pos = self.to_position(caller_private, ctx, rules.CALLER_PRIVATE_FAIL, vias or [], modelt) # Quantified variable q_name = mangled.quantifier_var_name(mangled.CALLER) q_var = TranslatedVar(mangled.CALLER, q_name, types.VYPER_ADDRESS, self.viper_ast, pos) ctx.locals[mangled.CALLER] = q_var # $caller != msg.sender ==> Expr == old(Expr) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) ignore_cond = self.viper_ast.NeCmp(msg_sender, q_var.local_var(ctx, pos), pos) _, curr_caller_private = self.spec_translator.translate_caller_private(caller_private, ctx) with ctx.state_scope(ctx.current_old_state, ctx.current_old_state): cond, old_caller_private = self.spec_translator\ .translate_caller_private(caller_private, ctx) ignore_cond = self.viper_ast.And(ignore_cond, cond, pos) caller_private_cond = self.viper_ast.EqCmp(curr_caller_private, old_caller_private, pos) expr = self.viper_ast.Implies(ignore_cond, caller_private_cond, pos) # Address type assumption type_assumptions = self.type_translator.type_assumptions(q_var.local_var(ctx), q_var.type, ctx) type_assumptions = reduce(self.viper_ast.And, type_assumptions, self.viper_ast.TrueLit()) expr = self.viper_ast.Implies(type_assumptions, expr, pos) # Assertion forall = self.viper_ast.Forall([q_var.var_decl(ctx)], [], expr, pos) res.append(self.viper_ast.Assert(forall, pos)) def assume_own_resources_stayed_constant(self, res: List[Stmt], ctx: Context, pos=None): if not ctx.program.config.has_option(names.CONFIG_ALLOCATION): return interface_names = [t.name for t in ctx.current_program.implements] interfaces = [ctx.current_program.interfaces[name] for name in interface_names] # The underlying wei resource must be translated differently. Therefore, exclude it for the moment. own_resources = [(name, resource) for name, resource in ctx.current_program.own_resources.items() if name != names.UNDERLYING_WEI] for i in interfaces: interface_resources = [(name, resource) for name, resource in i.own_resources.items() if name != names.UNDERLYING_WEI] own_resources.extend(interface_resources) translated_resources1 = self.resource_translator\ .translate_resources_for_quantified_expr(own_resources, ctx, pos) translated_resources2 = self.resource_translator\ .translate_resources_for_quantified_expr(own_resources, ctx, pos, args_idx_start=len(translated_resources1)) # Special translation for creator resources creator_resource = helpers.creator_resource() arg = self.viper_ast.LocalVarDecl(f'$arg$$1', helpers.struct_type(self.viper_ast), pos) t_resource = self.resource_translator.creator_resource(arg.localVar(), ctx, pos) translated_resources1.append((t_resource, [arg], self.viper_ast.TrueLit())) arg = self.viper_ast.LocalVarDecl(f'$arg$$2', helpers.struct_type(self.viper_ast), pos) t_resource = self.resource_translator.creator_resource(arg.localVar(), ctx, pos) translated_resources2.append((t_resource, [arg], self.viper_ast.TrueLit())) # forall({r: own Resources}, allocated[r]() == old(allocated[r]())) current_allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx) old_allocated = ctx.current_old_state[mangled.ALLOCATED].local_var(ctx) for t_resource, args, type_cond in translated_resources1: current_allocated_map = self.allocation_translator.get_allocated_map(current_allocated, t_resource, ctx) old_allocated_map = self.allocation_translator.get_allocated_map(old_allocated, t_resource, ctx) allocated_eq = self.viper_ast.EqCmp(current_allocated_map, old_allocated_map, pos) trigger = self.viper_ast.Trigger([current_allocated_map, t_resource], pos) forall_eq = self.viper_ast.Forall([*args], [trigger], self.viper_ast.Implies(type_cond, allocated_eq, pos), pos) res.append(self.viper_ast.Inhale(forall_eq, pos)) # trusted(self) == old(trusted(self)) current_trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx) old_trusted = ctx.current_old_state[mangled.TRUSTED].local_var(ctx) self_addr = ctx.self_address or helpers.self_address(self.viper_ast, pos) current_trusted_map = self.allocation_translator.get_trusted_map(current_trusted, self_addr, ctx) old_trusted_map = self.allocation_translator.get_trusted_map(old_trusted, self_addr, ctx) eq = self.viper_ast.EqCmp(current_trusted_map, old_trusted_map, pos) res.append(self.viper_ast.Inhale(eq, pos)) # Quantified address variable address = self.viper_ast.LocalVarDecl('$a', self.viper_ast.Int) address_var = address.localVar() address_type_conds = self.type_translator.type_assumptions(address_var, types.VYPER_ADDRESS, ctx) address_type_cond = reduce(lambda l, r: self.viper_ast.And(l, r, pos), address_type_conds, self.viper_ast.TrueLit()) # forall({r1: own Resources, r2: own Resources}, offered[r1 <-> r2]() == old(offered[r1 <-> r2]()) current_offered = ctx.current_state[mangled.OFFERED].local_var(ctx) old_offered = ctx.current_old_state[mangled.OFFERED].local_var(ctx) for index, (t_resource1, args1, type_cond1) in enumerate(translated_resources1): resource1 = own_resources[index][1] if index < len(own_resources) else None for t_resource2, args2, type_cond2 in translated_resources2: current_offered_map = self.allocation_translator.get_offered_map(current_offered, t_resource1, t_resource2, ctx) old_offered_map = self.allocation_translator.get_offered_map(old_offered, t_resource1, t_resource2, ctx) offered_eq = self.viper_ast.EqCmp(current_offered_map, old_offered_map, pos) type_cond = self.viper_ast.And(type_cond1, type_cond2) forall_eq = self.viper_ast.Forall( [*args1, *args2], [self.viper_ast.Trigger([current_offered_map], pos), self.viper_ast.Trigger([old_offered_map], pos)], self.viper_ast.Implies(type_cond, offered_eq, pos), pos) res.append(self.viper_ast.Inhale(forall_eq, pos)) if resource1 is not None and resource1.underlying_resource is not None: if resource1.name == names.WEI: t_underlying_resource = self.resource_translator.underlying_wei_resource(ctx) else: t_underlying_address = self.spec_translator.translate(resource1.underlying_address, res, ctx) args = self.viper_ast.to_list(t_resource1.getArgs()) args.pop() args.append(t_underlying_address) assert isinstance(resource1.type, types.DerivedResourceType) t_underlying_resource = helpers.struct_init(self.viper_ast, args, resource1.type.underlying_resource) current_offered_map = self.allocation_translator.get_offered_map(current_offered, t_resource1, t_underlying_resource, ctx) old_offered_map = self.allocation_translator.get_offered_map(old_offered, t_resource1, t_underlying_resource, ctx) offered_eq = self.viper_ast.EqCmp(current_offered_map, old_offered_map, pos) forall_eq = self.viper_ast.Forall( [*args1], [self.viper_ast.Trigger([current_offered_map], pos), self.viper_ast.Trigger([old_offered_map], pos)], self.viper_ast.Implies(type_cond1, offered_eq, pos), pos) res.append(self.viper_ast.Inhale(forall_eq, pos)) no_offers = helpers.no_offers(self.viper_ast, old_offered, t_resource1, address_var) curr_no_offers = helpers.no_offers(self.viper_ast, current_offered, t_resource1, address_var) implies = self.viper_ast.Implies(no_offers, curr_no_offers, pos) trigger = self.viper_ast.Trigger([curr_no_offers], pos) type_cond = self.viper_ast.And(type_cond1, address_type_cond) forall_eq = self.viper_ast.Forall([address, *args1], [trigger], self.viper_ast.Implies(type_cond, implies)) res.append(self.viper_ast.Inhale(forall_eq, pos)) def assume_interface_resources_stayed_constant(self, interface, interface_inst, res, ctx: Context, pos=None): if isinstance(interface, VyperProgram): with ctx.program_scope(interface): with ctx.self_address_scope(interface_inst): self.assume_own_resources_stayed_constant(res, ctx, pos) def _implicit_resource_caller_private_expressions(self, interface, self_address, res, ctx, pos=None): if not ctx.program.config.has_option(names.CONFIG_ALLOCATION): return body = [] # Quantified self address q_self_address_from_context = [] q_self_address_name = mangled.quantifier_var_name(names.INTERFACE) q_self_address = ctx.quantified_vars.get(q_self_address_name) if q_self_address is not None: q_self_address_from_context = [q_self_address.var_decl(ctx)] # Interface Address interface_addr = ctx.self_address or helpers.self_address(self.viper_ast) # Quantified address variable address = self.viper_ast.LocalVarDecl('$a', self.viper_ast.Int) address_var = address.localVar() type_conds = self.type_translator.type_assumptions(address_var, types.VYPER_ADDRESS, ctx) type_cond = reduce(lambda l, r: self.viper_ast.And(l, r, pos), type_conds, self.viper_ast.TrueLit()) # forall({a: address}, trusted(a, by=self, where=interface) # == old(trusted(a, by=self, where=interface))) current_trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx) old_trusted = ctx.current_old_state[mangled.TRUSTED].local_var(ctx) curr_trusted_value = self.allocation_translator.get_trusted(current_trusted, interface_addr, address_var, self_address, ctx) old_trusted_value = self.allocation_translator.get_trusted(old_trusted, interface_addr, address_var, self_address, ctx) trusted_eq = self.viper_ast.EqCmp(curr_trusted_value, old_trusted_value) forall_eq = self.viper_ast.Forall([address, *q_self_address_from_context], [self.viper_ast.Trigger([old_trusted_value], pos), self.viper_ast.Trigger([curr_trusted_value], pos)], self.viper_ast.Implies(type_cond, trusted_eq)) body.append(self.viper_ast.Inhale(forall_eq, pos)) current_trust_no_one = helpers.trust_no_one(self.viper_ast, current_trusted, self_address, interface_addr) old_trust_no_one = helpers.trust_no_one(self.viper_ast, old_trusted, self_address, interface_addr) forall_implies = self.viper_ast.Forall([*q_self_address_from_context], [self.viper_ast.Trigger([current_trust_no_one], pos), self.viper_ast.Trigger([old_trust_no_one], pos)], self.viper_ast.Implies(old_trust_no_one, current_trust_no_one)) body.append(self.viper_ast.Inhale(forall_implies, pos)) # Declared resources of interface resources = interface.declared_resources.items() translated_resources1 = self.resource_translator.translate_resources_for_quantified_expr(resources, ctx) translated_resources2 = self.resource_translator\ .translate_resources_for_quantified_expr(resources, ctx, args_idx_start=len(translated_resources1)) # No trust condition trust_no_one = helpers.trust_no_one(self.viper_ast, old_trusted, self_address, interface_addr) # Quantified offer struct variable offer = self.viper_ast.LocalVarDecl('$o', helpers.struct_type(self.viper_ast)) offer_var = offer.localVar() # Offered map type offered_type = helpers.offered_type() k_type = self.type_translator.translate(offered_type.value_type.value_type.key_type, ctx) v_type = self.type_translator.translate(offered_type.value_type.value_type.value_type, ctx) # forall({r1: Resource on interface, r2: Resource on interface, o: Offer}, # trust_no_one(self, interface) ==> old(offered[r1 <-> r2][o]) == 0 ==> # offered[r1 <-> r2][o] == 0) current_offered = ctx.current_state[mangled.OFFERED].local_var(ctx) old_offered = ctx.current_old_state[mangled.OFFERED].local_var(ctx) for t_resource1, args1, type_cond1 in translated_resources1: for t_resource2, args2, type_cond2 in translated_resources2: current_offered_map = self.allocation_translator \ .get_offered_map(current_offered, t_resource1, t_resource2, ctx) old_offered_map = self.allocation_translator \ .get_offered_map(old_offered, t_resource1, t_resource2, ctx) current_offered_map_get = helpers.map_get(self.viper_ast, current_offered_map, offer_var, k_type, v_type) old_offered_map_get = helpers.map_get(self.viper_ast, old_offered_map, offer_var, k_type, v_type) offered_eq = self.viper_ast.EqCmp(current_offered_map_get, old_offered_map_get) type_cond = self.viper_ast.And(type_cond1, type_cond2) cond = self.viper_ast.And(trust_no_one, type_cond) forall_eq = self.viper_ast.Forall([offer, *args1, *args2, *q_self_address_from_context], [self.viper_ast.Trigger([current_offered_map_get], pos), self.viper_ast.Trigger([old_offered_map_get], pos)], self.viper_ast.Implies(cond, offered_eq)) body.append(self.viper_ast.Inhale(forall_eq, pos)) # forall({r: Resource on interface}, trust_no_one(self, interface) # and no_offers[r](self) ==> allocated[r](self) >= old(allocated[r](self))) current_allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx) old_allocated = ctx.current_old_state[mangled.ALLOCATED].local_var(ctx) for t_resource, args, type_cond in translated_resources1: # No offers condition no_offers = helpers.no_offers(self.viper_ast, old_offered, t_resource, self_address) curr_no_offers = helpers.no_offers(self.viper_ast, current_offered, t_resource, self_address) current_allocated_map = self.allocation_translator \ .get_allocated(current_allocated, t_resource, self_address, ctx) old_allocated_map = self.allocation_translator \ .get_allocated(old_allocated, t_resource, self_address, ctx) allocated_geq = self.viper_ast.GeCmp(current_allocated_map, old_allocated_map, pos) cond = self.viper_ast.And(trust_no_one, no_offers) allocated_geq = self.viper_ast.Implies(cond, allocated_geq) forall_implies = self.viper_ast.Forall([*args, *q_self_address_from_context], [self.viper_ast.Trigger([current_allocated_map], pos), self.viper_ast.Trigger([old_allocated_map], pos)], self.viper_ast.Implies(type_cond, allocated_geq, pos), pos) body.append(self.viper_ast.Inhale(forall_implies, pos)) forall_implies = self.viper_ast.Forall([*args, *q_self_address_from_context], [self.viper_ast.Trigger([no_offers], pos), self.viper_ast.Trigger([curr_no_offers], pos)], self.viper_ast.Implies(no_offers, curr_no_offers, pos), pos) body.append(self.viper_ast.Inhale(forall_implies, pos)) self.seqn_with_info(body, f"Implicit caller private expr of resources in interface {interface.name}", res) def implicit_resource_caller_private_expressions(self, interface, interface_inst, self_address, res, ctx: Context, pos=None): if isinstance(interface, VyperInterface): with ctx.program_scope(interface): with ctx.self_address_scope(interface_inst): self._implicit_resource_caller_private_expressions(interface, self_address, res, ctx, pos) def assume_contract_state(self, known_interface_refs: List[Tuple[str, Expr]], res: List[Stmt], ctx: Context, receiver: Optional[Expr] = None, skip_caller_private=False): for interface_name, interface_ref in known_interface_refs: body = [] if not skip_caller_private: # Assume caller private interface = ctx.program.interfaces[interface_name] with ctx.program_scope(interface): with ctx.state_scope(ctx.current_state, ctx.current_old_state): # Caller variable mangled_name = ctx.new_local_var_name(mangled.CALLER) caller_var = TranslatedVar(mangled.CALLER, mangled_name, types.VYPER_ADDRESS, self.viper_ast) ctx.locals[mangled.CALLER] = caller_var ctx.new_local_vars.append(caller_var.var_decl(ctx)) self_address = ctx.self_address or helpers.self_address(self.viper_ast) if self.arithmetic_translator.is_wrapped(self_address): self_address = helpers.w_unwrap(self.viper_ast, self_address) assign = self.viper_ast.LocalVarAssign(caller_var.local_var(ctx), self_address) body.append(assign) with ctx.self_address_scope(interface_ref): for caller_private in interface.caller_private: pos = self.to_position(caller_private, ctx, rules.INHALE_CALLER_PRIVATE_FAIL) # Caller private assumption _, curr_caller_private = self.spec_translator\ .translate_caller_private(caller_private, ctx) with ctx.state_scope(ctx.current_old_state, ctx.current_old_state): cond, old_caller_private = self.spec_translator\ .translate_caller_private(caller_private, ctx) caller_private_cond = self.viper_ast.EqCmp(curr_caller_private, old_caller_private, pos) caller_private_cond = self.viper_ast.Implies(cond, caller_private_cond, pos) body.append(self.viper_ast.Inhale(caller_private_cond, pos)) self._implicit_resource_caller_private_expressions(interface, caller_var.local_var(ctx), body, ctx) if receiver and body: neq_cmp = self.viper_ast.NeCmp(receiver, interface_ref) body = helpers.flattened_conditional(self.viper_ast, neq_cmp, body, []) # Assume interface invariants interface = ctx.program.interfaces[interface_name] with ctx.program_scope(interface): with ctx.self_address_scope(interface_ref): for inv in ctx.current_program.invariants: cond = self.spec_translator.translate_invariant(inv, res, ctx, True) i_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) body.append(self.viper_ast.Inhale(cond, i_pos)) if ctx.program.config.has_option(names.CONFIG_TRUST_CASTS): res.extend(body) else: implements = helpers.implements(self.viper_ast, interface_ref, interface_name, ctx) res.extend(helpers.flattened_conditional(self.viper_ast, implements, body, [])) def log_event(self, event: VyperEvent, args: List[Expr], res: List[Stmt], ctx: Context, pos=None): assert ctx event_name = mangled.event_name(event.name) pred_acc = self.viper_ast.PredicateAccess(args, event_name, pos) one = self.viper_ast.FullPerm(pos) pred_acc_pred = self.viper_ast.PredicateAccessPredicate(pred_acc, one, pos) log = self.viper_ast.Inhale(pred_acc_pred, pos) self.seqn_with_info([log], f"Event: {event.name}", res) def _translate_external_call(self, node: ast.Expr, to: Expr, amount: Optional[Expr], constant: bool, res: List[Stmt], ctx: Context, known: Tuple[VyperInterface, VyperFunction, List[Expr]] = None) -> Tuple[Expr, Expr]: # Sends are translated as follows: # - Evaluate arguments to and amount # - Check that balance is sufficient (self.balance >= amount) else revert # - Increment sent by amount # - Subtract amount from self.balance (self.balance -= amount) # - If in init, set old_self to self if this is the first public state # - Assert checks, own 'caller private' and inter contract invariants # - The next step is only necessary if the function is modifying: # - Create new old-contract state # - Havoc contract state # - Assert local state invariants # - Fail based on an unknown value (i.e. the call could fail) # - The next step is only necessary if the function is modifying: # - Undo havocing of contract state # - The next steps are only necessary if the function is modifying: # - Create new old state which old in the invariants after the call refers to # - Store state before call (To be used to restore old contract state) # - Havoc state # - Assume 'caller private' of interface state variables but NOT receiver # - Assume invariants of interface state variables and receiver # - Create new old-contract state # - Havoc contract state # - Assume type assumptions for self # - Assume local state invariants (where old refers to the state before send) # - Assume invariants of interface state variables and receiver # - Assume transitive postcondition # - Assume that there were no reentrant calls based on an unknown value # - If there were no reentrant calls: # - Restore state from old state # - Restore old contract state # - Create new old-contract state # - Havoc contract state # - Assume 'caller private' of interface state variables and receiver # - Assert inter contract invariants (during call) # - Create new old-contract state # - Havoc contract state # - Assume 'caller private' of interface state variables but NOT receiver # - Assume invariants of interface state variables and receiver # - Restore old contract state # - In the case of an interface call: # - Assume postconditions # - The next step is only necessary if the function is modifying: # - Assert inter contract invariants (after call) # - Create new old state which subsequent old expressions refer to pos = self.to_position(node, ctx) self_var = ctx.self_var.local_var(ctx) modifying = not constant if known: interface, function, args = known else: interface = None function = None args = None if amount: self.balance_translator.check_balance(amount, res, ctx, pos) self.balance_translator.increase_sent(to, amount, res, ctx, pos) if ctx.program.config.has_option(names.CONFIG_ALLOCATION): self.allocation_translator.deallocate_wei(node, to, amount, res, ctx, pos) self.balance_translator.decrease_balance(amount, res, ctx, pos) general_stmts_for_performs = [] performs_as_stmts_generators = [] with ctx.inline_scope(None): # Create pre_state for function call def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) state_for_performs = self.state_translator.state(inlined_pre_state, ctx) if modifying: # Save the values of to, amount, and args, as self could be changed by reentrancy if known: def new_var(variable, name='v'): name += '$' var_name = ctx.new_local_var_name(name) var_decl = self.viper_ast.LocalVarDecl(var_name, variable.typ(), pos) ctx.new_local_vars.append(var_decl) res.append(self.viper_ast.LocalVarAssign(var_decl.localVar(), variable)) return var_decl.localVar() to = new_var(to, 'to') if amount: amount = new_var(amount, 'amount') # Force evaluation at this point args = list(map(new_var, args)) if known and function.performs: self.state_translator.copy_state(ctx.current_state, state_for_performs, general_stmts_for_performs, ctx) performs_as_stmts = {} performs_decider_variables = {} sender_is_resource_address_map = {} with ctx.program_scope(interface): with ctx.self_address_scope(to): with ctx.state_scope(ctx.current_state, ctx.current_old_state): ctx.current_state[mangled.SELF] = state_for_performs[mangled.SELF] ctx.current_state[mangled.CONTRACTS] = state_for_performs[mangled.CONTRACTS] with ctx.interface_call_scope(): # Define new msg variable msg_name = ctx.inline_prefix + mangled.MSG msg_var = TranslatedVar(names.MSG, msg_name, types.MSG_TYPE, self.viper_ast) ctx.locals[names.MSG] = msg_var ctx.new_local_vars.append(msg_var.var_decl(ctx)) # Assume msg.sender == self and msg.value == amount msg = msg_var.local_var(ctx) svytype = types.MSG_TYPE.member_types[names.MSG_SENDER] svitype = self.type_translator.translate(svytype, ctx) msg_sender = helpers.struct_get(self.viper_ast, msg, names.MSG_SENDER, svitype, types.MSG_TYPE) self_address = helpers.self_address(self.viper_ast) general_stmts_for_performs.append(self.viper_ast.Inhale( self.viper_ast.EqCmp(msg_sender, self_address))) if amount: vvytype = types.MSG_TYPE.member_types[names.MSG_VALUE] vvitype = self.type_translator.translate(vvytype, ctx) msg_value = helpers.struct_get(self.viper_ast, msg, names.MSG_VALUE, vvitype, types.MSG_TYPE) general_stmts_for_performs.append(self.viper_ast.Inhale( self.viper_ast.EqCmp(msg_value, amount))) # Arguments as translated variables args_as_translated_var = [ TranslatedVar(name, val.name(), arg.type, self.viper_ast, is_local=not self.arithmetic_translator.is_wrapped(val)) for (name, arg), val in zip(function.args.items(), args)] ctx.locals.update((var.name, var) for var in args_as_translated_var) # Assume performs clauses with ctx.derived_resource_performs_scope(): for performs in function.performs: self.spec_translator.translate_ghost_statement( performs, general_stmts_for_performs, ctx, is_performs=True) zero = self.viper_ast.IntLit(0) two = self.viper_ast.IntLit(2) for performs_idx, performs in enumerate(function.performs): location_address = self.allocation_translator.location_address_of_performs( performs, res, ctx) if location_address is not None: sender_is_resource_address = self.viper_ast.EqCmp(msg_sender, location_address) else: sender_is_resource_address = self.viper_ast.FalseLit() perform_as_stmts = [] self.spec_translator.translate(performs, perform_as_stmts, ctx) performs_var_name = ctx.new_local_var_name("performs_decider_var") performs_var = TranslatedVar(performs_var_name, performs_var_name, types.VYPER_UINT256, self.viper_ast) ctx.locals[performs_var_name] = performs_var ctx.new_local_vars.append(performs_var.var_decl(ctx)) performs_local_var = performs_var.local_var(ctx) performs_var_ge_zero = self.viper_ast.GeCmp(performs_local_var, zero) performs_var_le_two = self.viper_ast.LeCmp(performs_local_var, two) cond = self.viper_ast.And(performs_var_ge_zero, performs_var_le_two) general_stmts_for_performs.append(self.viper_ast.Inhale(cond)) performs_as_stmts[performs_idx] = perform_as_stmts performs_decider_variables[performs_idx] = performs_local_var sender_is_resource_address_map[performs_idx] = sender_is_resource_address def conditional_perform_generator(p_idx: int) -> Callable[[int], List[Stmt]]: def conditional_perform(index: int) -> List[Stmt]: if index >= 0: idx = self.viper_ast.IntLit(index) decider_eq_idx = self.viper_ast.EqCmp( performs_decider_variables[p_idx], idx) cond_for_perform = self.viper_ast.And( decider_eq_idx, self.viper_ast.Not( sender_is_resource_address_map[performs_idx])) return helpers.flattened_conditional(self.viper_ast, cond_for_perform, performs_as_stmts[p_idx], []) else: return helpers.flattened_conditional( self.viper_ast, sender_is_resource_address_map[performs_idx], performs_as_stmts[p_idx], []) return conditional_perform performs_as_stmts_generators.append(conditional_perform_generator(performs_idx)) res.extend(general_stmts_for_performs) # In init set the old self state to the current self state, if this is the # first public state. if ctx.function.name == names.INIT: self.state_translator.check_first_public_state(res, ctx, True) modelt = self.model_translator.save_variables(res, ctx, pos) self.assert_caller_private(modelt, res, ctx, [Via('external function call', pos)]) for check in chain(ctx.function.checks, ctx.program.general_checks): check_cond = self.spec_translator.translate_check(check, res, ctx) via = [Via('check', check_cond.pos())] check_pos = self.to_position(node, ctx, rules.CALL_CHECK_FAIL, via, modelt) res.append(self.viper_ast.Assert(check_cond, check_pos)) def assert_invariants(inv_getter: Callable[[Context], List[ast.Expr]], rule: rules.Rule) -> List[Stmt]: res_list = [] # Assert implemented interface invariants for implemented_interface in ctx.program.implements: vyper_interface = ctx.program.interfaces[implemented_interface.name] with ctx.program_scope(vyper_interface): for inv in inv_getter(ctx): translated_inv = self.spec_translator.translate_invariant(inv, res_list, ctx, True) call_pos = self.to_position(node, ctx, rule, [Via('invariant', translated_inv.pos())], modelt) res_list.append(self.viper_ast.Assert(translated_inv, call_pos)) # Assert own invariants for inv in inv_getter(ctx): # We ignore accessible because it only has to be checked in the end of # the function translated_inv = self.spec_translator.translate_invariant(inv, res_list, ctx, True) call_pos = self.to_position(node, ctx, rule, [Via('invariant', translated_inv.pos())], modelt) res_list.append(self.viper_ast.Assert(translated_inv, call_pos)) return res_list def assume_invariants(inv_getter: Callable[[Context], List[ast.Expr]]) -> List[Stmt]: res_list = [] # Assume implemented interface invariants for implemented_interface in ctx.program.implements: vyper_interface = ctx.program.interfaces[implemented_interface.name] with ctx.program_scope(vyper_interface): for inv in inv_getter(ctx): translated_inv = self.spec_translator.translate_invariant(inv, res_list, ctx, True) inv_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) res_list.append(self.viper_ast.Inhale(translated_inv, inv_pos)) # Assume own invariants for inv in inv_getter(ctx): translated_inv = self.spec_translator.translate_invariant(inv, res_list, ctx, True) inv_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) res_list.append(self.viper_ast.Inhale(translated_inv, inv_pos)) return res_list assert_inter_contract_invariants = assert_invariants(lambda c: c.current_program.inter_contract_invariants, rules.CALL_INVARIANT_FAIL) self.seqn_with_info(assert_inter_contract_invariants, "Assert inter contract invariants before call", res) assert_derived_resource_invariants = [self.viper_ast.Assert(expr, expr.pos()) for expr in ctx.derived_resources_invariants(node)] self.seqn_with_info(assert_derived_resource_invariants, "Assert derived resource invariants before call", res) self.forget_about_all_events(res, ctx, pos) if modifying: # Copy contract state self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) # Havoc contract state self.state_translator.havoc_state(ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) self.assume_own_resources_stayed_constant(res, ctx, pos) assert_local_state_invariants = assert_invariants(lambda c: c.current_program.local_state_invariants, rules.CALL_INVARIANT_FAIL) self.seqn_with_info(assert_local_state_invariants, "Assert local state invariants before call", res) # We check that the invariant tracks all allocation by doing a leak check. if ctx.program.config.has_option(names.CONFIG_ALLOCATION): self.allocation_translator.send_leak_check(node, res, ctx, pos) send_fail_name = ctx.new_local_var_name('send_fail') send_fail = self.viper_ast.LocalVarDecl(send_fail_name, self.viper_ast.Bool) ctx.new_local_vars.append(send_fail) fail_cond = send_fail.localVar() if node.type: ret_name = ctx.new_local_var_name('raw_ret') ret_type = self.type_translator.translate(node.type, ctx) ret_var = self.viper_ast.LocalVarDecl(ret_name, ret_type, pos) ctx.new_local_vars.append(ret_var) return_value = ret_var.localVar() type_ass = self.type_translator.type_assumptions(return_value, node.type, ctx) res.extend(self.viper_ast.Inhale(ass) for ass in type_ass) else: return_value = None call_failed = helpers.call_failed(self.viper_ast, to, pos) self.fail_if(fail_cond, [call_failed], res, ctx, pos) if isinstance(node, ast.ReceiverCall): # If it is a receiver call and the receiver is null the transaction will revert. self.fail_if(self.viper_ast.EqCmp(to, self.viper_ast.IntLit(0, pos), pos), [call_failed], res, ctx, pos) with ctx.inline_scope(None): # Create pre_state for function call def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) old_state_for_postconditions = self.state_translator.state(inlined_pre_state, ctx) with ctx.inline_scope(None): # Create needed states to verify inter contract invariants def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) old_state_for_inter_contract_invariant_during = self.state_translator.state(inlined_pre_state, ctx) def inlined_old_state(name: str) -> str: return ctx.inline_prefix + mangled.old_state_var_name(name) curr_state_for_inter_contract_invariant_during = self.state_translator.state(inlined_old_state, ctx) with ctx.inline_scope(None): # Create needed states to verify inter contract invariants def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) old_state_for_inter_contract_invariant_after = self.state_translator.state(inlined_pre_state, ctx) def inlined_old_state(name: str) -> str: return ctx.inline_prefix + mangled.old_state_var_name(name) curr_state_for_inter_contract_invariant_after = self.state_translator.state(inlined_old_state, ctx) known_interface_ref = [] if modifying: # Collect known interface references self_type = ctx.program.fields.type for member_name, member_type in self_type.member_types.items(): viper_type = self.type_translator.translate(member_type, ctx) if isinstance(member_type, types.InterfaceType): get = helpers.struct_get(self.viper_ast, ctx.self_var.local_var(ctx), member_name, viper_type, self_type) known_interface_ref.append((member_type.name, get)) for var in chain(ctx.locals.values(), ctx.args.values()): assert isinstance(var, TranslatedVar) if isinstance(var.type, types.InterfaceType): known_interface_ref.append((var.type.name, var.local_var(ctx))) # Undo havocing of contract state self.state_translator.copy_state(ctx.current_old_state, ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) for val in chain(state_for_performs.values(), old_state_for_postconditions.values(), old_state_for_inter_contract_invariant_during.values(), curr_state_for_inter_contract_invariant_during.values(), old_state_for_inter_contract_invariant_after.values(), curr_state_for_inter_contract_invariant_after.values()): ctx.new_local_vars.append(val.var_decl(ctx, pos)) # Copy state self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx) if modifying: # Prepare old state for the postconditions of the external call self.state_translator.copy_state(ctx.current_state, old_state_for_postconditions, res, ctx) # Havoc state self.state_translator.havoc_state(ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) self.assume_own_resources_stayed_constant(res, ctx, pos) # Prepare old state for inter contract invariants assume_caller_private_without_receiver = [] self.assume_contract_state(known_interface_ref, assume_caller_private_without_receiver, ctx, to) self.seqn_with_info(assume_caller_private_without_receiver, "Assume caller private for old state", res) caller_address = ctx.self_address or helpers.self_address(self.viper_ast) self.implicit_resource_caller_private_expressions(interface, to, caller_address, res, ctx) res.extend(stmt for performs_as_stmts in performs_as_stmts_generators for stmt in performs_as_stmts(0)) self.state_translator.copy_state(ctx.current_state, old_state_for_inter_contract_invariant_during, res, ctx) # Assume caller private and create new contract state self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) self.state_translator.havoc_state(ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) self.assume_own_resources_stayed_constant(res, ctx, pos) self.seqn_with_info(assume_caller_private_without_receiver, "Assume caller private", res) self.implicit_resource_caller_private_expressions(interface, to, caller_address, res, ctx) res.extend(stmt for performs_as_stmts in performs_as_stmts_generators for stmt in performs_as_stmts(1)) self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) self.state_translator.havoc_state(ctx.current_state, res, ctx) ############################################################################################################ # We did not yet make any assumptions about the self state. # # # # The contract state (which models all self states of other contracts) is at a point where anything could # # have happened, but it is before the receiver of the external call has made any re-entrant call to self. # ############################################################################################################ res.extend(stmt for performs_as_stmts in performs_as_stmts_generators for stmt in performs_as_stmts(-1)) type_ass = self.type_translator.type_assumptions(self_var, ctx.self_type, ctx) assume_type_ass = [self.viper_ast.Inhale(inv) for inv in type_ass] self.seqn_with_info(assume_type_ass, "Assume type assumptions", res) assume_invs = [] for inv in ctx.unchecked_invariants(): assume_invs.append(self.viper_ast.Inhale(inv)) assume_invs.extend(assume_invariants(lambda c: c.current_program.local_state_invariants)) self.seqn_with_info(assume_invs, "Assume local state invariants", res) # Assume transitive postconditions assume_transitive_posts = [] self.assume_contract_state(known_interface_ref, assume_transitive_posts, ctx, skip_caller_private=True) for post in ctx.unchecked_transitive_postconditions(): assume_transitive_posts.append(self.viper_ast.Inhale(post)) for post in ctx.program.transitive_postconditions: post_expr = self.spec_translator.translate_pre_or_postcondition(post, assume_transitive_posts, ctx) ppos = self.to_position(post, ctx, rules.INHALE_POSTCONDITION_FAIL) assume_transitive_posts.append(self.viper_ast.Inhale(post_expr, ppos)) self.seqn_with_info(assume_transitive_posts, "Assume transitive postconditions", res) no_reentrant_name = ctx.new_local_var_name('no_reentrant_call') no_reentrant = self.viper_ast.LocalVarDecl(no_reentrant_name, self.viper_ast.Bool) ctx.new_local_vars.append(no_reentrant) no_reentrant_cond = no_reentrant.localVar() # If there were no reentrant calls, reset the contract state. use_zero_reentrant_call_state = [] self.state_translator.copy_state(ctx.current_old_state, ctx.current_state, use_zero_reentrant_call_state, ctx) res.extend(helpers.flattened_conditional(self.viper_ast, no_reentrant_cond, use_zero_reentrant_call_state, [])) ############################################################################################################ # At this point, we have a self state with all the assumptions of a self state in a public state. # # This self state corresponds to the last state of self after any (zero or more) re-entrant calls. # # # # The contract state is at this point also at the public state after the last re-entrant call to self. # # Due to re-entrant calls, any caller private expression might have gotten modified. But we can assume # # that they are only modified by self and only in such a way as described in the # # transitive postconditions. # ############################################################################################################ # Assume caller private in a new contract state self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) self.state_translator.havoc_state(ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) self.assume_own_resources_stayed_constant(res, ctx, pos) assume_caller_private = [] self.assume_contract_state(known_interface_ref, assume_caller_private, ctx) self.seqn_with_info(assume_caller_private, "Assume caller private", res) ############################################################################################################ # Since no more re-entrant calls can happen, the self state does not change anymore. # # # # The contract state is at a point where the last call, which lead to a re-entrant call to self, returned. # # We can assume all caller private expressions of self stayed constant, since the contract state above. # # We can only assume that variables captured with a caller private expression did not change, since # # any other contract might got called which could change everything except caller private expressions. # ############################################################################################################ # Store the states to assert the inter contract invariants during the call self.state_translator.copy_state(ctx.current_state, curr_state_for_inter_contract_invariant_during, res, ctx) # Assume caller private in a new contract state self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) self.state_translator.havoc_state(ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) self.assume_own_resources_stayed_constant(res, ctx, pos) self.seqn_with_info(assume_caller_private_without_receiver, "Assume caller private", res) self.implicit_resource_caller_private_expressions(interface, to, caller_address, res, ctx) res.extend(stmt for performs_as_stmts in performs_as_stmts_generators for stmt in performs_as_stmts(2)) ############################################################################################################ # The contract state is at the point where the external call returns. Since the last modeled public state, # # any non-caller-private expression might have changed but also the caller private # # expressions of the receiver. Therefore, we can only assume that all but the receiver's caller private # # expressions stayed constant. # ############################################################################################################ # Store the states to assert the inter contract invariants after the call self.state_translator.copy_state(ctx.current_state, curr_state_for_inter_contract_invariant_after, res, ctx) self.state_translator.copy_state(ctx.current_old_state, old_state_for_inter_contract_invariant_after, res, ctx) # Assume caller private in a new contract state self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) self.state_translator.havoc_state(ctx.current_state, res, ctx, unless=lambda n: n == mangled.SELF) self.assume_own_resources_stayed_constant(res, ctx, pos) self.seqn_with_info(assume_caller_private_without_receiver, "Assume caller private", res) self.implicit_resource_caller_private_expressions(interface, to, caller_address, res, ctx) ############################################################################################################ # The contract is at the end of the external call, only changes to the caller private expressions of the # # receiver of the external call could have happened. # # This state models the same state as the previous. But, we must not assert the inter contract invariants # # in the state where we assumed the postcondition. # ############################################################################################################ # Restore old state for postcondition self.state_translator.copy_state(old_state_for_postconditions, ctx.current_old_state, res, ctx, unless=lambda n: n == mangled.SELF) # Assume type assumptions for allocation maps self.state_translator.assume_type_assumptions_for_state( {name: state for name, state in ctx.current_state.items() if StateTranslator.is_allocation(name)}, "State after call", res, ctx) success = self.viper_ast.Not(fail_cond, pos) amount = amount or self.viper_ast.IntLit(0) # Assume postcondition of the external call if known: self._assume_interface_specifications(node, interface, function, args, to, amount, success, return_value, res, ctx) if modifying: # Assert inter contract invariants during call with ctx.state_scope(curr_state_for_inter_contract_invariant_during, old_state_for_inter_contract_invariant_during): assert_invs = assert_invariants(lambda c: c.current_program.inter_contract_invariants, rules.DURING_CALL_INVARIANT_FAIL) self.seqn_with_info(assert_invs, "Assert inter contract invariants during call", res) # Assert inter contract invariants after call with ctx.state_scope(curr_state_for_inter_contract_invariant_after, old_state_for_inter_contract_invariant_after): assert_invs = assert_invariants(lambda c: c.current_program.inter_contract_invariants, rules.DURING_CALL_INVARIANT_FAIL) self.seqn_with_info(assert_invs, "Assert inter contract invariants after call", res) self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, res, ctx) return success, return_value def forget_about_all_events(self, res, ctx, pos): # We forget about events by exhaling all permissions to the event predicates, i.e. # for all event predicates e we do # exhale forall arg0, arg1, ... :: perm(e(arg0, arg1, ...)) > none ==> acc(e(...), perm(e(...))) # We use an implication with a '> none' because of a bug in Carbon (TODO: issue #171) where it isn't possible # to exhale no permissions under a quantifier. for event in ctx.program.events.values(): event_name = mangled.event_name(event.name) viper_types = [self.type_translator.translate(arg, ctx) for arg in event.type.arg_types] event_args = [self.viper_ast.LocalVarDecl(f'$arg{idx}', viper_type, pos) for idx, viper_type in enumerate(viper_types)] local_args = [arg.localVar() for arg in event_args] pa = self.viper_ast.PredicateAccess(local_args, event_name, pos) perm = self.viper_ast.CurrentPerm(pa, pos) pap = self.viper_ast.PredicateAccessPredicate(pa, perm, pos) none = self.viper_ast.NoPerm(pos) impl = self.viper_ast.Implies(self.viper_ast.GtCmp(perm, none, pos), pap) trigger = self.viper_ast.Trigger([pa], pos) forall = self.viper_ast.Forall(event_args, [trigger], impl, pos) res.append(self.viper_ast.Exhale(forall, pos)) def log_all_events_zero_or_more_times(self, res, ctx, pos): for event in ctx.program.events.values(): event_name = mangled.event_name(event.name) viper_types = [self.type_translator.translate(arg, ctx) for arg in event.type.arg_types] event_args = [self.viper_ast.LocalVarDecl(ctx.new_local_var_name('$arg'), arg_type, pos) for arg_type in viper_types] ctx.new_local_vars.extend(event_args) local_args = [arg.localVar() for arg in event_args] ctx.event_vars[event_name] = local_args # Inhale zero or more times write permission # PermMul variable for unknown permission amount var_name = ctx.new_local_var_name('$a') var_decl = self.viper_ast.LocalVarDecl(var_name, self.viper_ast.Int, pos) ctx.new_local_vars.append(var_decl) var_perm_mul = var_decl.localVar() ge_zero_cond = self.viper_ast.GeCmp(var_perm_mul, self.viper_ast.IntLit(0, pos), pos) assume_ge_zero = self.viper_ast.Inhale(ge_zero_cond, pos) # PredicateAccessPredicate pred_acc = self.viper_ast.PredicateAccess(local_args, event_name, pos) perm_mul = self.viper_ast.IntPermMul(var_perm_mul, self.viper_ast.FullPerm(pos), pos) pred_acc_pred = self.viper_ast.PredicateAccessPredicate(pred_acc, perm_mul, pos) log_event = self.viper_ast.Inhale(pred_acc_pred, pos) # Append both Inhales res.extend([assume_ge_zero, log_event]) def _assume_interface_specifications(self, node: ast.Node, interface: VyperInterface, function: VyperFunction, args: List[Expr], to: Expr, amount: Expr, succ: Expr, return_value: Optional[Expr], res: List[Stmt], ctx: Context): with ctx.interface_call_scope(): body = [] # Define new msg variable msg_name = ctx.inline_prefix + mangled.MSG msg_var = TranslatedVar(names.MSG, msg_name, types.MSG_TYPE, self.viper_ast) ctx.locals[names.MSG] = msg_var ctx.new_local_vars.append(msg_var.var_decl(ctx)) # Assume msg.sender == self and msg.value == amount msg = msg_var.local_var(ctx) svytype = types.MSG_TYPE.member_types[names.MSG_SENDER] svitype = self.type_translator.translate(svytype, ctx) msg_sender = helpers.struct_get(self.viper_ast, msg, names.MSG_SENDER, svitype, types.MSG_TYPE) self_address = helpers.self_address(self.viper_ast) body.append(self.viper_ast.Inhale(self.viper_ast.EqCmp(msg_sender, self_address))) vvytype = types.MSG_TYPE.member_types[names.MSG_VALUE] vvitype = self.type_translator.translate(vvytype, ctx) msg_value = helpers.struct_get(self.viper_ast, msg, names.MSG_VALUE, vvitype, types.MSG_TYPE) body.append(self.viper_ast.Inhale(self.viper_ast.EqCmp(msg_value, amount))) # Add arguments to local vars, assign passed args for (name, var), arg in zip(function.args.items(), args): apos = arg.pos() arg_var = self._translate_var(var, ctx) ctx.locals[name] = arg_var lhs = arg_var.local_var(ctx) if (types.is_numeric(arg_var.type) and self.arithmetic_translator.is_wrapped(arg) and self.arithmetic_translator.is_unwrapped(lhs)): arg_var.is_local = False lhs = arg_var.local_var(ctx) elif (types.is_numeric(arg_var.type) and self.arithmetic_translator.is_unwrapped(arg) and self.arithmetic_translator.is_wrapped(lhs)): arg = helpers.w_wrap(self.viper_ast, arg) elif (not types.is_numeric(arg_var.type) and self.arithmetic_translator.is_wrapped(arg)): arg = helpers.w_unwrap(self.viper_ast, arg) ctx.new_local_vars.append(arg_var.var_decl(ctx)) body.append(self.viper_ast.LocalVarAssign(arg_var.local_var(ctx), arg, apos)) # Add result variable if function.type.return_type: ret_name = ctx.inline_prefix + mangled.RESULT_VAR ret_pos = return_value.pos() ctx.result_var = TranslatedVar(names.RESULT, ret_name, function.type.return_type, self.viper_ast, ret_pos, is_local=False) ctx.new_local_vars.append(ctx.result_var.var_decl(ctx, ret_pos)) if (types.is_numeric(function.type.return_type) and self.arithmetic_translator.is_unwrapped(return_value)): return_value = helpers.w_wrap(self.viper_ast, return_value) body.append(self.viper_ast.LocalVarAssign(ctx.result_var.local_var(ret_pos), return_value, ret_pos)) # Add success variable succ_name = ctx.inline_prefix + mangled.SUCCESS_VAR succ_var = TranslatedVar(names.SUCCESS, succ_name, types.VYPER_BOOL, self.viper_ast, succ.pos()) ctx.new_local_vars.append(succ_var.var_decl(ctx)) ctx.success_var = succ_var body.append(self.viper_ast.LocalVarAssign(succ_var.local_var(ctx), succ, succ.pos())) translate = self.spec_translator.translate_pre_or_postcondition pos = self.to_position(node, ctx, rules.INHALE_INTERFACE_FAIL) with ctx.program_scope(interface): with ctx.self_address_scope(to): postconditions = chain(function.postconditions, interface.general_postconditions) exprs = [translate(post, body, ctx) for post in postconditions] body.extend(self.viper_ast.Inhale(expr, pos) for expr in exprs) if ctx.program.config.has_option(names.CONFIG_TRUST_CASTS): res.extend(body) else: implements = helpers.implements(self.viper_ast, to, interface.name, ctx, pos) res.append(self.viper_ast.If(implements, body, [], pos)) def _translate_var(self, var: VyperVar, ctx: Context) -> TranslatedVar: pos = self.to_position(var.node, ctx) name = mangled.local_var_name(ctx.inline_prefix, var.name) return TranslatedVar(var.name, name, var.type, self.viper_ast, pos)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/expression.py
expression.py
from typing import List from twovyper.ast import names from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt from twovyper.translation.context import Context from twovyper.translation.abstract import CommonTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation import helpers from twovyper.translation import mangled class BalanceTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): self.viper_ast = viper_ast self.type_translator = TypeTranslator(viper_ast) def get_balance(self, self_var: Expr, ctx: Context, pos=None, info=None) -> Expr: balance_type = ctx.field_types[names.ADDRESS_BALANCE] return helpers.struct_get(self.viper_ast, self_var, names.ADDRESS_BALANCE, balance_type, ctx.self_type, pos, info) def set_balance(self, self_var: Expr, value: Expr, ctx: Context, pos=None, info=None) -> Expr: balance_type = ctx.field_types[names.ADDRESS_BALANCE] return helpers.struct_set(self.viper_ast, self_var, value, names.ADDRESS_BALANCE, balance_type, ctx.self_type, pos, info) def check_balance(self, amount: Expr, res: List[Stmt], ctx: Context, pos=None, info=None): self_var = ctx.self_var.local_var(ctx) get_balance = self.get_balance(self_var, ctx, pos) self.fail_if(self.viper_ast.LtCmp(get_balance, amount), [], res, ctx, pos, info) def increase_balance(self, amount: Expr, res: List[Stmt], ctx: Context, pos=None, info=None): self_var = ctx.self_var.local_var(ctx) get_balance = self.get_balance(self_var, ctx, pos) inc_sum = self.viper_ast.Add(get_balance, amount, pos) inc = self.set_balance(self_var, inc_sum, ctx, pos) res.append(self.viper_ast.LocalVarAssign(self_var, inc, pos, info)) def decrease_balance(self, amount: Expr, res: List[Stmt], ctx: Context, pos=None, info=None): self_var = ctx.self_var.local_var(ctx) get_balance = self.get_balance(self_var, ctx, pos) diff = self.viper_ast.Sub(get_balance, amount) sub = self.set_balance(self_var, diff, ctx, pos) res.append(self.viper_ast.LocalVarAssign(self_var, sub, pos, info)) def received(self, self_var: Expr, ctx: Context, pos=None, info=None) -> Expr: received_type = ctx.field_types[mangled.RECEIVED_FIELD] return helpers.struct_get(self.viper_ast, self_var, mangled.RECEIVED_FIELD, received_type, ctx.self_type, pos, info) def sent(self, self_var: Expr, ctx: Context, pos=None, info=None) -> Expr: sent_type = ctx.field_types[mangled.SENT_FIELD] return helpers.struct_get(self.viper_ast, self_var, mangled.SENT_FIELD, sent_type, ctx.self_type, pos, info) def get_received(self, self_var: Expr, address: Expr, ctx: Context, pos=None, info=None) -> Expr: received = self.received(self_var, ctx, pos) return helpers.map_get(self.viper_ast, received, address, self.viper_ast.Int, self.viper_ast.Int, pos) def get_sent(self, self_var: Expr, address: Expr, ctx: Context, pos=None, info=None) -> Expr: sent = self.sent(self_var, ctx, pos) return helpers.map_get(self.viper_ast, sent, address, self.viper_ast.Int, self.viper_ast.Int, pos) def increase_received(self, amount: Expr, res: List[Stmt], ctx: Context, pos=None, info=None): self_var = ctx.self_var.local_var(ctx) # TODO: pass this as an argument msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) rec_type = ctx.field_types[mangled.RECEIVED_FIELD] rec = helpers.struct_get(self.viper_ast, self_var, mangled.RECEIVED_FIELD, rec_type, ctx.self_type, pos) rec_sender = helpers.map_get(self.viper_ast, rec, msg_sender, self.viper_ast.Int, self.viper_ast.Int, pos) rec_inc_sum = self.viper_ast.Add(rec_sender, amount, pos) rec_set = helpers.map_set(self.viper_ast, rec, msg_sender, rec_inc_sum, self.viper_ast.Int, self.viper_ast.Int, pos) self_set = helpers.struct_set(self.viper_ast, self_var, rec_set, mangled.RECEIVED_FIELD, rec_type, ctx.self_type, pos) res.append(self.viper_ast.LocalVarAssign(self_var, self_set, pos, info)) def increase_sent(self, to: Expr, amount: Expr, res: List[Stmt], ctx: Context, pos=None, info=None): self_var = ctx.self_var.local_var(ctx) sent_type = ctx.field_types[mangled.SENT_FIELD] sent = helpers.struct_get(self.viper_ast, self_var, mangled.SENT_FIELD, sent_type, ctx.self_type, pos) sent_to = helpers.map_get(self.viper_ast, sent, to, self.viper_ast.Int, self.viper_ast.Int, pos) sent_inc = self.viper_ast.Add(sent_to, amount, pos) sent_set = helpers.map_set(self.viper_ast, sent, to, sent_inc, self.viper_ast.Int, self.viper_ast.Int, pos) self_set = helpers.struct_set(self.viper_ast, self_var, sent_set, mangled.SENT_FIELD, sent_type, ctx.self_type, pos) res.append(self.viper_ast.LocalVarAssign(self_var, self_set, pos, info))
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/balance.py
balance.py
from typing import Union from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.types import FunctionType, MapType, StructType, AnyStructType, ResourceType from twovyper.ast.nodes import VyperFunction, Resource from twovyper.analysis.analyzer import FunctionAnalysis from twovyper.viper.ast import ViperAST from twovyper.translation import mangled from twovyper.translation.context import Context from twovyper.translation.wrapped_viper_ast import WrappedViperAST, wrapped_integer_decorator from twovyper.utils import first_index from twovyper.viper.typedefs import Expr # Helper functions def init_function() -> VyperFunction: type = FunctionType([], None) function = VyperFunction(mangled.INIT, -1, {}, {}, type, [], [], [], {}, [], [ast.Decorator(names.PUBLIC, [])], None) function.analysis = FunctionAnalysis() return function def msg_var(viper_ast: ViperAST, pos=None, info=None): return viper_ast.LocalVarDecl(mangled.MSG, viper_ast.Ref, pos, info) def msg_sender(viper_ast: ViperAST, ctx: Context, pos=None, info=None): msg_var = ctx.msg_var.local_var(ctx) type = types.MSG_TYPE return struct_get(viper_ast, msg_var, names.MSG_SENDER, viper_ast.Int, type, pos, info) def msg_value(viper_ast: ViperAST, ctx: Context, pos=None, info=None): msg_var = ctx.msg_var.local_var(ctx) type = types.MSG_TYPE return struct_get(viper_ast, msg_var, names.MSG_VALUE, viper_ast.Int, type, pos, info) def overflow_var(viper_ast: ViperAST, pos=None, info=None): return viper_ast.LocalVarDecl(mangled.OVERFLOW, viper_ast.Bool, pos, info) def out_of_gas_var(viper_ast: ViperAST, pos=None, info=None): return viper_ast.LocalVarDecl(mangled.OUT_OF_GAS, viper_ast.Bool, pos, info) def call_failed(viper_ast: ViperAST, address, pos=None, info=None): write = viper_ast.FullPerm(pos) predicate = viper_ast.PredicateAccess([address], mangled.FAILED, pos) predicate_acc = viper_ast.PredicateAccessPredicate(predicate, write, pos) return viper_ast.Inhale(predicate_acc, pos, info) def check_call_failed(viper_ast: ViperAST, address, pos=None, info=None): none = viper_ast.NoPerm(pos) predicate = viper_ast.PredicateAccess([address], mangled.FAILED, pos) return viper_ast.GtCmp(viper_ast.CurrentPerm(predicate, pos), none, pos, info) def first_public_state_var(viper_ast: ViperAST, pos=None, info=None): return viper_ast.LocalVarDecl(mangled.FIRST_PUBLIC_STATE, viper_ast.Bool, pos, info) def contracts_type(): return MapType(types.VYPER_ADDRESS, AnyStructType()) def allocated_type(): return MapType(AnyStructType(), MapType(types.VYPER_ADDRESS, types.NON_NEGATIVE_INT)) def offer_type(): members = { '0': types.VYPER_WEI_VALUE, '1': types.VYPER_WEI_VALUE, '2': types.VYPER_ADDRESS, '3': types.VYPER_ADDRESS } return StructType(mangled.OFFER, members) def offered_type(): return MapType(AnyStructType(), MapType(AnyStructType(), MapType(offer_type(), types.NON_NEGATIVE_INT))) def trusted_type(): return MapType(types.VYPER_ADDRESS, MapType(types.VYPER_ADDRESS, MapType(types.VYPER_ADDRESS, types.VYPER_BOOL))) def allocation_predicate(viper_ast: ViperAST, resource, address, pos=None): return viper_ast.PredicateAccess([resource, address], mangled.ALLOCATION, pos) def offer(viper_ast: ViperAST, from_val, to_val, from_addr, to_addr, pos=None): return struct_init(viper_ast, [from_val, to_val, from_addr, to_addr], offer_type(), pos) def offer_predicate(viper_ast: ViperAST, from_resource, to_resource, from_val, to_val, from_addr, to_addr, pos=None): return viper_ast.PredicateAccess([from_resource, to_resource, from_val, to_val, from_addr, to_addr], mangled.OFFER, pos) def no_offers(viper_ast: ViperAST, offered, resource, address, pos=None): return viper_ast.FuncApp(mangled.NO_OFFERS, [offered, resource, address], pos, type=viper_ast.Bool) def trust_predicate(viper_ast: ViperAST, where, address, by_address, pos=None): return viper_ast.PredicateAccess([where, address, by_address], mangled.TRUST, pos) def trust_no_one(viper_ast: ViperAST, trusted, who, where, pos=None): return viper_ast.FuncApp(mangled.TRUST_NO_ONE, [trusted, who, where], pos, type=viper_ast.Bool) def performs_predicate(viper_ast: ViperAST, function: str, args, pos=None): name = mangled.performs_predicate_name(function) return viper_ast.PredicateAccess(args, name, pos) def creator_resource() -> Resource: creator_name = mangled.CREATOR creator_type = ResourceType(creator_name, {mangled.CREATOR_RESOURCE: AnyStructType()}) return Resource(creator_type, None, None) def blockhash(viper_ast: ViperAST, no, ctx: Context, pos=None, info=None): bhash = mangled.BLOCKCHAIN_BLOCKHASH domain = mangled.BLOCKCHAIN_DOMAIN return viper_ast.DomainFuncApp(bhash, [no], viper_ast.SeqType(viper_ast.Int), pos, info, domain) def method_id(viper_ast: ViperAST, method, len: int, pos=None, info=None): mid = mangled.BLOCKCHAIN_METHOD_ID domain = mangled.BLOCKCHAIN_DOMAIN rl = viper_ast.IntLit(len, pos) return viper_ast.DomainFuncApp(mid, [method, rl], viper_ast.SeqType(viper_ast.Int), pos, info, domain) def keccak256(viper_ast: ViperAST, arg, pos=None, info=None): int_array_type = viper_ast.SeqType(viper_ast.Int) keccak = mangled.BLOCKCHAIN_KECCAK256 domain = mangled.BLOCKCHAIN_DOMAIN return viper_ast.DomainFuncApp(keccak, [arg], int_array_type, pos, info, domain) def sha256(viper_ast: ViperAST, arg, pos=None, info=None): int_array_type = viper_ast.SeqType(viper_ast.Int) sha = mangled.BLOCKCHAIN_SHA256 domain = mangled.BLOCKCHAIN_DOMAIN return viper_ast.DomainFuncApp(sha, [arg], int_array_type, pos, info, domain) def ecrecover(viper_ast: ViperAST, args, pos=None, info=None): ec = mangled.BLOCKCHAIN_ECRECOVER domain = mangled.BLOCKCHAIN_DOMAIN return viper_ast.DomainFuncApp(ec, args, viper_ast.Int, pos, info, domain) def ecadd(viper_ast: ViperAST, args, pos=None, info=None): int_array_type = viper_ast.SeqType(viper_ast.Int) ea = mangled.BLOCKCHAIN_ECADD domain = mangled.BLOCKCHAIN_DOMAIN return viper_ast.DomainFuncApp(ea, args, int_array_type, pos, info, domain) def ecmul(viper_ast: ViperAST, args, pos=None, info=None): int_array_type = viper_ast.SeqType(viper_ast.Int) em = mangled.BLOCKCHAIN_ECMUL domain = mangled.BLOCKCHAIN_DOMAIN return viper_ast.DomainFuncApp(em, args, int_array_type, pos, info, domain) def self_address(viper_ast: ViperAST, pos=None, info=None): address = mangled.SELF_ADDRESS domain = mangled.CONTRACT_DOMAIN return viper_ast.DomainFuncApp(address, [], viper_ast.Int, pos, info, domain) def implements(viper_ast: ViperAST, address, interface: str, ctx: Context, pos=None, info=None): impl = mangled.IMPLEMENTS domain = mangled.CONTRACT_DOMAIN intf = viper_ast.IntLit(first_index(lambda i: i == interface, ctx.program.interfaces), pos) return viper_ast.DomainFuncApp(impl, [address, intf], viper_ast.Bool, pos, info, domain) def wrapped_int_type(viper_ast: ViperAST): return viper_ast.DomainType(mangled.WRAPPED_INT_DOMAIN, {}, []) def w_mul(viper_ast: ViperAST, first, second, pos=None, info=None): if isinstance(viper_ast, WrappedViperAST): viper_ast = viper_ast.viper_ast wi_mul = mangled.WRAPPED_INT_MUL domain = mangled.WRAPPED_INT_DOMAIN args = [first, second] return viper_ast.DomainFuncApp(wi_mul, args, wrapped_int_type(viper_ast), pos, info, domain) def w_div(viper_ast: ViperAST, first, second, pos=None, info=None): if isinstance(viper_ast, WrappedViperAST): viper_ast = viper_ast.viper_ast wi_div = mangled.WRAPPED_INT_DIV domain = mangled.WRAPPED_INT_DOMAIN args = [first, second] func_app = viper_ast.DomainFuncApp(wi_div, args, wrapped_int_type(viper_ast), pos, info, domain) is_div_zero = viper_ast.EqCmp(viper_ast.IntLit(0), w_unwrap(viper_ast, second, pos, info), pos, info) artificial_div_zero = w_wrap(viper_ast, viper_ast.Div(w_unwrap(viper_ast, first, pos, info), w_unwrap(viper_ast, second, pos, info), pos, info), pos, info) return viper_ast.CondExp(is_div_zero, artificial_div_zero, func_app, pos, info) def w_mod(viper_ast: ViperAST, first, second, pos=None, info=None): if isinstance(viper_ast, WrappedViperAST): viper_ast = viper_ast.viper_ast wi_mod = mangled.WRAPPED_INT_MOD domain = mangled.WRAPPED_INT_DOMAIN args = [first, second] func_app = viper_ast.DomainFuncApp(wi_mod, args, wrapped_int_type(viper_ast), pos, info, domain) is_div_zero = viper_ast.EqCmp(viper_ast.IntLit(0), w_unwrap(viper_ast, second, pos, info), pos, info) artificial_div_zero = w_wrap(viper_ast, viper_ast.Mod(w_unwrap(viper_ast, first, pos, info), w_unwrap(viper_ast, second, pos, info), pos, info), pos, info) return viper_ast.CondExp(is_div_zero, artificial_div_zero, func_app, pos, info) def w_wrap(viper_ast: ViperAST, value, pos=None, info=None): if isinstance(viper_ast, WrappedViperAST): viper_ast = viper_ast.viper_ast wi_wrap = mangled.WRAPPED_INT_WRAP domain = mangled.WRAPPED_INT_DOMAIN return viper_ast.DomainFuncApp(wi_wrap, [value], wrapped_int_type(viper_ast), pos, info, domain) def w_unwrap(viper_ast: ViperAST, value, pos=None, info=None): if isinstance(viper_ast, WrappedViperAST): viper_ast = viper_ast.viper_ast wi_unwrap = mangled.WRAPPED_INT_UNWRAP domain = mangled.WRAPPED_INT_DOMAIN return viper_ast.DomainFuncApp(wi_unwrap, [value], viper_ast.Int, pos, info, domain) def div(viper_ast: ViperAST, dividend, divisor, pos=None, info=None): # We need a special division function because Vyper uses truncating division # instead of Viper's floor division mdiv = mangled.MATH_DIV domain = mangled.MATH_DOMAIN # We pass the Viper floor division as a third argument to trigger a correct # division by 0 error instead of an assertion failure if divisor == 0 args = [dividend, divisor, viper_ast.Div(dividend, divisor, pos)] return viper_ast.DomainFuncApp(mdiv, args, viper_ast.Int, pos, info, domain) def mod(viper_ast: ViperAST, dividend, divisor, pos=None, info=None): # We need a special mod function because Vyper uses truncating division # instead of Viper's floor division mmod = mangled.MATH_MOD domain = mangled.MATH_DOMAIN # We pass the Viper floor division as a third argument to trigger a correct # division by 0 error instead of an assertion failure if divisor == 0 args = [dividend, divisor, viper_ast.Mod(dividend, divisor, pos)] return viper_ast.DomainFuncApp(mmod, args, viper_ast.Int, pos, info, domain) def pow(viper_ast: ViperAST, base, exp, pos=None, info=None): mpow = mangled.MATH_POW domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(mpow, [base, exp], viper_ast.Int, pos, info, domain) def sqrt(viper_ast: ViperAST, dec, pos=None, info=None): msqrt = mangled.MATH_SQRT domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(msqrt, [dec], viper_ast.Int, pos, info, domain) def floor(viper_ast: ViperAST, dec, scaling_factor: int, pos=None, info=None): mfloor = mangled.MATH_FLOOR domain = mangled.MATH_DOMAIN scaling_factor_lit = viper_ast.IntLit(scaling_factor, pos) args = [dec, scaling_factor_lit] return viper_ast.DomainFuncApp(mfloor, args, viper_ast.Int, pos, info, domain) def ceil(viper_ast: ViperAST, dec, scaling_factor: int, pos=None, info=None): mceil = mangled.MATH_CEIL domain = mangled.MATH_DOMAIN scaling_factor_lit = viper_ast.IntLit(scaling_factor, pos) args = [dec, scaling_factor_lit] return viper_ast.DomainFuncApp(mceil, args, viper_ast.Int, pos, info, domain) def shift(viper_ast: ViperAST, arg, shift, pos=None, info=None): b_shift = mangled.MATH_SHIFT domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(b_shift, [arg, shift], viper_ast.Int, pos, info, domain) def bitwise_not(viper_ast: ViperAST, arg, pos=None, info=None): b_not = mangled.MATH_BITWISE_NOT domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(b_not, [arg], viper_ast.Int, pos, info, domain) def bitwise_and(viper_ast: ViperAST, a, b, pos=None, info=None): b_and = mangled.MATH_BITWISE_AND domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(b_and, [a, b], viper_ast.Int, pos, info, domain) def bitwise_or(viper_ast: ViperAST, a, b, pos=None, info=None): b_or = mangled.MATH_BITWISE_OR domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(b_or, [a, b], viper_ast.Int, pos, info, domain) def bitwise_xor(viper_ast: ViperAST, a, b, pos=None, info=None): b_xor = mangled.MATH_BITWISE_XOR domain = mangled.MATH_DOMAIN return viper_ast.DomainFuncApp(b_xor, [a, b], viper_ast.Int, pos, info, domain) def array_type(viper_ast: ViperAST, element_type): return viper_ast.SeqType(element_type) def empty_array(viper_ast: ViperAST, element_type, pos=None, info=None): return viper_ast.EmptySeq(element_type, pos, info) def array_init(viper_ast: ViperAST, arg, size: int, element_type, pos=None, info=None): arr_type = array_type(viper_ast, element_type) type_vars = {viper_ast.TypeVar(mangled.ARRAY_ELEMENT_VAR): element_type} size = viper_ast.IntLit(size, pos, info) init = mangled.ARRAY_INIT domain = mangled.ARRAY_DOMAIN return viper_ast.DomainFuncApp(init, [arg, size], arr_type, pos, info, domain, type_vars) def array_length(viper_ast: ViperAST, ref, pos=None, info=None): return viper_ast.SeqLength(ref, pos, info) @wrapped_integer_decorator(wrap_output=True) def array_get(viper_ast: ViperAST, ref, idx, element_type, pos=None, info=None): return viper_ast.SeqIndex(ref, idx, pos, info) def array_set(viper_ast: ViperAST, ref, idx, value, element_type, pos=None, info=None): return viper_ast.SeqUpdate(ref, idx, value, pos, info) def array_contains(viper_ast: ViperAST, value, ref, pos=None, info=None): return viper_ast.SeqContains(value, ref, pos, info) def array_not_contains(viper_ast: ViperAST, value, ref, pos=None, info=None): return viper_ast.Not(array_contains(viper_ast, value, ref, pos, info), pos, info) def _map_type_var_map(viper_ast: ViperAST, key_type, value_type): key = viper_ast.TypeVar(mangled.MAP_KEY_VAR) value = viper_ast.TypeVar(mangled.MAP_VALUE_VAR) return {key: key_type, value: value_type} def map_type(viper_ast: ViperAST, key_type, value_type): type_vars = _map_type_var_map(viper_ast, key_type, value_type) return viper_ast.DomainType(mangled.MAP_DOMAIN, type_vars, type_vars.keys()) def map_init(viper_ast: ViperAST, arg, key_type, value_type, pos=None, info=None): mp_type = map_type(viper_ast, key_type, value_type) type_vars = _map_type_var_map(viper_ast, key_type, value_type) init = mangled.MAP_INIT domain = mangled.MAP_DOMAIN return viper_ast.DomainFuncApp(init, [arg], mp_type, pos, info, domain, type_vars) def map_eq(viper_ast: ViperAST, left, right, key_type, value_type, pos=None, info=None): type_vars = _map_type_var_map(viper_ast, key_type, value_type) eq = mangled.MAP_EQ domain = mangled.MAP_DOMAIN return viper_ast.DomainFuncApp(eq, [left, right], viper_ast.Bool, pos, info, domain, type_vars) @wrapped_integer_decorator(wrap_output=True) def map_get(viper_ast: ViperAST, ref, idx, key_type, value_type, pos=None, info=None): type_vars = _map_type_var_map(viper_ast, key_type, value_type) get = mangled.MAP_GET domain = mangled.MAP_DOMAIN return viper_ast.DomainFuncApp(get, [ref, idx], value_type, pos, info, domain, type_vars) def map_set(viper_ast: ViperAST, ref, idx, value, key_type, value_type, pos=None, info=None): type_vars = _map_type_var_map(viper_ast, key_type, value_type) mtype = map_type(viper_ast, key_type, value_type) mset = mangled.MAP_SET domain = mangled.MAP_DOMAIN return viper_ast.DomainFuncApp(mset, [ref, idx, value], mtype, pos, info, domain, type_vars) def map_sum(viper_ast: ViperAST, ref, key_type, pos=None, info=None): type_vars = {viper_ast.TypeVar(mangled.MAP_KEY_VAR): key_type} type = viper_ast.Int msum = mangled.MAP_SUM domain = mangled.MAP_INT_DOMAIN return viper_ast.DomainFuncApp(msum, [ref], type, pos, info, domain, type_vars) def struct_type(viper_ast: ViperAST): return viper_ast.DomainType(mangled.STRUCT_DOMAIN, {}, []) def struct_loc(viper_ast: ViperAST, ref, idx, pos=None, info=None): domain = mangled.STRUCT_DOMAIN loc = mangled.STRUCT_LOC return viper_ast.DomainFuncApp(loc, [ref, idx], viper_ast.Int, pos, info, domain) def struct_init(viper_ast: ViperAST, args, struct: StructType, pos=None, info=None): domain = mangled.struct_name(struct.name, struct.kind) init_name = mangled.struct_init_name(struct.name, struct.kind) type = struct_type(viper_ast) return viper_ast.DomainFuncApp(init_name, args, type, pos, info, domain) def struct_eq(viper_ast: ViperAST, left, right, struct: StructType, pos=None, info=None): domain = mangled.struct_name(struct.name, struct.kind) eq = mangled.struct_eq_name(struct.name, struct.kind) return viper_ast.DomainFuncApp(eq, [left, right], viper_ast.Bool, pos, info, domain) def struct_type_tag(viper_ast: ViperAST, ref, pos=None, info=None): """ Returns the type tag of a struct which we store at index -1 of a struct """ domain = mangled.STRUCT_OPS_DOMAIN idx = viper_ast.IntLit(mangled.STRUCT_TYPE_LOC) field = struct_loc(viper_ast, ref, idx, pos) getter = mangled.STRUCT_GET type_type = viper_ast.Int type_map = _struct_type_var_map(viper_ast, type_type) return viper_ast.DomainFuncApp(getter, [field], type_type, pos, info, domain, type_map) def _struct_type_var_map(viper_ast: ViperAST, member_type): member = viper_ast.TypeVar(mangled.STRUCT_OPS_VALUE_VAR) return {member: member_type} @wrapped_integer_decorator(wrap_output=True) def struct_get(viper_ast: ViperAST, ref, member: str, member_type, struct_type: StructType, pos=None, info=None): domain = mangled.STRUCT_OPS_DOMAIN idx = viper_ast.IntLit(struct_type.member_indices[member]) field = struct_loc(viper_ast, ref, idx, pos, info) getter = mangled.STRUCT_GET type_map = _struct_type_var_map(viper_ast, member_type) return viper_ast.DomainFuncApp(getter, [field], member_type, pos, info, domain, type_map) def struct_pure_get_success(viper_ast: ViperAST, ref, pos=None): return struct_get_idx(viper_ast, ref, 0, viper_ast.Bool, pos) def struct_pure_get_result(viper_ast: ViperAST, ref, viper_type, pos=None): return struct_get_idx(viper_ast, ref, 1, viper_type, pos) def struct_get_idx(viper_ast: ViperAST, ref, idx: Union[int, Expr], viper_type, pos=None, info=None): domain = mangled.STRUCT_OPS_DOMAIN idx_lit = viper_ast.IntLit(idx) if isinstance(idx, int) else idx field = struct_loc(viper_ast, ref, idx_lit, pos, info) getter = mangled.STRUCT_GET type_map = _struct_type_var_map(viper_ast, viper_type) return viper_ast.DomainFuncApp(getter, [field], viper_type, pos, info, domain, type_map) def struct_set(viper_ast: ViperAST, ref, val, member: str, member_type, type: StructType, pos=None, info=None): setter = mangled.STRUCT_SET s_type = struct_type(viper_ast) domain = mangled.STRUCT_OPS_DOMAIN idx = viper_ast.IntLit(type.member_indices[member]) type_map = _struct_type_var_map(viper_ast, member_type) return viper_ast.DomainFuncApp(setter, [ref, idx, val], s_type, pos, info, domain, type_map) def struct_set_idx(viper_ast: ViperAST, ref, val, idx: int, member_type, pos=None, info=None): setter = mangled.STRUCT_SET s_type = struct_type(viper_ast) domain = mangled.STRUCT_OPS_DOMAIN idx = viper_ast.IntLit(idx) type_map = _struct_type_var_map(viper_ast, member_type) return viper_ast.DomainFuncApp(setter, [ref, idx, val], s_type, pos, info, domain, type_map) def get_lock(viper_ast: ViperAST, name: str, ctx: Context, pos=None, info=None): lock_name = mangled.lock_name(name) self_var = ctx.self_var.local_var(ctx) return struct_get(viper_ast, self_var, lock_name, viper_ast.Bool, ctx.self_type, pos, info) def set_lock(viper_ast: ViperAST, name: str, val: bool, ctx: Context, pos=None, info=None): lock_name = mangled.lock_name(name) value = viper_ast.TrueLit(pos) if val else viper_ast.FalseLit(pos) self_var = ctx.self_var.local_var(ctx) return struct_set(viper_ast, self_var, value, lock_name, viper_ast.Bool, ctx.self_type, pos, info) @wrapped_integer_decorator(wrap_output=True) def convert_bytes32_to_signed_int(viper_ast: ViperAST, bytes, pos=None, info=None): domain = mangled.CONVERT_DOMAIN function = mangled.CONVERT_BYTES32_TO_SIGNED_INT return viper_ast.DomainFuncApp(function, [bytes], viper_ast.Int, pos, info, domain) @wrapped_integer_decorator(wrap_output=True) def convert_bytes32_to_unsigned_int(viper_ast: ViperAST, bytes, pos=None, info=None): domain = mangled.CONVERT_DOMAIN function = mangled.CONVERT_BYTES32_TO_UNSIGNED_INT return viper_ast.DomainFuncApp(function, [bytes], viper_ast.Int, pos, info, domain) def convert_signed_int_to_bytes32(viper_ast: ViperAST, i, pos=None, info=None): domain = mangled.CONVERT_DOMAIN function = mangled.CONVERT_SIGNED_INT_TO_BYTES32 return viper_ast.DomainFuncApp(function, [i], viper_ast.SeqType(viper_ast.Int), pos, info, domain) def convert_unsigned_int_to_bytes32(viper_ast: ViperAST, i, pos=None, info=None): domain = mangled.CONVERT_DOMAIN function = mangled.CONVERT_UNSIGNED_INT_TO_BYTES32 return viper_ast.DomainFuncApp(function, [i], viper_ast.SeqType(viper_ast.Int), pos, info, domain) def pad32(viper_ast: ViperAST, bytes, pos=None, info=None): """ Left-pads a byte array shorter than 32 bytes with 0s so that its resulting length is 32. Left-crops a byte array longer than 32 bytes so that its resulting length is 32. """ domain = mangled.CONVERT_DOMAIN function = mangled.CONVERT_PAD32 return viper_ast.DomainFuncApp(function, [bytes], viper_ast.SeqType(viper_ast.Int), pos, info, domain) def range(viper_ast: ViperAST, start, end, pos=None, info=None): range_func = mangled.RANGE_RANGE range_type = viper_ast.SeqType(viper_ast.Int) domain = mangled.RANGE_DOMAIN return viper_ast.DomainFuncApp(range_func, [start, end], range_type, pos, info, domain) def ghost_function(viper_ast: ViperAST, function, address, struct, args, return_type, pos=None, info=None): ghost_func = mangled.ghost_function_name(function.interface, function.name) return viper_ast.FuncApp(ghost_func, [address, struct, *args], pos, info, return_type) def havoc_var(viper_ast: ViperAST, viper_type, ctx: Context): if ctx.is_pure_function: pure_idx = ctx.next_pure_var_index() function_result = viper_ast.Result(struct_type(viper_ast)) return struct_get_idx(viper_ast, function_result, pure_idx, viper_type) else: havoc_name = ctx.new_local_var_name('havoc') havoc = viper_ast.LocalVarDecl(havoc_name, viper_type) ctx.new_local_vars.append(havoc) return havoc.localVar() def flattened_conditional(viper_ast: ViperAST, cond, thn, els, pos=None): res = [] if_class = viper_ast.ast.If seqn_class = viper_ast.ast.Seqn assign_class = viper_ast.ast.LocalVarAssign assume_or_check_stmts = [viper_ast.ast.Inhale, viper_ast.ast.Assert, viper_ast.ast.Exhale] supported_classes = [*assume_or_check_stmts, if_class, seqn_class, assign_class] if all(stmt.__class__ in supported_classes for stmt in thn + els): not_cond = viper_ast.Not(cond, pos) thn = [(stmt, cond) for stmt in thn] els = [(stmt, not_cond) for stmt in els] for stmt, cond in thn + els: stmt_class = stmt.__class__ if stmt_class in assume_or_check_stmts: implies = viper_ast.Implies(cond, stmt.exp(), stmt.pos()) res.append(stmt_class(implies, stmt.pos(), stmt.info(), stmt.errT())) elif stmt_class == assign_class: cond_expr = viper_ast.CondExp(cond, stmt.rhs(), stmt.lhs(), stmt.pos()) res.append(viper_ast.LocalVarAssign(stmt.lhs(), cond_expr, stmt.pos())) elif stmt_class == if_class: new_cond = viper_ast.And(stmt.cond(), cond, stmt.pos()) stmts = viper_ast.to_list(stmt.thn().ss()) res.extend(flattened_conditional(viper_ast, new_cond, stmts, [], stmt.pos())) new_cond = viper_ast.And(viper_ast.Not(stmt.cond(), stmt.pos()), cond, stmt.pos()) stmts = viper_ast.to_list(stmt.els().ss()) res.extend(flattened_conditional(viper_ast, new_cond, stmts, [], stmt.pos())) elif stmt_class == seqn_class: seqn_as_list = viper_ast.to_list(stmt.ss()) transformed_stmts = flattened_conditional(viper_ast, cond, seqn_as_list, [], stmt.pos()) res.append(viper_ast.Seqn(transformed_stmts, stmt.pos(), stmt.info())) else: assert False else: res.append(viper_ast.If(cond, thn, [], pos)) return res
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/helpers.py
helpers.py
from typing import Callable, List from twovyper.ast import names from twovyper.translation import helpers, mangled, State from twovyper.translation.abstract import CommonTranslator from twovyper.translation.context import Context from twovyper.translation.variable import TranslatedVar from twovyper.translation.type import TypeTranslator from twovyper.verification import rules from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Stmt class StateTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.type_translator = TypeTranslator(self.viper_ast) @property def expression_translator(self): from twovyper.translation.specification import ExpressionTranslator return ExpressionTranslator(self.viper_ast) def state(self, name_transformation: Callable[[str], str], ctx: Context): def self_var(name): return TranslatedVar(names.SELF, name, ctx.self_type, self.viper_ast) def contract_var(name): contracts_type = helpers.contracts_type() return TranslatedVar(mangled.CONTRACTS, name, contracts_type, self.viper_ast) def allocated_var(name): allocated_type = helpers.allocated_type() return TranslatedVar(mangled.ALLOCATED, name, allocated_type, self.viper_ast) def offered_var(name): offered_type = helpers.offered_type() return TranslatedVar(mangled.OFFERED, name, offered_type, self.viper_ast) def trusted_var(name): trusted_type = helpers.trusted_type() return TranslatedVar(mangled.TRUSTED, name, trusted_type, self.viper_ast) s = { names.SELF: self_var(name_transformation(mangled.SELF)), mangled.CONTRACTS: contract_var(name_transformation(mangled.CONTRACTS)) } if ctx.program.config.has_option(names.CONFIG_ALLOCATION): s[mangled.ALLOCATED] = allocated_var(name_transformation(mangled.ALLOCATED)) s[mangled.OFFERED] = offered_var(name_transformation(mangled.OFFERED)) s[mangled.TRUSTED] = trusted_var(name_transformation(mangled.TRUSTED)) return s @staticmethod def _is_self(state_var: str) -> bool: return state_var == mangled.SELF @staticmethod def _is_non_contracts(state_var: str) -> bool: return state_var != mangled.CONTRACTS @staticmethod def is_allocation(state_var: str) -> bool: return (state_var == mangled.ALLOCATED or state_var == mangled.TRUSTED or state_var == mangled.OFFERED) def initialize_state(self, state: State, res: List[Stmt], ctx: Context): """ Initializes the state belonging to the current contract, namely self and allocated, to its default value. """ for var in state.values(): if self._is_non_contracts(var.name): default = self.type_translator.default_value(None, var.type, res, ctx) assign = self.viper_ast.LocalVarAssign(var.local_var(ctx), default) res.append(assign) def copy_state(self, from_state: State, to_state: State, res: List[Stmt], ctx: Context, pos=None, unless=None): copies = [] for name in set(from_state) & set(to_state): if unless and unless(name): continue to_var = to_state[name].local_var(ctx) from_var = from_state[name].local_var(ctx) copies.append(self.viper_ast.LocalVarAssign(to_var, from_var, pos)) self.seqn_with_info(copies, "Copy state", res) def assume_type_assumptions_for_state(self, state_dict: State, name: str, res, ctx): stmts = [] for state_var in state_dict.values(): type_assumptions = self.type_translator.type_assumptions(state_var.local_var(ctx), state_var.type, ctx) stmts.extend(self.viper_ast.Inhale(type_assumption) for type_assumption in type_assumptions) return self.seqn_with_info(stmts, f"{name} state assumptions", res) def havoc_state_except_self(self, state: State, res: List[Stmt], ctx: Context, pos=None): """ Havocs all contract state except self and self-allocated. """ with ctx.inline_scope(None): def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) old_state_for_performs = self.state(inlined_pre_state, ctx) for val in old_state_for_performs.values(): ctx.new_local_vars.append(val.var_decl(ctx, pos)) self.copy_state(ctx.current_state, old_state_for_performs, res, ctx, unless=lambda n: not self.is_allocation(n)) self.copy_state(ctx.current_old_state, old_state_for_performs, res, ctx, unless=self.is_allocation) self.havoc_state(state, res, ctx, pos, unless=self._is_self) with ctx.state_scope(ctx.current_state, old_state_for_performs): self.expression_translator.assume_own_resources_stayed_constant(res, ctx, pos) def havoc_state(self, state: State, res: List[Stmt], ctx: Context, pos=None, unless=None): havocs = [] for var in state.values(): if unless and unless(var.name): continue havoc_name = ctx.new_local_var_name('havoc') havoc_var = self.viper_ast.LocalVarDecl(havoc_name, var.var_decl(ctx).typ(), pos) ctx.new_local_vars.append(havoc_var) havocs.append(self.viper_ast.LocalVarAssign(var.local_var(ctx), havoc_var.localVar(), pos)) self.seqn_with_info(havocs, "Havoc state", res) def havoc_old_and_current_state(self, specification_translator, res, ctx, pos=None): # Havoc states self.havoc_state(ctx.current_state, res, ctx, pos) self.havoc_state(ctx.current_old_state, res, ctx, pos) self.assume_type_assumptions_for_state(ctx.current_state, "Present", res, ctx) self.assume_type_assumptions_for_state(ctx.current_old_state, "Old", res, ctx) assume_invs = [] # Assume Invariants for old state with ctx.state_scope(ctx.current_old_state, ctx.current_old_state): for inv in ctx.unchecked_invariants(): assume_invs.append(self.viper_ast.Inhale(inv)) # Assume implemented interface invariants for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.invariants: cond = specification_translator.translate_invariant(inv, assume_invs, ctx, True) inv_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) assume_invs.append(self.viper_ast.Inhale(cond, inv_pos)) # Assume own invariants for inv in ctx.current_program.invariants: cond = specification_translator.translate_invariant(inv, assume_invs, ctx, True) inv_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) assume_invs.append(self.viper_ast.Inhale(cond, inv_pos)) # Assume Invariants for current state with ctx.state_scope(ctx.current_state, ctx.current_state): for inv in ctx.unchecked_invariants(): assume_invs.append(self.viper_ast.Inhale(inv)) self.seqn_with_info(assume_invs, "Assume invariants", res) def check_first_public_state(self, res: List[Stmt], ctx: Context, set_false: bool, pos=None, info=None): stmts = [] for name in ctx.current_state: if self._is_non_contracts(name): current_var = ctx.current_state[name].local_var(ctx) old_var = ctx.current_old_state[name].local_var(ctx) assign = self.viper_ast.LocalVarAssign(old_var, current_var) stmts.append(assign) first_public_state = helpers.first_public_state_var(self.viper_ast, pos).localVar() if set_false: false = self.viper_ast.FalseLit(pos) var_assign = self.viper_ast.LocalVarAssign(first_public_state, false, pos) stmts.append(var_assign) res.extend(helpers.flattened_conditional(self.viper_ast, first_public_state, stmts, [], pos))
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/state.py
state.py
from functools import reduce from itertools import chain from typing import List, Optional from twovyper import resources from twovyper.translation.lemma import LemmaTranslator from twovyper.utils import flatten, seq_to_list from twovyper.ast import names, types, ast_nodes as ast from twovyper.ast.nodes import VyperProgram, VyperEvent, VyperStruct, VyperFunction, GhostFunction, Resource from twovyper.ast.types import AnyStructType from twovyper.exceptions import ConsistencyException from twovyper.translation import helpers, mangled, State from twovyper.translation.context import Context from twovyper.translation.abstract import CommonTranslator from twovyper.translation.allocation import AllocationTranslator from twovyper.translation.balance import BalanceTranslator from twovyper.translation.function import FunctionTranslator from twovyper.translation.pure_function import PureFunctionTranslator from twovyper.translation.resource import ResourceTranslator from twovyper.translation.specification import SpecificationTranslator from twovyper.translation.state import StateTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedVar from twovyper.translation.wrapped_viper_ast import WrappedViperAST from twovyper.verification import rules from twovyper.viper import sif from twovyper.viper.ast import ViperAST from twovyper.viper.jvmaccess import JVM from twovyper.viper.parser import ViperParser from twovyper.viper.typedefs import Program, Stmt class TranslationOptions: def __init__(self, create_model: bool, check_ast_inconsistencies: bool): self.create_model = create_model self.check_ast_inconsistencies = check_ast_inconsistencies builtins: Optional[Program] = None def translate(vyper_program: VyperProgram, options: TranslationOptions, jvm: JVM) -> Program: viper_ast = ViperAST(jvm) if not viper_ast.is_available(): raise Exception('Viper not found on classpath.') if not viper_ast.is_extension_available(): raise Exception('Viper AST SIF extension not found on classpath.') if vyper_program.is_interface(): return viper_ast.Program([], [], [], [], []) global builtins if builtins is None: viper_parser = ViperParser(jvm) builtins = viper_parser.parse(*resources.viper_all()) translator = ProgramTranslator(viper_ast, builtins) viper_program = translator.translate(vyper_program, options) if options.check_ast_inconsistencies: consistency_errors = seq_to_list(viper_program.checkTransitively()) if consistency_errors: raise ConsistencyException(viper_program, "The AST contains inconsistencies.", consistency_errors) sif.configure_mpp_transformation(jvm) viper_program = sif.transform(jvm, viper_program) return viper_program class ProgramTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST, twovyper_builtins: Program): viper_ast = WrappedViperAST(viper_ast) super().__init__(viper_ast) self.builtins = twovyper_builtins self.allocation_translator = AllocationTranslator(viper_ast) self.function_translator = FunctionTranslator(viper_ast) self.pure_function_translator = PureFunctionTranslator(viper_ast) self.lemma_translator = LemmaTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) self.resource_translator = ResourceTranslator(viper_ast) self.specification_translator = SpecificationTranslator(viper_ast) self.state_translator = StateTranslator(viper_ast) self.balance_translator = BalanceTranslator(viper_ast) def translate(self, vyper_program: VyperProgram, options: TranslationOptions) -> Program: if names.INIT not in vyper_program.functions: vyper_program.functions[mangled.INIT] = helpers.init_function() # Add built-in methods methods = seq_to_list(self.builtins.methods()) # Add built-in domains domains = seq_to_list(self.builtins.domains()) # Add built-in functions functions = seq_to_list(self.builtins.functions()) # Add built-in predicates predicates = seq_to_list(self.builtins.predicates()) # Add self.$sent field sent_type = types.MapType(types.VYPER_ADDRESS, types.NON_NEGATIVE_INT) vyper_program.fields.type.add_member(mangled.SENT_FIELD, sent_type) # Add self.$received field received_type = types.MapType(types.VYPER_ADDRESS, types.NON_NEGATIVE_INT) vyper_program.fields.type.add_member(mangled.RECEIVED_FIELD, received_type) # Add self.$selfdestruct field selfdestruct_type = types.VYPER_BOOL vyper_program.fields.type.add_member(mangled.SELFDESTRUCT_FIELD, selfdestruct_type) # For each nonreentrant key add a boolean flag whether it is set for key in vyper_program.nonreentrant_keys(): vyper_program.fields.type.add_member(mangled.lock_name(key), types.VYPER_BOOL) ctx = Context() ctx.program = vyper_program ctx.current_program = vyper_program ctx.options = options # Translate self domains.append(self._translate_struct(vyper_program.fields, ctx)) for field, field_type in vyper_program.fields.type.member_types.items(): ctx.field_types[field] = self.type_translator.translate(field_type, ctx) # Add the offer struct which we use as the key type of the offered map if ctx.program.config.has_option(names.CONFIG_ALLOCATION): offer_struct = VyperStruct(mangled.OFFER, helpers.offer_type(), None) domains.append(self._translate_struct(offer_struct, ctx)) def derived_resources_invariants(node: Optional[ast.Node] = None): if not ctx.program.config.has_option(names.CONFIG_ALLOCATION): return [] derived_resources_invs = [] trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx) offered = ctx.current_state[mangled.OFFERED].local_var(ctx) self_address = ctx.self_address or helpers.self_address(self.viper_ast) own_derived_resources = [(name, resource) for name, resource in ctx.program.own_resources.items() if isinstance(resource.type, types.DerivedResourceType)] translated_own_derived_resources = self.resource_translator\ .translate_resources_for_quantified_expr(own_derived_resources, ctx) translated_own_underlying_resources = self.resource_translator\ .translate_resources_for_quantified_expr(own_derived_resources, ctx, translate_underlying=True, args_idx_start=len(translated_own_derived_resources)) for index, (name, resource) in enumerate(own_derived_resources): if name == names.WEI: continue pos_node = node or resource.node invariants = [] assert resource.underlying_address is not None assert resource.underlying_resource is not None stmts = [] t_underlying_address = self.specification_translator.translate(resource.underlying_address, stmts, ctx) with ctx.state_scope(ctx.current_old_state, ctx.current_old_state): t_old_underlying_address = self.specification_translator.translate(resource.underlying_address, stmts, ctx) assert not stmts # resource.underlying_address is not self pos = self.to_position(resource.node, ctx, rules.UNDERLYING_ADDRESS_SELF_FAIL, values={'resource': resource}) underlying_address_not_self = self.viper_ast.NeCmp(t_underlying_address, self_address, pos) invariants.append(underlying_address_not_self) # resource.underlying_address is constant once set pos = self.to_position(pos_node, ctx, rules.UNDERLYING_ADDRESS_CONSTANT_FAIL, values={'resource': resource}) old_underlying_address_neq_zero = self.viper_ast.NeCmp(t_old_underlying_address, self.viper_ast.IntLit(0), pos) underlying_address_eq = self.viper_ast.EqCmp(t_underlying_address, t_old_underlying_address, pos) underlying_address_const = self.viper_ast.Implies(old_underlying_address_neq_zero, underlying_address_eq, pos) invariants.append(underlying_address_const) # trust_no_one in resource.underlying_address pos = self.to_position(pos_node, ctx, rules.UNDERLYING_ADDRESS_TRUST_NO_ONE_FAIL, values={'resource': resource}) trust_no_one = helpers.trust_no_one(self.viper_ast, trusted, self_address, t_underlying_address, pos) invariants.append(trust_no_one) # no_offers for resource.underlying_resource pos = self.to_position(pos_node, ctx, rules.UNDERLYING_RESOURCE_NO_OFFERS_FAIL, values={'resource': resource}) t_resource, args, type_cond = translated_own_underlying_resources[index] no_offers = helpers.no_offers(self.viper_ast, offered, t_resource, self_address, pos) forall_no_offers = self.viper_ast.Forall([*args], [self.viper_ast.Trigger([no_offers], pos)], self.viper_ast.Implies(type_cond, no_offers, pos), pos) invariants.append(forall_no_offers) # forall derived resource the underlying resource is different for i in range(index): pos = self.to_position(pos_node, ctx, rules.UNDERLYING_RESOURCE_NEQ_FAIL, values={'resource': resource, 'other_resource': own_derived_resources[i][1]}) t_other_resource, other_args, other_type_cond = translated_own_underlying_resources[i] neq_other_resource = self.viper_ast.NeCmp(t_resource, t_other_resource, pos) and_type_cond = self.viper_ast.And(type_cond, other_type_cond, pos) forall_neq_other_resource = self.viper_ast.Forall( [*args, *other_args], [self.viper_ast.Trigger([t_resource, t_other_resource], pos)], self.viper_ast.Implies(and_type_cond, neq_other_resource, pos), pos) invariants.append(forall_neq_other_resource) derived_resources_invs.extend(invariants) return derived_resources_invs ctx.derived_resources_invariants = derived_resources_invariants def unchecked_invariants(): res = [] self_var = ctx.self_var.local_var(ctx) address_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) # forall({a: address}, {sent(a)}, sent(a) >= old(sent(a))) old_self_var = ctx.old_self_var.local_var(ctx) q_var = self.viper_ast.LocalVarDecl('$a', address_type) q_local = q_var.localVar() sent = self.balance_translator.get_sent(self_var, q_local, ctx) old_sent = self.balance_translator.get_sent(old_self_var, q_local, ctx) expr = self.viper_ast.GeCmp(sent, old_sent) trigger = self.viper_ast.Trigger([sent]) sent_inc = self.viper_ast.Forall([q_var], [trigger], expr) res.append(sent_inc) if (ctx.program.config.has_option(names.CONFIG_ALLOCATION) and not ctx.program.config.has_option(names.CONFIG_NO_DERIVED_WEI)): # self.balance >= sum(allocated()) balance = self.balance_translator.get_balance(self_var, ctx) allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx) stmts = [] wei_resource = self.resource_translator.translate(None, stmts, ctx) assert len(stmts) == 0 allocated_map = self.allocation_translator.get_allocated_map(allocated, wei_resource, ctx) allocated_sum = helpers.map_sum(self.viper_ast, allocated_map, address_type) balance_geq_sum = self.viper_ast.GeCmp(balance, allocated_sum) res.append(balance_geq_sum) res.extend(derived_resources_invariants()) return res def unchecked_transitive_postconditions(): assume_locked = [] for lock in ctx.program.nonreentrant_keys(): with ctx.state_scope(ctx.current_old_state, ctx.current_old_state): old_lock_val = helpers.get_lock(self.viper_ast, lock, ctx) with ctx.state_scope(ctx.current_state, ctx.current_state): new_lock_val = helpers.get_lock(self.viper_ast, lock, ctx) assume_locked.append(self.viper_ast.EqCmp(old_lock_val, new_lock_val)) return assume_locked ctx.unchecked_invariants = unchecked_invariants ctx.unchecked_transitive_postconditions = unchecked_transitive_postconditions # Structs structs = vyper_program.structs.values() domains.extend(self._translate_struct(struct, ctx) for struct in structs) # Resources all_resources = flatten(vyper_program.resources.values()) domains.extend(self._translate_struct(resource, ctx) for resource in all_resources) domains.append(self._translate_struct(helpers.creator_resource(), ctx)) # Ghost functions functions.extend(self._translate_ghost_function(func, ctx) for func_list in vyper_program.ghost_functions.values() for func in func_list) domains.append(self._translate_implements(vyper_program, ctx)) # Pure functions pure_vyper_functions = filter(VyperFunction.is_pure, vyper_program.functions.values()) functions += [self.pure_function_translator.translate(function, ctx) for function in pure_vyper_functions] # Lemmas functions += [function for lemma in vyper_program.lemmas.values() for function in self.lemma_translator.translate(lemma, ctx)] # Events events = [self._translate_event(event, ctx) for event in vyper_program.events.values()] accs = [self._translate_accessible(acc, ctx) for acc in vyper_program.functions.values()] predicates.extend([*events, *accs]) # Viper methods def translate_condition_for_vyper_function(func: VyperFunction) -> bool: has_general_postcondition = (len(vyper_program.general_postconditions) > 0 or len(vyper_program.transitive_postconditions) > 0) if not has_general_postcondition and func.is_pure(): has_loop_invariants = len(func.loop_invariants) > 0 has_unreachable_assertions = func.analysis.uses_unreachable return has_loop_invariants or has_unreachable_assertions if func.is_private(): # We have to generate a Viper method to check the specification # if the specification of the function could get assumed. return self.function_translator.can_assume_private_function(func) return True vyper_functions = filter(translate_condition_for_vyper_function, vyper_program.functions.values()) methods.append(self._create_transitivity_check(ctx)) methods.append(self._create_reflexivity_check(ctx)) methods.append(self._create_forced_ether_check(ctx)) methods += [self.function_translator.translate(function, ctx) for function in vyper_functions] for i, t in enumerate(self.viper_ast.seq_types): type_vars = { self.viper_ast.TypeVar('$E') : t } dt = self.viper_ast.DomainType('_array_ce_helper', type_vars, type_vars.keys()) functions.append(self.viper_ast.Function('___dummy' + str(i), [], dt, [], [], None)) # Viper Program viper_program = self.viper_ast.Program(domains, [], functions, predicates, methods) return viper_program def _translate_struct(self, struct: VyperStruct, ctx: Context): # For structs we need to synthesize an initializer and an equality domain function with # their corresponding axioms domain = mangled.struct_name(struct.name, struct.type.kind) struct_type = self.type_translator.translate(struct.type, ctx) address_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) number_of_members = len(struct.type.member_types) members = [None] * number_of_members for name, vyper_type in struct.type.member_types.items(): idx = struct.type.member_indices[name] member_type = self.type_translator.translate(vyper_type, ctx) var_decl = self.viper_ast.LocalVarDecl(f'$arg_{idx}', member_type) members[idx] = (name, var_decl) init_name = mangled.struct_init_name(struct.name, struct.type.kind) init_parms = [var for _, var in members] resource_address_var = None if isinstance(struct, Resource) and not (struct.name == mangled.CREATOR or struct.name == names.UNDERLYING_WEI): # First argument has to be an address for resources if it is not the creator resource resource_address_var = self.viper_ast.LocalVarDecl(f'$address_arg', address_type) init_parms.append(resource_address_var) init_f = self.viper_ast.DomainFunc(init_name, init_parms, struct_type, False, domain) eq_name = mangled.struct_eq_name(struct.name, struct.type.kind) eq_left_decl = self.viper_ast.LocalVarDecl('$l', struct_type) eq_right_decl = self.viper_ast.LocalVarDecl('$r', struct_type) eq_parms = [eq_left_decl, eq_right_decl] eq_f = self.viper_ast.DomainFunc(eq_name, eq_parms, self.viper_ast.Bool, False, domain) init_args = [param.localVar() for param in init_parms] init = helpers.struct_init(self.viper_ast, init_args, struct.type) # The type tag of the initializer is always the type tag of the struct being initialized type_tag = self.viper_ast.IntLit(mangled.struct_type_tag(struct.type.name, struct.type.kind)) init_expr = self.viper_ast.EqCmp(helpers.struct_type_tag(self.viper_ast, init), type_tag) eq_left = eq_left_decl.localVar() eq_right = eq_right_decl.localVar() eq = helpers.struct_eq(self.viper_ast, eq_left, eq_right, struct.type) # For two struct to be equal the type tags have to agree, i.e., they have to be of the same Vyper type ltag = helpers.struct_type_tag(self.viper_ast, eq_left) rtag = helpers.struct_type_tag(self.viper_ast, eq_right) eq_expr = self.viper_ast.EqCmp(ltag, rtag) for name, var in members: init_get = helpers.struct_get(self.viper_ast, init, name, var.typ(), struct.type) init_eq = self.viper_ast.EqCmp(init_get, var.localVar()) init_expr = self.viper_ast.And(init_expr, init_eq) eq_get_l = helpers.struct_get(self.viper_ast, eq_left, name, var.typ(), struct.type) eq_get_r = helpers.struct_get(self.viper_ast, eq_right, name, var.typ(), struct.type) member_type = struct.type.member_types[name] eq_eq = self.type_translator.eq(eq_get_l, eq_get_r, member_type, ctx) eq_expr = self.viper_ast.And(eq_expr, eq_eq) if isinstance(struct, Resource) and not (struct.name == mangled.CREATOR or struct.name == names.UNDERLYING_WEI): init_get = helpers.struct_get_idx(self.viper_ast, init, number_of_members, address_type) init_eq = self.viper_ast.EqCmp(init_get, resource_address_var.localVar()) init_expr = self.viper_ast.And(init_expr, init_eq) eq_get_l = helpers.struct_get_idx(self.viper_ast, eq_left, number_of_members, address_type) eq_get_r = helpers.struct_get_idx(self.viper_ast, eq_right, number_of_members, address_type) eq_eq = self.type_translator.eq(eq_get_l, eq_get_r, types.VYPER_ADDRESS, ctx) eq_expr = self.viper_ast.And(eq_expr, eq_eq) init_trigger = self.viper_ast.Trigger([init]) init_quant = self.viper_ast.Forall(init_parms, [init_trigger], init_expr) init_ax_name = mangled.axiom_name(init_name) init_axiom = self.viper_ast.DomainAxiom(init_ax_name, init_quant, domain) eq_trigger = self.viper_ast.Trigger([eq]) eq_lr_eq = self.viper_ast.EqCmp(eq_left, eq_right) eq_equals = self.viper_ast.EqCmp(eq, eq_lr_eq) eq_definition = self.viper_ast.EqCmp(eq, eq_expr) eq_expr = self.viper_ast.And(eq_equals, eq_definition) eq_quant = self.viper_ast.Forall(eq_parms, [eq_trigger], eq_expr) eq_axiom_name = mangled.axiom_name(eq_name) eq_axiom = self.viper_ast.DomainAxiom(eq_axiom_name, eq_quant, domain) return self.viper_ast.Domain(domain, [init_f, eq_f], [init_axiom, eq_axiom], []) def _translate_ghost_function(self, function: GhostFunction, ctx: Context): # We translate a ghost function as a function where the first argument is the # self struct usually obtained through the contracts map pos = self.to_position(function.node, ctx) fname = mangled.ghost_function_name(function.interface, function.name) addr_var = TranslatedVar(names.ADDRESS, '$addr', types.VYPER_ADDRESS, self.viper_ast, pos) self_var = TranslatedVar(names.SELF, '$self', AnyStructType(), self.viper_ast, pos) self_address = helpers.self_address(self.viper_ast, pos) args = [addr_var, self_var] for idx, var in enumerate(function.args.values()): args.append(TranslatedVar(var.name, f'$arg_{idx}', var.type, self.viper_ast, pos)) args_var_decls = [arg.var_decl(ctx) for arg in args] viper_type = self.type_translator.translate(function.type.return_type, ctx) if ctx.program.config.has_option(names.CONFIG_TRUST_CASTS): pres = [] else: ifs = filter(lambda i: function.name in i.ghost_functions, ctx.program.interfaces.values()) interface = next(ifs) addr = addr_var.local_var(ctx) implements = helpers.implements(self.viper_ast, addr, interface.name, ctx, pos) pres = [implements] result = self.viper_ast.Result(viper_type) posts = self.type_translator.type_assumptions(result, function.type.return_type, ctx) # If the ghost function has an implementation we add a postcondition for that implementation = ctx.program.ghost_function_implementations.get(function.name) if implementation: with ctx.function_scope(): ctx.args = {arg.name: arg for arg in args} ctx.current_state = {mangled.SELF: self_var} body = implementation.node.body[0] assert isinstance(body, ast.ExprStmt) expr = body.value stmts = [] impl_expr = self.specification_translator.translate(expr, stmts, ctx) assert not stmts definition = self.viper_ast.EqCmp(result, impl_expr, pos) # The implementation is only defined for the self address is_self = self.viper_ast.EqCmp(addr_var.local_var(ctx), self_address, pos) posts.append(self.viper_ast.Implies(is_self, definition, pos)) return self.viper_ast.Function(fname, args_var_decls, viper_type, pres, posts, None, pos) def _translate_implements(self, program: VyperProgram, ctx: Context): domain = mangled.IMPLEMENTS_DOMAIN self_address = helpers.self_address(self.viper_ast) implements = [] for interface in program.implements: implements.append(helpers.implements(self.viper_ast, self_address, interface.name, ctx)) axiom_name = mangled.axiom_name(domain) axiom_body = reduce(self.viper_ast.And, implements, self.viper_ast.TrueLit()) axiom = self.viper_ast.DomainAxiom(axiom_name, axiom_body, domain) return self.viper_ast.Domain(domain, [], [axiom], {}) def _translate_event(self, event: VyperEvent, ctx: Context): name = mangled.event_name(event.name) viper_types = [self.type_translator.translate(arg, ctx) for arg in event.type.arg_types] args = [self.viper_ast.LocalVarDecl(f'$arg{idx}', viper_type) for idx, viper_type in enumerate(viper_types)] return self.viper_ast.Predicate(name, args, None) def _translate_accessible(self, function: VyperFunction, ctx: Context): name = mangled.accessible_name(function.name) arg0 = self.viper_ast.LocalVarDecl('$tag', self.viper_ast.Int) address_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) arg1 = self.viper_ast.LocalVarDecl('$to', address_type) wei_value_type = self.type_translator.translate(types.VYPER_WEI_VALUE, ctx) arg2 = self.viper_ast.LocalVarDecl('$amount', wei_value_type) args = [arg0, arg1, arg2] for idx, arg in enumerate(function.args.values()): arg_name = f'$arg{idx}' arg_type = self.type_translator.translate(arg.type, ctx) args.append(self.viper_ast.LocalVarDecl(arg_name, arg_type)) return self.viper_ast.Predicate(name, args, None) def _assume_assertions(self, self_state: State, old_state: State, res: List[Stmt], ctx: Context): with ctx.state_scope(self_state, old_state): for inv in ctx.unchecked_invariants(): res.append(self.viper_ast.Inhale(inv)) for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.invariants: pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) inv_expr = self.specification_translator.translate_invariant(inv, res, ctx) res.append(self.viper_ast.Inhale(inv_expr, pos)) for inv in ctx.current_program.invariants: pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) inv_expr = self.specification_translator.translate_invariant(inv, res, ctx) res.append(self.viper_ast.Inhale(inv_expr, pos)) is_post_var = self.viper_ast.LocalVar('$post', self.viper_ast.Bool) for post in ctx.program.transitive_postconditions: pos = self.to_position(post, ctx, rules.INHALE_POSTCONDITION_FAIL) post_expr = self.specification_translator.translate_pre_or_postcondition(post, res, ctx) post_expr = self.viper_ast.Implies(is_post_var, post_expr, pos) res.append(self.viper_ast.Inhale(post_expr, pos)) for post in ctx.unchecked_transitive_postconditions(): post_expr = self.viper_ast.Implies(is_post_var, post) res.append(self.viper_ast.Inhale(post_expr)) def _create_transitivity_check(self, ctx: Context): # Creates a check that all invariants and transitive postconditions are transitive. # This is needed, because we want to assume them after a call, which could have # reentered multiple times. # To check transitivity, we create 3 states, assume the global unchecked invariants # for all of them, assume the invariants for state no 1 (with state no 1 being the # old state), for state no 2 (with state no 1 being the old state), and again for # state no 3 (with state no 2 being the old state). # In the end we assert the invariants for state no 3 (with state no 1 being the old state) # The transitive postconditions are checked similarly, but conditioned under an unkown # boolean variable so we can't assume them for checking the invariants with ctx.function_scope(): name = mangled.TRANSITIVITY_CHECK states = [self.state_translator.state(lambda n: f'${n}${i}', ctx) for i in range(3)] block = TranslatedVar(names.BLOCK, mangled.BLOCK, types.BLOCK_TYPE, self.viper_ast) ctx.locals[names.BLOCK] = block is_post = self.viper_ast.LocalVarDecl('$post', self.viper_ast.Bool) local_vars = [*flatten(s.values() for s in states), block] local_vars = [var.var_decl(ctx) for var in local_vars] local_vars.append(is_post) if ctx.program.analysis.uses_issued: ctx.issued_state = self.state_translator.state(mangled.issued_state_var_name, ctx) local_vars.extend(var.var_decl(ctx) for var in ctx.issued_state.values()) all_states = chain(states, [ctx.issued_state]) else: all_states = states body = [] # Assume type assumptions for all self-states for state in all_states: for var in state.values(): local = var.local_var(ctx) type_assumptions = self.type_translator.type_assumptions(local, var.type, ctx) body.extend(self.viper_ast.Inhale(a) for a in type_assumptions) # Assume type assumptions for block block_var = block.local_var(ctx) block_assumptions = self.type_translator.type_assumptions(block_var, types.BLOCK_TYPE, ctx) body.extend(self.viper_ast.Inhale(a) for a in block_assumptions) def assume_assertions(s1, s2): self._assume_assertions(s1, s2, body, ctx) if ctx.program.analysis.uses_issued: # Assume assertions for issued state and issued state assume_assertions(ctx.issued_state, ctx.issued_state) # Assume assertions for current state 0 and issued state assume_assertions(states[0], ctx.issued_state) else: # Assume assertions for current state 0 and old state 0 assume_assertions(states[0], states[0]) # Assume assertions for current state 1 and old state 0 assume_assertions(states[1], states[0]) # Assume assertions for current state 2 and old state 1 assume_assertions(states[2], states[1]) # Check invariants for current state 2 and old state 0 with ctx.state_scope(states[2], states[0]): for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.invariants: rule = rules.INVARIANT_TRANSITIVITY_VIOLATED apos = self.to_position(inv, ctx, rule) inv_expr = self.specification_translator.translate_invariant(inv, body, ctx) body.append(self.viper_ast.Assert(inv_expr, apos)) for inv in ctx.current_program.invariants: rule = rules.INVARIANT_TRANSITIVITY_VIOLATED apos = self.to_position(inv, ctx, rule) inv_expr = self.specification_translator.translate_invariant(inv, body, ctx) body.append(self.viper_ast.Assert(inv_expr, apos)) for post in ctx.program.transitive_postconditions: rule = rules.POSTCONDITION_TRANSITIVITY_VIOLATED apos = self.to_position(post, ctx, rule) post_expr = self.specification_translator.translate_invariant(post, body, ctx) pos = self.to_position(post, ctx) is_post_var = self.viper_ast.LocalVar('$post', self.viper_ast.Bool, pos) post_expr = self.viper_ast.Implies(is_post_var, post_expr, pos) body.append(self.viper_ast.Assert(post_expr, apos)) local_vars.extend(ctx.new_local_vars) return self.viper_ast.Method(name, [], [], [], [], local_vars, body) def _create_reflexivity_check(self, ctx: Context): # Creates a check that all invariants and transitive postconditions are reflexive. # This is needed, because we want to assume them after a call, which could have # reentered zero times. # To check transitivity, we create 2 states, assume the global unchecked invariants # for both of them, assume the invariants for state no 2 with state no 1 being the # old state. # In the end we assert the invariants for state no 2 with state no 2 being the old state. # The transitive postconditions are checked similarly, but conditioned under an unknown # boolean variable so we can't assume them for checking the invariants with ctx.function_scope(): name = mangled.REFLEXIVITY_CHECK states = [self.state_translator.state(lambda n: f'${n}${i}', ctx) for i in range(2)] block = TranslatedVar(names.BLOCK, mangled.BLOCK, types.BLOCK_TYPE, self.viper_ast) ctx.locals[names.BLOCK] = block is_post = self.viper_ast.LocalVarDecl('$post', self.viper_ast.Bool) local_vars = [*flatten(s.values() for s in states), block] local_vars = [var.var_decl(ctx) for var in local_vars] local_vars.append(is_post) if ctx.program.analysis.uses_issued: ctx.issued_state = self.state_translator.state(mangled.issued_state_var_name, ctx) local_vars.extend(var.var_decl(ctx) for var in ctx.issued_state.values()) all_states = chain(states, [ctx.issued_state]) else: all_states = states body = [] # Assume type assumptions for all self-states for state in all_states: for var in state.values(): local = var.local_var(ctx) type_assumptions = self.type_translator.type_assumptions(local, var.type, ctx) body.extend(self.viper_ast.Inhale(a) for a in type_assumptions) # Assume type assumptions for block block_var = block.local_var(ctx) block_assumptions = self.type_translator.type_assumptions(block_var, types.BLOCK_TYPE, ctx) body.extend(self.viper_ast.Inhale(a) for a in block_assumptions) def assume_assertions(s1, s2): self._assume_assertions(s1, s2, body, ctx) # Assume assertions for current state 1 and old state 0 assume_assertions(states[1], states[0]) # Check invariants for current state 1 and old state 1 with ctx.state_scope(states[1], states[1]): for inv in ctx.program.invariants: rule = rules.INVARIANT_REFLEXIVITY_VIOLATED apos = self.to_position(inv, ctx, rule) inv_expr = self.specification_translator.translate_invariant(inv, body, ctx) body.append(self.viper_ast.Assert(inv_expr, apos)) for post in ctx.program.transitive_postconditions: rule = rules.POSTCONDITION_REFLEXIVITY_VIOLATED apos = self.to_position(post, ctx, rule) post_expr = self.specification_translator.translate_invariant(post, body, ctx) pos = self.to_position(post, ctx) is_post_var = self.viper_ast.LocalVar('$post', self.viper_ast.Bool, pos) post_expr = self.viper_ast.Implies(is_post_var, post_expr, pos) body.append(self.viper_ast.Assert(post_expr, apos)) local_vars.extend(ctx.new_local_vars) return self.viper_ast.Method(name, [], [], [], [], local_vars, body) def _create_forced_ether_check(self, ctx: Context): # Creates a check that all transitive postconditions still hold after # forcibly receiving ether through selfdestruct or coinbase transactions with ctx.function_scope(): name = mangled.FORCED_ETHER_CHECK present_state = self.state_translator.state(mangled.present_state_var_name, ctx) pre_state = self.state_translator.state(mangled.pre_state_var_name, ctx) local_vars = [var.var_decl(ctx) for var in chain(present_state.values(), pre_state.values())] if ctx.program.analysis.uses_issued: issued_state = self.state_translator.state(mangled.issued_state_var_name, ctx) ctx.issued_state = issued_state local_vars.extend(var.var_decl(ctx) for var in issued_state.values()) all_states = [present_state, pre_state, issued_state] else: all_states = [present_state, pre_state] block = TranslatedVar(names.BLOCK, mangled.BLOCK, types.BLOCK_TYPE, self.viper_ast) ctx.locals[names.BLOCK] = block is_post = self.viper_ast.LocalVarDecl('$post', self.viper_ast.Bool) havoc = self.viper_ast.LocalVarDecl('$havoc', self.viper_ast.Int) local_vars.extend([is_post, havoc, block.var_decl(ctx)]) body = [] for state in all_states: for var in state.values(): local = var.local_var(ctx) type_assumptions = self.type_translator.type_assumptions(local, var.type, ctx) body.extend(self.viper_ast.Inhale(a) for a in type_assumptions) # Assume type assumptions for block block_var = block.local_var(ctx) block_assumptions = self.type_translator.type_assumptions(block_var, types.BLOCK_TYPE, ctx) body.extend(self.viper_ast.Inhale(a) for a in block_assumptions) def assume_assertions(s1, s2): self._assume_assertions(s1, s2, body, ctx) # Assume balance increase to be non-negative zero = self.viper_ast.IntLit(0) assume_non_negative = self.viper_ast.Inhale(self.viper_ast.GeCmp(havoc.localVar(), zero)) body.append(assume_non_negative) if ctx.program.analysis.uses_issued: assume_assertions(issued_state, issued_state) assume_assertions(present_state, issued_state) else: assume_assertions(present_state, present_state) self.state_translator.copy_state(present_state, pre_state, body, ctx) with ctx.state_scope(present_state, present_state): self.balance_translator.increase_balance(havoc.localVar(), body, ctx) with ctx.state_scope(present_state, pre_state): for post in ctx.program.transitive_postconditions: rule = rules.POSTCONDITION_CONSTANT_BALANCE apos = self.to_position(post, ctx, rule) post_expr = self.specification_translator.translate_pre_or_postcondition(post, body, ctx) pos = self.to_position(post, ctx) is_post_var = self.viper_ast.LocalVar('$post', self.viper_ast.Bool, pos) post_expr = self.viper_ast.Implies(is_post_var, post_expr, pos) body.append(self.viper_ast.Assert(post_expr, apos)) local_vars.extend(ctx.new_local_vars) return self.viper_ast.Method(name, [], [], [], [], local_vars, body)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/translator.py
translator.py
from typing import List from twovyper.ast import ast_nodes as ast from twovyper.ast.nodes import VyperFunction, VyperVar from twovyper.translation import mangled from twovyper.translation.abstract import CommonTranslator from twovyper.translation.context import Context from twovyper.translation.specification import SpecificationTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedVar from twovyper.verification import rules from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Function class LemmaTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.specification_translator = SpecificationTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) def translate(self, function: VyperFunction, ctx: Context) -> List[Function]: with ctx.function_scope(): with ctx.lemma_scope(): pos = self.to_position(function.node, ctx) ctx.function = function args = {name: self._translate_non_local_var(var, ctx) for name, var in function.args.items()} ctx.present_state = {} ctx.old_state = {} ctx.pre_state = {} ctx.issued_state = {} ctx.current_state = {} ctx.current_old_state = {} ctx.args = args.copy() ctx.locals = {} ctx.success_var = None ctx.return_label = None ctx.revert_label = None ctx.result_var = None preconditions = [] # Type assumptions for arguments for var in function.args.values(): local_var = args[var.name].local_var(ctx) assumptions = self.type_translator.type_assumptions(local_var, var.type, ctx) preconditions.extend(assumptions) # Explicit preconditions for precondition in function.preconditions: stmts = [] preconditions.append(self.specification_translator .translate_pre_or_postcondition(precondition, stmts, ctx)) assert not stmts # If we assume uninterpreted function and assert the interpreted ones, the lemma has no body body = None if function.is_interpreted() else self.viper_ast.TrueLit() postconditions = [] interpreted_postconditions = [] if function.is_interpreted(): # Without a body, we must ensure that "result == true" viper_result = self.viper_ast.Result(self.viper_ast.Bool, pos) postconditions.append(self.viper_ast.EqCmp(viper_result, self.viper_ast.TrueLit(), pos)) for idx, stmt in enumerate(function.node.body): assert isinstance(stmt, ast.ExprStmt) expr = stmt.value stmts = [] post = self.specification_translator.translate(expr, stmts, ctx) post_pos = self.to_position(stmt, ctx, rules=rules.LEMMA_FAIL) viper_result = self.viper_ast.Result(self.viper_ast.Bool, post_pos) postconditions.append(self.viper_ast.EqCmp(viper_result, post, post_pos)) if function.is_interpreted(): # If the function is interpreted, generate also an interpreted version of the lemma step with ctx.interpreted_scope(): interpreted_post = self.specification_translator.translate(expr, stmts, ctx) interpreted_postconditions.append( self.viper_ast.EqCmp(viper_result, interpreted_post, post_pos)) assert not stmts args_list = [arg.var_decl(ctx) for arg in args.values()] viper_name = mangled.lemma_name(function.name) viper_functions = [self.viper_ast.Function(viper_name, args_list, self.viper_ast.Bool, preconditions, postconditions, body, pos)] if function.is_interpreted(): # If we have interpreted postconditions, generate a second function. # This second function has always a body, the same arguments and the same preconditions, but uses # interpreted mul, div and mod instead of the uninterpreted $Int-functions in the postconditions. viper_functions.append(self.viper_ast.Function( "interpreted$" + viper_name, args_list, self.viper_ast.Bool, preconditions, interpreted_postconditions, self.viper_ast.TrueLit(), pos)) return viper_functions def _translate_non_local_var(self, var: VyperVar, ctx: Context): pos = self.to_position(var.node, ctx) name = mangled.local_var_name(ctx.inline_prefix, var.name) return TranslatedVar(var.name, name, var.type, self.viper_ast, pos, is_local=False)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/lemma.py
lemma.py
from functools import reduce from itertools import chain, zip_longest from typing import List from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.nodes import VyperFunction, VyperVar from twovyper.translation import helpers, mangled from twovyper.translation.context import Context from twovyper.translation.abstract import CommonTranslator from twovyper.translation.allocation import AllocationTranslator from twovyper.translation.balance import BalanceTranslator from twovyper.translation.expression import ExpressionTranslator from twovyper.translation.model import ModelTranslator from twovyper.translation.resource import ResourceTranslator from twovyper.translation.specification import SpecificationTranslator from twovyper.translation.state import StateTranslator from twovyper.translation.statement import StatementTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedVar from twovyper.verification import rules from twovyper.verification.error import Via from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Method, Stmt, Expr class FunctionTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.allocation_translator = AllocationTranslator(viper_ast) self.balance_translator = BalanceTranslator(viper_ast) self.expression_translator = ExpressionTranslator(viper_ast) self.model_translator = ModelTranslator(viper_ast) self.resource_translator = ResourceTranslator(viper_ast) self.specification_translator = SpecificationTranslator(viper_ast) self.statement_translator = StatementTranslator(viper_ast) self.state_translator = StateTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) def translate(self, function: VyperFunction, ctx: Context) -> Method: with ctx.function_scope(): # A synthesized __init__ does not have a position in the file if function.node: pos = self.to_position(function.node, ctx) else: pos = self.to_position(ctx.program.node, ctx) ctx.function = function is_init = (function.name == names.INIT) do_performs = not ctx.program.config.has_option(names.CONFIG_NO_PERFORMS) if is_init and do_performs: ctx.program.config.options.append(names.CONFIG_NO_PERFORMS) args = {name: self._translate_var(var, ctx, False) for name, var in function.args.items()} # Local variables will be added when translating. local_vars = { # The msg variable names.MSG: TranslatedVar(names.MSG, mangled.MSG, types.MSG_TYPE, self.viper_ast), # The block variable names.BLOCK: TranslatedVar(names.BLOCK, mangled.BLOCK, types.BLOCK_TYPE, self.viper_ast), # The chain variable names.CHAIN: TranslatedVar(names.CHAIN, mangled.CHAIN, types.CHAIN_TYPE, self.viper_ast), # The tx variable names.TX: TranslatedVar(names.TX, mangled.TX, types.TX_TYPE, self.viper_ast) } # We represent self as a struct in each state (present, old, pre, issued). # For other contracts we use a map from addresses to structs. ctx.present_state = self.state_translator.state(mangled.present_state_var_name, ctx) # The last publicly visible state of the blockchain ctx.old_state = self.state_translator.state(mangled.old_state_var_name, ctx) if function.is_private(): # The last publicly visible state of the blockchain before the function call ctx.pre_old_state = self.state_translator.state(mangled.pre_old_state_var_name, ctx) # The state of the blockchain before the function call ctx.pre_state = self.state_translator.state(mangled.pre_state_var_name, ctx) # The state of the blockchain when the transaction was issued ctx.issued_state = self.state_translator.state(mangled.issued_state_var_name, ctx) # Usually self refers to the present state and old(self) refers to the old state ctx.current_state = ctx.present_state ctx.current_old_state = ctx.old_state # We create copies of variable maps because ctx is allowed to modify them ctx.args = args.copy() ctx.locals = local_vars.copy() ctx.locals[mangled.ORIGINAL_MSG] = local_vars[names.MSG] state_dicts = [ctx.present_state, ctx.old_state, ctx.pre_state, ctx.issued_state] if function.is_private(): state_dicts.append(ctx.pre_old_state) state = [] for d in state_dicts: state.extend(d.values()) self_var = ctx.self_var.local_var(ctx) pre_self_var = ctx.pre_self_var.local_var(ctx) ctx.success_var = TranslatedVar(names.SUCCESS, mangled.SUCCESS_VAR, types.VYPER_BOOL, self.viper_ast) return_variables = [ctx.success_var] success_var = ctx.success_var.local_var(ctx) end_label = self.viper_ast.Label(mangled.END_LABEL) return_label = self.viper_ast.Label(mangled.RETURN_LABEL) revert_label = self.viper_ast.Label(mangled.REVERT_LABEL) ctx.return_label = mangled.RETURN_LABEL ctx.revert_label = mangled.REVERT_LABEL if function.type.return_type: ctx.result_var = TranslatedVar(names.RESULT, mangled.RESULT_VAR, function.type.return_type, self.viper_ast) return_variables.append(ctx.result_var) body = [] # Assume type assumptions for self state self.state_translator.assume_type_assumptions_for_state(ctx.present_state, "Present", body, ctx) if function.is_private(): self.state_translator.assume_type_assumptions_for_state(ctx.old_state, "Old", body, ctx) # Assume type assumptions for issued state if function.analysis.uses_issued: self.state_translator.assume_type_assumptions_for_state(ctx.issued_state, "Issued", body, ctx) # Assume type assumptions for self address self_address = helpers.self_address(self.viper_ast) self_address_ass = self.type_translator.type_assumptions(self_address, types.VYPER_ADDRESS, ctx) self_address_assumptions = [self.viper_ast.Inhale(c) for c in self_address_ass] self_address_info_msg = "Assume type assumptions for self address" self.seqn_with_info(self_address_assumptions, self_address_info_msg, body) # Assume type assumptions for arguments argument_type_assumptions = [] for var in function.args.values(): local_var = args[var.name].local_var(ctx) assumptions = self.type_translator.type_assumptions(local_var, var.type, ctx) argument_type_assumptions.extend(assumptions) argument_cond_assumes = [self.viper_ast.Inhale(c) for c in argument_type_assumptions] ui_info_msg = "Assume type assumptions for arguments" self.seqn_with_info(argument_cond_assumes, ui_info_msg, body) # Assume type assumptions for block block_var = ctx.block_var.local_var(ctx) block_type_assumptions = self.type_translator.type_assumptions(block_var, types.BLOCK_TYPE, ctx) block_assumes = [self.viper_ast.Inhale(c) for c in block_type_assumptions] block_info_msg = "Assume type assumptions for block" self.seqn_with_info(block_assumes, block_info_msg, body) # Assume type assumptions for msg msg_var = ctx.msg_var.local_var(ctx) msg_type_assumption = self.type_translator.type_assumptions(msg_var, types.MSG_TYPE, ctx) # We additionally know that msg.sender != 0 zero = self.viper_ast.IntLit(0) msg_sender = helpers.msg_sender(self.viper_ast, ctx) neq0 = self.viper_ast.NeCmp(msg_sender, zero) msg_assumes = [self.viper_ast.Inhale(c) for c in chain(msg_type_assumption, [neq0])] msg_info_msg = "Assume type assumptions for msg" self.seqn_with_info(msg_assumes, msg_info_msg, body) # Interface references we have knowledge about and therefore can e.g. assume their invariants known_interface_ref = [] self_type = ctx.program.fields.type for member_name, member_type in self_type.member_types.items(): viper_type = self.type_translator.translate(member_type, ctx) if isinstance(member_type, types.InterfaceType): get = helpers.struct_get(self.viper_ast, ctx.self_var.local_var(ctx), member_name, viper_type, self_type) known_interface_ref.append((member_type.name, get)) # Assume unchecked and user-specified invariants inv_pres_issued = [] inv_pres_self = [] # Translate the invariants for the issued state. Since we don't know anything about # the state before then, we use the issued state itself as the old state if not is_init and function.analysis.uses_issued: with ctx.state_scope(ctx.issued_state, ctx.issued_state): for inv in ctx.unchecked_invariants(): inv_pres_issued.append(self.viper_ast.Inhale(inv)) # Assume implemented interface invariants for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.invariants: program_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) expr = self.specification_translator.translate_invariant(inv, inv_pres_issued, ctx, True) inv_pres_issued.append(self.viper_ast.Inhale(expr, program_pos)) # Assume own invariants for inv in ctx.current_program.invariants: program_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) expr = self.specification_translator.translate_invariant(inv, inv_pres_issued, ctx, True) inv_pres_issued.append(self.viper_ast.Inhale(expr, program_pos)) # If we use issued, we translate the invariants for the current state with the # issued state as the old state, else we just use the self state as the old state # which results in fewer assumptions passed to the prover if not is_init: present_state = ctx.present_state if function.is_public() else ctx.old_state last_state = ctx.issued_state if function.analysis.uses_issued else present_state with ctx.state_scope(present_state, last_state): for inv in ctx.unchecked_invariants(): inv_pres_self.append(self.viper_ast.Inhale(inv)) # Assume implemented interface invariants for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.invariants: program_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) expr = self.specification_translator.translate_invariant(inv, inv_pres_self, ctx) inv_pres_self.append(self.viper_ast.Inhale(expr, program_pos)) # Assume own invariants for inv in ctx.current_program.invariants: program_pos = self.to_position(inv, ctx, rules.INHALE_INVARIANT_FAIL) expr = self.specification_translator.translate_invariant(inv, inv_pres_self, ctx) inv_pres_self.append(self.viper_ast.Inhale(expr, program_pos)) # Also assume the unchecked invariants for non-public states if function.is_private(): with ctx.state_scope(ctx.present_state, last_state): for inv in ctx.unchecked_invariants(): inv_pres_self.append(self.viper_ast.Inhale(inv)) self.expression_translator.assume_contract_state(known_interface_ref, inv_pres_self, ctx, skip_caller_private=True) iv_info_msg = "Assume invariants for issued self" self.seqn_with_info(inv_pres_issued, iv_info_msg, body) iv_info_msg = "Assume invariants for self" self.seqn_with_info(inv_pres_self, iv_info_msg, body) if function.is_private(): # Assume an unspecified permission amount to the events if the function is private event_handling = [] self.expression_translator.log_all_events_zero_or_more_times(event_handling, ctx, pos) self.seqn_with_info(event_handling, "Assume we know nothing about events", body) # Assume preconditions pre_stmts = [] with ctx.state_scope(ctx.present_state, ctx.old_state): for precondition in function.preconditions: cond = self.specification_translator.\ translate_pre_or_postcondition(precondition, pre_stmts, ctx, assume_events=True) pre_pos = self.to_position(precondition, ctx, rules.INHALE_PRECONDITION_FAIL) pre_stmts.append(self.viper_ast.Inhale(cond, pre_pos)) self.seqn_with_info(pre_stmts, "Assume preconditions", body) # pre_self is the same as self in the beginning self.state_translator.copy_state(ctx.present_state, ctx.pre_state, body, ctx) # If the function is public, old_self is also the same as self in the beginning if function.is_public(): self.state_translator.copy_state(ctx.present_state, ctx.old_state, body, ctx) else: self.state_translator.copy_state(ctx.old_state, ctx.pre_old_state, body, ctx) def return_bool(value: bool) -> Stmt: lit = self.viper_ast.TrueLit if value else self.viper_ast.FalseLit return self.viper_ast.LocalVarAssign(success_var, lit()) # If we do not encounter an exception we will return success body.append(return_bool(True)) # Add variable for success(if_not=overflow) that tracks whether an overflow happened overflow_var = helpers.overflow_var(self.viper_ast) ctx.new_local_vars.append(overflow_var) overflow_var_assign = self.viper_ast.LocalVarAssign(overflow_var.localVar(), self.viper_ast.FalseLit()) body.append(overflow_var_assign) # Add variable for whether we need to set old_self to current self # In the beginning, it is True as the first public state needs to # be checked against itself if is_init: ctx.new_local_vars.append(helpers.first_public_state_var(self.viper_ast)) fps = helpers.first_public_state_var(self.viper_ast, pos).localVar() var_assign = self.viper_ast.LocalVarAssign(fps, self.viper_ast.TrueLit()) body.append(var_assign) # Translate the performs clauses performs_clause_conditions = [] interface_files = [ctx.program.interfaces[impl.name].file for impl in ctx.program.implements] for performs in function.performs: assert isinstance(performs, ast.FunctionCall) with ctx.state_scope(ctx.pre_state, ctx.pre_state): address, resource = self.allocation_translator.location_address_of_performs(performs, body, ctx, return_resource=True) if (resource is not None and resource.file is not None and resource.file != ctx.program.file and resource.file in interface_files): # All performs clauses with own resources of an implemented interface should be on that interface apos = self.to_position(performs, ctx, rules.INTERFACE_RESOURCE_PERFORMS, values={'resource': resource}) cond = self.viper_ast.NeCmp(address, self_address, apos) performs_clause_conditions.append(self.viper_ast.Assert(cond, apos)) _ = self.specification_translator.translate_ghost_statement(performs, body, ctx, is_performs=True) for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] interface_func = interface.functions.get(function.name) if interface_func: with ctx.program_scope(interface): for performs in interface_func.performs: assert isinstance(performs, ast.FunctionCall) self.specification_translator.translate_ghost_statement(performs, body, ctx, is_performs=True) # Revert if a @nonreentrant lock is set self._assert_unlocked(function, body, ctx) # Set all @nonreentrant locks self._set_locked(function, True, body, ctx) # In the initializer initialize all fields to their default values if is_init: self.state_translator.initialize_state(ctx.current_state, body, ctx) # Havoc self.balance, because we are not allowed to assume self.balance == 0 # in the beginning self._havoc_balance(body, ctx) if ctx.program.config.has_option(names.CONFIG_ALLOCATION): self.state_translator.copy_state(ctx.current_state, ctx.current_old_state, body, ctx, unless=lambda n: (n != mangled.ALLOCATED and n != mangled.TRUSTED and n != mangled.OFFERED)) self.state_translator.havoc_state(ctx.current_state, body, ctx, unless=lambda n: (n != mangled.ALLOCATED and n != mangled.TRUSTED and n != mangled.OFFERED)) self.expression_translator.assume_own_resources_stayed_constant(body, ctx, pos) for _, interface in ctx.program.interfaces.items(): with ctx.quantified_var_scope(): var_name = mangled.quantifier_var_name(names.INTERFACE) qvar = TranslatedVar(var_name, var_name, types.VYPER_ADDRESS, self.viper_ast) ctx.quantified_vars[var_name] = qvar self.expression_translator.implicit_resource_caller_private_expressions( interface, qvar.local_var(ctx), self_address, body, ctx) # For public function we can make further assumptions about msg.value if function.is_public(): msg_value = helpers.msg_value(self.viper_ast, ctx) if not function.is_payable(): # If the function is not payable we assume that msg.value == 0 # Technically speaking it is possible to send ether to a non-payable function # which leads to a revert, however, we implicitly require all function calls # to adhere to the Vyper function call interface (i.e., that they have the # correct types and ether). zero = self.viper_ast.IntLit(0) is_zero = self.viper_ast.EqCmp(msg_value, zero) payable_info = self.to_info(["Function is not payable"]) assume = self.viper_ast.Inhale(is_zero, info=payable_info) body.append(assume) else: # Increase balance by msg.value payable_info = self.to_info(["Function is payable"]) self.balance_translator.increase_balance(msg_value, body, ctx, info=payable_info) # Increase received for msg.sender by msg.value self.balance_translator.increase_received(msg_value, body, ctx) # Allocate the received ether to the sender if (ctx.program.config.has_option(names.CONFIG_ALLOCATION) and not ctx.program.config.has_option(names.CONFIG_NO_DERIVED_WEI)): resource = self.resource_translator.translate(None, body, ctx) # Wei resource self.allocation_translator.allocate_derived( function.node, resource, msg_sender, msg_sender, msg_value, body, ctx, pos) # If we are in a synthesized init, we don't have a function body if function.node: body_stmts = [] self.statement_translator.translate_stmts(function.node.body, body_stmts, ctx) self.seqn_with_info(body_stmts, "Function body", body) # If we reach this point we either jumped to it by returning or got there directly # because we didn't revert (yet) body.append(return_label) # Check that we were allowed to inhale the performs clauses body.extend(performs_clause_conditions) # Unset @nonreentrant locks self._set_locked(function, False, body, ctx) # Add variable for success(if_not=out_of_gas) that tracks whether the contract ran out of gas out_of_gas_var = helpers.out_of_gas_var(self.viper_ast) ctx.new_local_vars.append(out_of_gas_var) # Fail, if we ran out of gas # If the no_gas option is set, ignore it if not ctx.program.config.has_option(names.CONFIG_NO_GAS): self.fail_if(out_of_gas_var.localVar(), [], body, ctx) # If we reach this point do not revert the state body.append(self.viper_ast.Goto(mangled.END_LABEL)) # Revert the state label body.append(revert_label) # Return False body.append(return_bool(False)) # Havoc the return value if function.type.return_type: result_type = self.type_translator.translate(ctx.result_var.type, ctx) havoc = helpers.havoc_var(self.viper_ast, result_type, ctx) body.append(self.viper_ast.LocalVarAssign(ctx.result_var.local_var(ctx), havoc)) # Revert self and old_self to the state before the function self.state_translator.copy_state(ctx.pre_state, ctx.present_state, body, ctx) if function.is_private(): # In private functions the pre_state is not equal the old_state. For this we have the pre_old_state. # This is the case since for private function the pre_state may not be a public state. self.state_translator.copy_state(ctx.pre_old_state, ctx.old_state, body, ctx) else: self.state_translator.copy_state(ctx.pre_state, ctx.old_state, body, ctx) # The end of a program, label where return statements jump to body.append(end_label) # Postconditions hold for single transactions, checks hold before any public state, # invariants across transactions. # Therefore, after the function execution the following steps happen: # - Assert the specified postconditions of the function # - If the function is public # - Assert the checks # - Havoc self.balance # - Assert invariants # - Check accessible # This is necessary because a contract may receive additional money through # selfdestruct or mining # In init set old to current self, if this is the first public state # However, the state has to be set again after havocing the balance, therefore # we don't update the flag if is_init: self.state_translator.check_first_public_state(body, ctx, False) self.expression_translator.assume_contract_state(known_interface_ref, body, ctx, skip_caller_private=True) post_stmts = [] old_state = ctx.present_state if is_init else ctx.pre_state with ctx.state_scope(ctx.present_state, old_state): # Save model vars model_translator = self.model_translator.save_variables(post_stmts, ctx) # Assert postconditions for post in function.postconditions: post_pos = self.to_position(post, ctx, rules.POSTCONDITION_FAIL, modelt=model_translator) cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) post_assert = self.viper_ast.Exhale(cond, post_pos) post_stmts.append(post_assert) for post in chain(ctx.program.general_postconditions, ctx.program.transitive_postconditions): post_pos = self.to_position(post, ctx) cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) if is_init: init_pos = self.to_position(post, ctx, rules.POSTCONDITION_FAIL, modelt=model_translator) # General postconditions only have to hold for init if it succeeds cond = self.viper_ast.Implies(success_var, cond, post_pos) post_stmts.append(self.viper_ast.Assert(cond, init_pos)) else: via = [Via('general postcondition', post_pos)] func_pos = self.to_position(function.node, ctx, rules.POSTCONDITION_FAIL, via, model_translator) post_stmts.append(self.viper_ast.Assert(cond, func_pos)) # The postconditions of the interface the contract is supposed to implement for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] interface_func = interface.functions.get(function.name) if interface_func: postconditions = chain(interface_func.postconditions, interface.general_postconditions) else: postconditions = interface.general_postconditions for post in postconditions: post_pos = self.to_position(function.node or post, ctx) with ctx.program_scope(interface): cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) if is_init: cond = self.viper_ast.Implies(success_var, cond, post_pos) apos = self.to_position(function.node or post, ctx, rules.INTERFACE_POSTCONDITION_FAIL, modelt=model_translator) post_assert = self.viper_ast.Assert(cond, apos) post_stmts.append(post_assert) self.seqn_with_info(post_stmts, "Assert postconditions", body) # Checks and Invariants can be checked in the end of public functions # but not in the end of private functions if function.is_public(): # Assert checks # For the checks we need to differentiate between success and failure because we # on failure the assertion is evaluated in the old heap where events where not # inhaled yet checks_succ = [] checks_fail = [] for check in function.checks: check_pos = self.to_position(check, ctx, rules.CHECK_FAIL, modelt=model_translator) cond_succ = self.specification_translator.translate_check(check, checks_succ, ctx, False) checks_succ.append(self.viper_ast.Assert(cond_succ, check_pos)) # Checks do not have to hold if init fails if not is_init: cond_fail = self.specification_translator.translate_check(check, checks_fail, ctx, True) checks_fail.append(self.viper_ast.Assert(cond_fail, check_pos)) self.expression_translator.assert_caller_private(model_translator, checks_succ, ctx, [Via('end of function body', pos)]) for check in ctx.program.general_checks: cond_succ = self.specification_translator.translate_check(check, checks_succ, ctx, False) # If we are in the initializer we might have a synthesized __init__, therefore # just use always check as position, else use function as position and create # via to always check if is_init: check_pos = self.to_position(check, ctx, rules.CHECK_FAIL, modelt=model_translator) else: check_pos = self.to_position(check, ctx) via = [Via('check', check_pos)] check_pos = self.to_position(function.node, ctx, rules.CHECK_FAIL, via, model_translator) checks_succ.append(self.viper_ast.Assert(cond_succ, check_pos)) # Checks do not have to hold if __init__ fails if not is_init: cond_fail = self.specification_translator.translate_check(check, checks_fail, ctx, True) checks_fail.append(self.viper_ast.Assert(cond_fail, check_pos)) body.extend(helpers.flattened_conditional(self.viper_ast, success_var, checks_succ, checks_fail)) # Havoc self.balance self._havoc_balance(body, ctx) # In init set old to current self, if this is the first public state if is_init: self.state_translator.check_first_public_state(body, ctx, False) # Havoc other contract state self.state_translator.havoc_state_except_self(ctx.current_state, body, ctx) def assert_collected_invariants(collected_invariants) -> List[Expr]: invariant_assertions = [] # Assert collected invariants for invariant, invariant_condition in collected_invariants: invariant_pos = self.to_position(invariant, ctx) # If we have a synthesized __init__ we only create an # error message on the invariant if is_init: # Invariants do not have to hold if __init__ fails invariant_condition = self.viper_ast.Implies(success_var, invariant_condition, invariant_pos) assertion_pos = self.to_position(invariant, ctx, rules.INVARIANT_FAIL, modelt=invariant_model_translator) else: assertion_pos = self.to_position(function.node, ctx, rules.INVARIANT_FAIL, [Via('invariant', invariant_pos)], invariant_model_translator) invariant_assertions.append(self.viper_ast.Assert(invariant_condition, assertion_pos)) return invariant_assertions # Assert the invariants invariant_stmts = [] invariant_model_translator = self.model_translator.save_variables(invariant_stmts, ctx, pos) # Collect all local state invariants invariant_conditions = [] for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.local_state_invariants: cond = self.specification_translator.translate_invariant(inv, invariant_stmts, ctx, True) invariant_conditions.append((inv, cond)) for inv in ctx.current_program.local_state_invariants: # We ignore accessible here because we use a separate check cond = self.specification_translator.translate_invariant(inv, invariant_stmts, ctx, True) invariant_conditions.append((inv, cond)) invariant_stmts.extend(assert_collected_invariants(invariant_conditions)) self.seqn_with_info(invariant_stmts, "Assert Local State Invariants", body) self.expression_translator.assume_contract_state(known_interface_ref, body, ctx) # Collect all inter contract invariants invariant_stmts = [] invariant_conditions = [] for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] with ctx.program_scope(interface): for inv in ctx.current_program.inter_contract_invariants: cond = self.specification_translator.translate_invariant(inv, invariant_stmts, ctx, True) invariant_conditions.append((inv, cond)) for inv in ctx.current_program.inter_contract_invariants: # We ignore accessible here because we use a separate check cond = self.specification_translator.translate_invariant(inv, invariant_stmts, ctx, True) invariant_conditions.append((inv, cond)) invariant_stmts.extend(assert_collected_invariants(invariant_conditions)) self.seqn_with_info(invariant_stmts, "Assert Inter Contract Invariants", body) if is_init: derived_resources_invariants = [ self.viper_ast.Assert(self.viper_ast.Implies(success_var, expr, expr.pos()), expr.pos()) for expr in ctx.derived_resources_invariants(function.node)] else: derived_resources_invariants = [ self.viper_ast.Assert(expr, expr.pos()) for expr in ctx.derived_resources_invariants(function.node)] self.seqn_with_info(derived_resources_invariants, "Assert derived resource invariants", body) # We check that the invariant tracks all allocation by doing a leak check. # We also check that all necessary operations stated in perform clauses were # performed. if ctx.program.config.has_option(names.CONFIG_ALLOCATION): self.allocation_translator.function_leak_check(body, ctx, pos) # We check accessibility by inhaling a predicate in the corresponding function # and checking in the end that if it has been inhaled (i.e. if we want to prove # that some amount is a accessible) the amount has been sent to msg.sender # forall a: wei_value :: perm(accessible(tag, msg.sender, a, <args>)) > 0 ==> # success(if_not=out_of_gas or sender_failed) and # success() ==> sent(msg.sender) - old(sent(msg.sender)) >= a # The tag is used to differentiate between the different invariants the accessible # expressions occur in accessibles = [] for tag in function.analysis.accessible_tags: # It shouldn't be possible to write accessible for __init__ assert function.node tag_inv = ctx.program.analysis.inv_tags[tag] inv_pos = self.to_position(tag_inv, ctx) vias = [Via('invariant', inv_pos)] acc_pos = self.to_position(function.node, ctx, rules.INVARIANT_FAIL, vias, invariant_model_translator) wei_value_type = self.type_translator.translate(types.VYPER_WEI_VALUE, ctx) amount_var = self.viper_ast.LocalVarDecl('$a', wei_value_type, inv_pos) acc_name = mangled.accessible_name(function.name) tag_lit = self.viper_ast.IntLit(tag, inv_pos) msg_sender = helpers.msg_sender(self.viper_ast, ctx, inv_pos) amount_local = self.viper_ast.LocalVar('$a', wei_value_type, inv_pos) arg_vars = [arg.local_var(ctx, inv_pos) for arg in args.values()] acc_args = [tag_lit, msg_sender, amount_local, *arg_vars] acc_pred = self.viper_ast.PredicateAccess(acc_args, acc_name, inv_pos) acc_perm = self.viper_ast.CurrentPerm(acc_pred, inv_pos) pos_perm = self.viper_ast.GtCmp(acc_perm, self.viper_ast.NoPerm(inv_pos), inv_pos) sender_failed = helpers.check_call_failed(self.viper_ast, msg_sender, inv_pos) out_of_gas = helpers.out_of_gas_var(self.viper_ast, inv_pos).localVar() not_sender_failed = self.viper_ast.Not(self.viper_ast.Or(sender_failed, out_of_gas, inv_pos), inv_pos) succ_if_not = self.viper_ast.Implies(not_sender_failed, ctx.success_var.local_var(ctx, inv_pos), inv_pos) sent_to = self.balance_translator.get_sent(self_var, msg_sender, ctx, inv_pos) pre_sent_to = self.balance_translator.get_sent(pre_self_var, msg_sender, ctx, inv_pos) diff = self.viper_ast.Sub(sent_to, pre_sent_to, inv_pos) ge_sent_local = self.viper_ast.GeCmp(diff, amount_local, inv_pos) succ_impl = self.viper_ast.Implies(ctx.success_var.local_var(ctx, inv_pos), ge_sent_local, inv_pos) conj = self.viper_ast.And(succ_if_not, succ_impl, inv_pos) impl = self.viper_ast.Implies(pos_perm, conj, inv_pos) trigger = self.viper_ast.Trigger([acc_pred], inv_pos) forall = self.viper_ast.Forall([amount_var], [trigger], impl, inv_pos) accessibles.append(self.viper_ast.Assert(forall, acc_pos)) self.seqn_with_info(accessibles, "Assert accessibles", body) args_list = [arg.var_decl(ctx) for arg in args.values()] locals_list = [local.var_decl(ctx) for local in chain(local_vars.values(), state)] locals_list = [*locals_list, *ctx.new_local_vars] ret_list = [ret.var_decl(ctx) for ret in return_variables] viper_name = mangled.method_name(function.name) method = self.viper_ast.Method(viper_name, args_list, ret_list, [], [], locals_list, body, pos) if is_init and do_performs: ctx.program.config.options = [option for option in ctx.program.config.options if option != names.CONFIG_NO_PERFORMS] return method @staticmethod def can_assume_private_function(function: VyperFunction) -> bool: if function.postconditions or function.preconditions or function.checks: return True return False def inline(self, call: ast.ReceiverCall, args: List[Expr], res: List[Stmt], ctx: Context) -> Expr: function = ctx.program.functions[call.name] if function.is_pure(): return self._call_pure(call, args, res, ctx) elif self.can_assume_private_function(function): return self._assume_private_function(call, args, res, ctx) else: return self._inline(call, args, res, ctx) def _inline(self, call: ast.ReceiverCall, args: List[Expr], res: List[Stmt], ctx: Context) -> Expr: function = ctx.program.functions[call.name] call_pos = self.to_position(call, ctx) via = Via('inline', call_pos) with ctx.inline_scope(via, function): assert function.node # Only private self-calls are allowed in Vyper assert function.is_private() pos = self.to_position(function.node, ctx) body = [] # We keep the msg variable the same, as only msg.gas is allowed in the body of a private function. # In specifications we assume inline semantics, i.e., msg.sender and msg.value in the inlined function # correspond to msg.sender and msg.value in the caller function. self._generate_arguments_as_local_vars(function, args, body, pos, ctx) # Define return var if function.type.return_type: ret_name = ctx.inline_prefix + mangled.RESULT_VAR ctx.result_var = TranslatedVar(names.RESULT, ret_name, function.type.return_type, self.viper_ast, pos) ctx.new_local_vars.append(ctx.result_var.var_decl(ctx, pos)) ret_var = ctx.result_var.local_var(ctx, pos) else: ret_var = None # Define return label for inlined return statements return_label_name = ctx.inline_prefix + mangled.RETURN_LABEL return_label = self.viper_ast.Label(return_label_name) ctx.return_label = return_label_name old_state_for_postconditions = ctx.current_state if not function.is_constant(): # Create pre_state for private function def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) old_state_for_postconditions = self.state_translator.state(inlined_pre_state, ctx) for val in old_state_for_postconditions.values(): ctx.new_local_vars.append(val.var_decl(ctx, pos)) # Copy present state to this created pre_state self.state_translator.copy_state(ctx.current_state, old_state_for_postconditions, res, ctx) # Revert if a @nonreentrant lock is set self._assert_unlocked(function, body, ctx) # Set @nonreentrant locks self._set_locked(function, True, body, ctx) # Translate body self.statement_translator.translate_stmts(function.node.body, body, ctx) # Unset @nonreentrant locks self._set_locked(function, False, body, ctx) post_stmts = [] with ctx.state_scope(ctx.current_state, old_state_for_postconditions): for post in chain(ctx.program.general_postconditions, ctx.program.transitive_postconditions): cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) post_pos = self.to_position(post, ctx, rules.POSTCONDITION_FAIL, values={'function': function}) post_stmts.append(self.viper_ast.Assert(cond, post_pos)) for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] postconditions = interface.general_postconditions for post in postconditions: with ctx.program_scope(interface): cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) post_pos = self.to_position(post, ctx, rules.POSTCONDITION_FAIL, values={'function': function}) post_stmts.append(self.viper_ast.Inhale(cond, post_pos)) self.seqn_with_info(post_stmts, f"Assert general postconditions", body) self.seqn_with_info(body, f"Inlined call of {function.name}", res) res.append(return_label) return ret_var def _call_pure(self, call: ast.ReceiverCall, args: List[Expr], res: List[Expr], ctx: Context) -> Expr: function = ctx.program.functions[call.name] function_args = args.copy() for (name, _), arg in zip_longest(function.args.items(), args): if not arg: function_args.append(self.expression_translator.translate(function.defaults[name], res, ctx)) function = ctx.program.functions[call.name] return_type = self.viper_ast.Bool if function.type.return_type: return_type = self.type_translator.translate(function.type.return_type, ctx) mangled_name = mangled.pure_function_name(call.name) call_pos = self.to_position(call, ctx) via = Via('pure function call', call_pos) pos = self.to_position(function.node, ctx, vias=[via]) func_app = self.viper_ast.FuncApp(mangled_name, [ctx.self_var.local_var(ctx), *function_args], pos, type=helpers.struct_type(self.viper_ast)) called_success_var = helpers.struct_pure_get_success(self.viper_ast, func_app, pos) called_result_var = helpers.struct_pure_get_result(self.viper_ast, func_app, return_type, pos) self.fail_if(self.viper_ast.Not(called_success_var), [], res, ctx, pos) return called_result_var def _assume_private_function(self, call: ast.ReceiverCall, args: List[Expr], res: List[Stmt], ctx: Context) -> Expr: # Assume private functions are translated as follows: # - Evaluate arguments # - Define return variable # - Define new_success variable # - Check precondition # - Forget about all events # - The next steps are only necessary if the function is not constant: # - Create new state which corresponds to the pre_state of the private function call # - Havoc self and contracts # - Havoc old_self and old_contracts # - Assume type assumptions for self and old_self # - Assume invariants (where old and present refers to the havoced old state) # - Check that private function has stronger "check"s # - Assume postconditions (where old refers to present state, if the function is constant or # else to the newly create pre_state) # - Fail if not new_success # - Wrap integers to $Int if the function has a numeric return type function = ctx.program.functions[call.name] call_pos = self.to_position(call, ctx) via = Via('private function call', call_pos) with ctx.inline_scope(via): assert function.node # Only private self-calls are allowed in Vyper assert function.is_private() pos = self.to_position(function.node, ctx) args_as_local_vars = [] self._generate_arguments_as_local_vars(function, args, args_as_local_vars, pos, ctx) self.seqn_with_info(args_as_local_vars, "Arguments of private function call", res) # Define success var succ_name = ctx.inline_prefix + mangled.SUCCESS_VAR ctx.success_var = TranslatedVar(names.SUCCESS, succ_name, types.VYPER_BOOL, self.viper_ast, pos) ctx.new_local_vars.append(ctx.success_var.var_decl(ctx, pos)) success_var = ctx.success_var.local_var(ctx, pos) # Define return var if function.type.return_type: ret_name = ctx.inline_prefix + mangled.RESULT_VAR ctx.result_var = TranslatedVar(names.RESULT, ret_name, function.type.return_type, self.viper_ast, pos) ctx.new_local_vars.append(ctx.result_var.var_decl(ctx, pos)) ret_var = ctx.result_var.local_var(ctx, pos) else: ret_var = None # Check preconditions pre_stmts = [] with ctx.state_scope(ctx.current_state, ctx.current_old_state): for precondition in function.preconditions: cond = self.specification_translator.translate_pre_or_postcondition(precondition, pre_stmts, ctx) pre_pos = self.to_position(precondition, ctx, rules.PRECONDITION_FAIL, values={'function': function}) pre_stmts.append(self.viper_ast.Exhale(cond, pre_pos)) self.seqn_with_info(pre_stmts, "Check preconditions", res) # We forget about events by exhaling all permissions to the event predicates # and then inhale an unspecified permission amount. event_handling = [] self.expression_translator.forget_about_all_events(event_handling, ctx, pos) self.expression_translator.log_all_events_zero_or_more_times(event_handling, ctx, pos) self.seqn_with_info(event_handling, "Assume we know nothing about events", res) old_state_for_postconditions = ctx.current_state if not function.is_constant(): # Create pre_state for private function def inlined_pre_state(name: str) -> str: return ctx.inline_prefix + mangled.pre_state_var_name(name) old_state_for_postconditions = self.state_translator.state(inlined_pre_state, ctx) for val in old_state_for_postconditions.values(): ctx.new_local_vars.append(val.var_decl(ctx, pos)) # Copy present state to this created pre_state self.state_translator.copy_state(ctx.current_state, old_state_for_postconditions, res, ctx) self.state_translator.havoc_old_and_current_state(self.specification_translator, res, ctx, pos) private_function_checks_conjunction = self.viper_ast.TrueLit(pos) for check in function.checks: cond = self.specification_translator.translate_check(check, res, ctx) private_function_checks_conjunction = self.viper_ast.And(private_function_checks_conjunction, cond, pos) check_stmts = [] for check in ctx.function.checks: check_cond = self.specification_translator.translate_check(check, res, ctx) check_pos = self.to_position(check, ctx, rules.PRIVATE_CALL_CHECK_FAIL) cond = self.viper_ast.Implies(private_function_checks_conjunction, check_cond, check_pos) check_stmts.append(self.viper_ast.Assert(cond, check_pos)) self.seqn_with_info(check_stmts, "Check strength of checks of private function", res) post_stmts = [] with ctx.state_scope(ctx.current_state, old_state_for_postconditions): # Assume postconditions for post in function.postconditions: cond = self.specification_translator.\ translate_pre_or_postcondition(post, post_stmts, ctx, assume_events=True) post_pos = self.to_position(post, ctx, rules.INHALE_POSTCONDITION_FAIL) post_stmts.append(self.viper_ast.Inhale(cond, post_pos)) for post in chain(ctx.program.general_postconditions, ctx.program.transitive_postconditions): cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) post_pos = self.to_position(post, ctx, rules.INHALE_POSTCONDITION_FAIL) post_stmts.append(self.viper_ast.Inhale(cond, post_pos)) for interface_type in ctx.program.implements: interface = ctx.program.interfaces[interface_type.name] postconditions = interface.general_postconditions for post in postconditions: with ctx.program_scope(interface): cond = self.specification_translator.translate_pre_or_postcondition(post, post_stmts, ctx) post_pos = self.to_position(post, ctx, rules.INHALE_POSTCONDITION_FAIL) post_stmts.append(self.viper_ast.Inhale(cond, post_pos)) self.seqn_with_info(post_stmts, "Assume postconditions", res) self.fail_if(self.viper_ast.Not(success_var), [], res, ctx, call_pos) if (types.is_numeric(function.type.return_type) and self.expression_translator.arithmetic_translator.is_unwrapped(ret_var)): ret_var = helpers.w_wrap(self.viper_ast, ret_var) return ret_var def _generate_arguments_as_local_vars(self, function, args, res, pos, ctx): # Add arguments to local vars, assign passed args or default argument for (name, var), arg in zip_longest(function.args.items(), args): apos = self.to_position(var.node, ctx) translated_arg = self._translate_var(var, ctx, True) ctx.args[name] = translated_arg if not arg: arg = self.expression_translator.translate(function.defaults[name], res, ctx) lhs = translated_arg.local_var(ctx) if (types.is_numeric(translated_arg.type) and self.expression_translator.arithmetic_translator.is_wrapped(arg) and self.expression_translator.arithmetic_translator.is_unwrapped(lhs)): translated_arg.is_local = False lhs = translated_arg.local_var(ctx) elif (types.is_numeric(translated_arg.type) and self.expression_translator.arithmetic_translator.is_unwrapped(arg) and self.expression_translator.arithmetic_translator.is_wrapped(lhs)): arg = helpers.w_wrap(self.viper_ast, arg) elif (not types.is_numeric(translated_arg.type) and self.expression_translator.arithmetic_translator.is_wrapped(arg)): arg = helpers.w_unwrap(self.viper_ast, arg) ctx.new_local_vars.append(translated_arg.var_decl(ctx, pos)) res.append(self.viper_ast.LocalVarAssign(lhs, arg, apos)) def _translate_var(self, var: VyperVar, ctx: Context, is_local: bool): pos = self.to_position(var.node, ctx) name = mangled.local_var_name(ctx.inline_prefix, var.name) return TranslatedVar(var.name, name, var.type, self.viper_ast, pos, is_local=is_local) def _assume_non_negative(self, var, res: List[Stmt]): zero = self.viper_ast.IntLit(0) gez = self.viper_ast.GeCmp(var, zero) res.append(self.viper_ast.Inhale(gez)) def _havoc_balance(self, res: List[Stmt], ctx: Context): balance_type = ctx.field_types[names.ADDRESS_BALANCE] havoc = helpers.havoc_var(self.viper_ast, balance_type, ctx) self._assume_non_negative(havoc, res) self.balance_translator.increase_balance(havoc, res, ctx) def _assert_unlocked(self, function: VyperFunction, res: List[Stmt], ctx: Context): keys = function.nonreentrant_keys() locked = [helpers.get_lock(self.viper_ast, key, ctx) for key in keys] if locked: cond = reduce(self.viper_ast.Or, locked) self.fail_if(cond, [], res, ctx) def _set_locked(self, function: VyperFunction, value: bool, res: List[Stmt], ctx: Context): keys = function.nonreentrant_keys() self_var = ctx.self_var.local_var(ctx) def set_lock(key): return helpers.set_lock(self.viper_ast, key, value, ctx) res.extend(self.viper_ast.LocalVarAssign(self_var, set_lock(key)) for key in keys)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/function.py
function.py
import functools import inspect from typing import Optional, Union from collections.abc import Iterable from twovyper.translation import helpers from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr def wrapped_integer_decorator(*possible_wrapped_integer_inputs: str, wrap_output=False, store_unwrap_info=True): """ This decorator can be used to automatically unwrap $Int to Int. All functions, predicates, axioms and operators on Int are only available to Int and not $Int. With this decorator, all these functions, predicates, axioms and operators on Int can also be used for $Int. This decorator also stores the information if it unwrapped an expression or it wraps a resulting Int again to a $Int. :param possible_wrapped_integer_inputs: The names of arguments that may contain $Int typed expressions :param wrap_output: A flag if the output should always be considered to be a $Int (Not only if an input was a $Int) :param store_unwrap_info: A boolean Flag, if false then the output gets wrapped if the output is considered as a $Int. If true then only the :attr:`WrappedViperAST.unwrapped_some_expressions` flag gets set. """ def _decorator(func): (arg_names, _, _, _, _, _, _) = inspect.getfullargspec(func) pos_names = {"position", "pos"} info_names = {"info"} assert pos_names.isdisjoint(possible_wrapped_integer_inputs),\ 'The "position" argument cannot contain wrapped integers.' assert info_names.isdisjoint(possible_wrapped_integer_inputs),\ 'The "info" argument cannot contain wrapped integers.' assert wrap_output or len(possible_wrapped_integer_inputs) > 0,\ 'The decorator is not necessary here.' pos_index = -1 info_index = -1 possible_wrapped_integer_inputs_indices = [] for idx, arg_n in enumerate(arg_names): if arg_n in pos_names: assert pos_index == -1 pos_index = idx elif arg_n in info_names: assert info_index == -1 info_index = idx elif arg_n in possible_wrapped_integer_inputs: possible_wrapped_integer_inputs_indices.append(idx) assert pos_index != -1, 'Could not find the "position" argument.' assert info_index != -1, 'Could not find the "info" argument.' assert len(possible_wrapped_integer_inputs_indices) == len(possible_wrapped_integer_inputs),\ 'Some of the argument names of the decorator could not be found.' possible_wrapped_integers = list(zip(possible_wrapped_integer_inputs_indices, possible_wrapped_integer_inputs)) wrapped_int_type = None @functools.wraps(func) def _wrapper(*args, **kwargs): new_args = list(args) new_kwargs = dict(kwargs) _self = args[0] assert isinstance(_self, WrappedViperAST) nonlocal wrapped_int_type if wrapped_int_type is None: wrapped_int_type = helpers.wrapped_int_type(_self.viper_ast) had_wrapped_integers = wrap_output provided_arg_length = len(args) kwarg_names = set(kwargs.keys()) pos = None info = None # Search for position and info arguments if pos_index < provided_arg_length: pos = args[pos_index] elif not kwarg_names.isdisjoint(pos_names): pos = next((kwargs[arg_name] for arg_name in pos_names if arg_name in kwargs)) if info_index < provided_arg_length: info = args[info_index] elif not kwarg_names.isdisjoint(info_names): info = next((kwargs[arg_name] for arg_name in info_names if arg_name in kwargs)) def unwrap(a: Expr) -> Expr: if hasattr(a, 'isSubtype') and a.isSubtype(wrapped_int_type): nonlocal had_wrapped_integers had_wrapped_integers = True return helpers.w_unwrap(_self.viper_ast, a, pos, info) return a def wrap(a: Expr) -> Expr: if hasattr(a, 'isSubtype') and a.isSubtype(_self.viper_ast.Int): return helpers.w_wrap(_self.viper_ast, a, pos, info) return a # Unwrap wrapped integers for index, arg_name in possible_wrapped_integers: arg: Optional[Union[Expr, Iterable]] = None if index < provided_arg_length: arg = args[index] elif arg_name in kwarg_names: arg = kwargs[arg_name] if arg is not None: new_arg = [unwrap(a) for a in arg] if isinstance(arg, Iterable) else unwrap(arg) if index < provided_arg_length: new_args[index] = new_arg else: # There are only two ways to get "arg" and the first one was not it. new_kwargs[arg_name] = new_arg # Call ast function value = func(*new_args, **new_kwargs) # Wrap output if one or more inputs were wrapped if had_wrapped_integers: if store_unwrap_info: _self.unwrapped_some_expressions = True else: value = wrap(value) return value return _wrapper return _decorator class WrappedViperAST(ViperAST): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast.jvm) self.viper_ast = viper_ast self.unwrapped_some_expressions = False @wrapped_integer_decorator("args") def PredicateAccess(self, args, pred_name, position=None, info=None): return super().PredicateAccess(args, pred_name, position, info) @wrapped_integer_decorator("args") def DomainFuncApp(self, func_name, args, type_passed, position, info, domain_name, type_var_map=None): if type_var_map is None: type_var_map = {} return super().DomainFuncApp(func_name, args, type_passed, position, info, domain_name, type_var_map) @wrapped_integer_decorator("expr") def Minus(self, expr, position=None, info=None): return super().Minus(expr, position, info) @wrapped_integer_decorator("then", "els") def CondExp(self, cond, then, els, position=None, info=None): return super().CondExp(cond, then, els, position, info) @wrapped_integer_decorator("left", "right") def EqCmp(self, left, right, position=None, info=None): return super().EqCmp(left, right, position, info) @wrapped_integer_decorator("left", "right") def NeCmp(self, left, right, position=None, info=None): return super().NeCmp(left, right, position, info) @wrapped_integer_decorator("left", "right") def GtCmp(self, left, right, position=None, info=None): return super().GtCmp(left, right, position, info) @wrapped_integer_decorator("left", "right") def GeCmp(self, left, right, position=None, info=None): return super().GeCmp(left, right, position, info) @wrapped_integer_decorator("left", "right") def LtCmp(self, left, right, position=None, info=None): return super().LtCmp(left, right, position, info) @wrapped_integer_decorator("left", "right") def LeCmp(self, left, right, position=None, info=None): return super().LeCmp(left, right, position, info) @wrapped_integer_decorator("args", wrap_output=True) def FuncApp(self, name, args, position=None, info=None, type=None): return super().FuncApp(name, args, position, info, type) @wrapped_integer_decorator("elems") def ExplicitSeq(self, elems, position=None, info=None): return super().ExplicitSeq(elems, position, info) @wrapped_integer_decorator("elems") def ExplicitSet(self, elems, position=None, info=None): return super().ExplicitSet(elems, position, info) @wrapped_integer_decorator("elems") def ExplicitMultiset(self, elems, position=None, info=None): return super().ExplicitMultiset(elems, position, info) @wrapped_integer_decorator("right") def SeqAppend(self, left, right, position=None, info=None): return super().SeqAppend(left, right, position, info) @wrapped_integer_decorator("elem") def SeqContains(self, elem, s, position=None, info=None): return super().SeqContains(elem, s, position, info) @wrapped_integer_decorator("ind") def SeqIndex(self, s, ind, position=None, info=None): return super().SeqIndex(s, ind, position, info) @wrapped_integer_decorator("end") def SeqTake(self, s, end, position=None, info=None): return super().SeqTake(s, end, position, info) @wrapped_integer_decorator("end") def SeqDrop(self, s, end, position=None, info=None): return super().SeqDrop(s, end, position, info) @wrapped_integer_decorator("ind", "elem") def SeqUpdate(self, s, ind, elem, position=None, info=None): return super().SeqUpdate(s, ind, elem, position, info) @wrapped_integer_decorator("left", "right") def Add(self, left, right, position=None, info=None): return super().Add(left, right, position, info) @wrapped_integer_decorator("left", "right") def Sub(self, left, right, position=None, info=None): return super().Sub(left, right, position, info) @wrapped_integer_decorator("left", "right") def Mul(self, left, right, position=None, info=None): return super().Mul(left, right, position, info) @wrapped_integer_decorator("left", "right") def Div(self, left, right, position=None, info=None): return super().Div(left, right, position, info) @wrapped_integer_decorator("left", "right") def Mod(self, left, right, position=None, info=None): return super().Mod(left, right, position, info)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/wrapped_viper_ast.py
wrapped_viper_ast.py
from collections import ChainMap from contextlib import contextmanager from functools import reduce from itertools import chain, starmap, zip_longest from typing import List, Optional, Iterable from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.nodes import VyperInterface from twovyper.ast.types import VyperType from twovyper.ast.visitors import NodeVisitor from twovyper.translation import helpers, mangled from twovyper.translation.context import Context from twovyper.translation.allocation import AllocationTranslator from twovyper.translation.expression import ExpressionTranslator from twovyper.translation.resource import ResourceTranslator from twovyper.translation.variable import TranslatedVar from twovyper.utils import switch, first from twovyper.verification import rules from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt class SpecificationTranslator(ExpressionTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.allocation_translator = AllocationTranslator(viper_ast) self.resource_translator = ResourceTranslator(viper_ast) self._assume_events = False self._translating_check = False self._caller_private_condition = None @property def no_reverts(self): return True @contextmanager def _ignore_accessible_scope(self, ignore: bool): self._ignore_accessible = ignore yield del self._ignore_accessible @contextmanager def _event_translation_scope(self, assume_events: bool): assume = self._assume_events self._assume_events = assume_events yield self._assume_events = assume @contextmanager def _check_translation_scope(self): translating_check = self._translating_check self._translating_check = True yield self._translating_check = translating_check def translate_pre_or_postcondition(self, cond: ast.Node, res: List[Stmt], ctx: Context, assume_events=False) -> Expr: with self._event_translation_scope(assume_events): expr = self.translate(cond, res, ctx) return expr def translate_check(self, check: ast.Node, res: List[Stmt], ctx: Context, is_fail=False) -> Expr: with self._check_translation_scope(): expr = self.translate(check, res, ctx) if is_fail: # We evaluate the check on failure in the old heap because events didn't # happen there pos = self.to_position(check, ctx) return self.viper_ast.Old(expr, pos) else: return expr def translate_invariant(self, inv: ast.Node, res: List[Stmt], ctx: Context, ignore_accessible=False) -> Expr: with self._ignore_accessible_scope(ignore_accessible): return self.translate(inv, res, ctx) def translate_caller_private(self, expr: ast.Expr, ctx: Context) -> (Expr, Expr): self._caller_private_condition = self.viper_ast.TrueLit() caller_private_expr = self._translate_spec(expr, ctx) return self._caller_private_condition, caller_private_expr def _translate_spec(self, node: ast.Node, ctx: Context) -> Expr: stmts = [] expr = self.translate(node, stmts, ctx) assert not stmts return expr def _translate_quantified_vars(self, node: ast.Dict, ctx: Context) -> (List[TranslatedVar], List[Expr]): quants = [] type_assumptions = [] # The first argument to forall is the variable declaration dict for var_name in node.keys: name_pos = self.to_position(var_name, ctx) qname = mangled.quantifier_var_name(var_name.id) qvar = TranslatedVar(var_name.id, qname, var_name.type, self.viper_ast, name_pos) tassps = self.type_translator.type_assumptions(qvar.local_var(ctx), qvar.type, ctx) type_assumptions.extend(tassps) quants.append(qvar) return quants, type_assumptions def translate_FunctionCall(self, node: ast.FunctionCall, res: List[Stmt], ctx: Context) -> Expr: pos = self.to_position(node, ctx) name = node.name if name == names.IMPLIES: lhs = self.translate(node.args[0], res, ctx) rhs = self.translate(node.args[1], res, ctx) return self.viper_ast.Implies(lhs, rhs, pos) elif name == names.FORALL: with ctx.quantified_var_scope(): num_args = len(node.args) assert len(node.args) > 0 dict_arg = node.args[0] assert isinstance(dict_arg, ast.Dict) # The first argument to forall is the variable declaration dict quants, type_assumptions = self._translate_quantified_vars(dict_arg, ctx) # Add the quantified variables to the context for var in quants: ctx.quantified_vars[var.name] = var # The last argument to forall is the quantified expression expr = self._translate_spec(node.args[num_args - 1], ctx) # We need to assume the type assumptions for the quantified variables def chain(assumptions): assumption, *rest = assumptions if rest: return self.viper_ast.And(assumption, chain(rest), pos) else: return assumption if type_assumptions: assumption_exprs = chain(type_assumptions) expr = self.viper_ast.Implies(assumption_exprs, expr, pos) # The arguments in the middle are the triggers triggers = [] with ctx.inside_trigger_scope(): for arg in node.args[1: num_args - 1]: trigger_pos = self.to_position(arg, ctx) trigger_exprs = [self._translate_spec(t, ctx) for t in arg.elements] trigger = self.viper_ast.Trigger(trigger_exprs, trigger_pos) triggers.append(trigger) quant_var_decls = [var.var_decl(ctx) for var in quants] return self.viper_ast.Forall(quant_var_decls, triggers, expr, pos) elif name == names.RESULT: if node.args: call = node.args[0] assert isinstance(call, ast.ReceiverCall) func = ctx.program.functions[call.name] viper_result_type = self.type_translator.translate(func.type.return_type, ctx) mangled_name = mangled.pure_function_name(call.name) pos = self.to_position(call, ctx, rules=rules.PURE_FUNCTION_FAIL, values={'function': func}) function_args = call.args.copy() for (name, _), arg in zip_longest(func.args.items(), call.args): if not arg: function_args.append(func.defaults[name]) args = [self.translate(arg, res, ctx) for arg in [call.receiver] + function_args] func_app = self.viper_ast.FuncApp(mangled_name, args, pos, type=helpers.struct_type(self.viper_ast)) result_func_app = self.viper_ast.FuncApp(mangled.PURE_RESULT, [func_app], pos, type=self.viper_ast.Int) domain = mangled.STRUCT_OPS_DOMAIN getter = mangled.STRUCT_GET type_map = {self.viper_ast.TypeVar(mangled.STRUCT_OPS_VALUE_VAR): viper_result_type} result = self.viper_ast.DomainFuncApp(getter, [result_func_app], viper_result_type, pos, None, domain_name=domain, type_var_map=type_map) if node.keywords: success = self._translate_pure_success(node, res, ctx, pos) default = self.translate(node.keywords[0].value, res, ctx) return self.viper_ast.CondExp(success, result, default, pos) else: return result else: return ctx.result_var.local_var(ctx, pos) elif name == names.SUCCESS: # The syntax for success is one of the following # - success() # - success(if_not=expr) # - success(pure_function_call) # where expr can be a disjunction of conditions success = None if node.args else ctx.success_var.local_var(ctx, pos) if node.keywords: conds = set() def collect_conds(n: ast.Node): if isinstance(n, ast.Name): conds.add(n.id) elif isinstance(n, ast.BoolOp): collect_conds(n.left) collect_conds(n.right) args = node.keywords[0].value collect_conds(args) # noinspection PyShadowingNames def translate_condition(success_condition): with switch(success_condition) as case: if case(names.SUCCESS_OVERFLOW): var = helpers.overflow_var(self.viper_ast, pos) elif case(names.SUCCESS_OUT_OF_GAS): var = helpers.out_of_gas_var(self.viper_ast, pos) elif case(names.SUCCESS_SENDER_FAILED): msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) out_of_gas_expr = helpers.out_of_gas_var(self.viper_ast, pos).localVar() call_failed_expr = helpers.check_call_failed(self.viper_ast, msg_sender, pos) return self.viper_ast.Or(out_of_gas_expr, call_failed_expr, pos) else: assert False return var.localVar() or_conds = [translate_condition(c) for c in conds] or_op = reduce(lambda l, r: self.viper_ast.Or(l, r, pos), or_conds) not_or_op = self.viper_ast.Not(or_op, pos) return self.viper_ast.Implies(not_or_op, success, pos) elif node.args: return self._translate_pure_success(node, res, ctx, pos) else: return success elif name == names.REVERT: if node.args: call = node.args[0] assert isinstance(call, ast.ReceiverCall) func = ctx.program.functions[call.name] mangled_name = mangled.pure_function_name(call.name) function_args = call.args.copy() for (name, _), arg in zip_longest(func.args.items(), call.args): if not arg: function_args.append(func.defaults[name]) args = [self.translate(arg, res, ctx) for arg in [call.receiver] + function_args] func_app = self.viper_ast.FuncApp(mangled_name, args, pos, type=helpers.struct_type(self.viper_ast)) success = self.viper_ast.FuncApp(mangled.PURE_SUCCESS, [func_app], pos, type=self.viper_ast.Bool) else: success = ctx.success_var.local_var(ctx, pos) return self.viper_ast.Not(success, pos) elif name == names.PREVIOUS: arg = node.args[0] assert isinstance(arg, ast.Name) assert ctx.loop_arrays.get(arg.id) assert ctx.loop_indices.get(arg.id) array = ctx.loop_arrays[arg.id] end = ctx.loop_indices[arg.id].local_var(ctx) return self.viper_ast.SeqTake(array, end, pos) elif name == names.LOOP_ARRAY: arg = node.args[0] assert isinstance(arg, ast.Name) assert ctx.loop_arrays.get(arg.id) return ctx.loop_arrays[arg.id] elif name == names.LOOP_ITERATION: arg = node.args[0] assert isinstance(arg, ast.Name) assert ctx.loop_indices.get(arg.id) return ctx.loop_indices[arg.id].local_var(ctx) elif name == names.OLD or name == names.ISSUED or name == names.PUBLIC_OLD: with switch(name) as case: if case(names.OLD): self_state = ctx.current_old_state elif case(names.PUBLIC_OLD): self_state = ctx.old_state elif case(names.ISSUED): self_state = ctx.issued_state else: assert False with ctx.state_scope(self_state, self_state): if name == names.OLD: ctx.locals = ChainMap(ctx.old_locals, ctx.locals) arg = node.args[0] return self.translate(arg, res, ctx) elif name == names.SUM: arg = node.args[0] expr = self.translate(arg, res, ctx) if isinstance(arg.type, types.MapType): key_type = self.type_translator.translate(arg.type.key_type, ctx) return helpers.map_sum(self.viper_ast, expr, key_type, pos) elif isinstance(arg.type, types.ArrayType): if isinstance(arg, ast.FunctionCall): if (arg.name == names.RANGE and hasattr(expr, "getArgs")): range_args = expr.getArgs() func_app = self.viper_ast.FuncApp(mangled.RANGE_SUM, [], pos, type=self.viper_ast.Int) return func_app.withArgs(range_args) elif arg.name == names.PREVIOUS: loop_var = arg.args[0] loop_array = ctx.loop_arrays.get(loop_var.id) if (hasattr(loop_array, "funcname") and hasattr(loop_array, "getArgs") and loop_array.funcname() == mangled.RANGE_RANGE): lower_arg = loop_array.getArgs().head() loop_idx = ctx.loop_indices[loop_var.id].local_var(ctx) upper_arg = self.viper_ast.SeqIndex(loop_array, loop_idx, pos) range_args = self.viper_ast.to_seq([lower_arg, upper_arg]) func_app = self.viper_ast.FuncApp(mangled.RANGE_SUM, [], pos, type=self.viper_ast.Int) return func_app.withArgs(range_args) int_lit_zero = self.viper_ast.IntLit(0, pos) sum_value = int_lit_zero for i in range(arg.type.size): int_lit_i = self.viper_ast.IntLit(i, pos) array_at = self.viper_ast.SeqIndex(expr, int_lit_i, pos) if arg.type.is_strict: value = array_at else: seq_length = self.viper_ast.SeqLength(expr, pos) cond = self.viper_ast.LtCmp(int_lit_i, seq_length, pos) value = self.viper_ast.CondExp(cond, array_at, int_lit_zero, pos) sum_value = self.viper_ast.Add(sum_value, value, pos) return sum_value else: assert False elif name == names.TUPLE: tuple_var = helpers.havoc_var(self.viper_ast, helpers.struct_type(self.viper_ast), ctx) for idx, element in enumerate(node.args): viper_type = self.type_translator.translate(element.type, ctx) value = self.translate(element, res, ctx) tuple_var = helpers.struct_set_idx(self.viper_ast, tuple_var, value, idx, viper_type, pos) return tuple_var elif name == names.LOCKED: lock_name = node.args[0].s return helpers.get_lock(self.viper_ast, lock_name, ctx, pos) elif name == names.STORAGE: args = node.args # We translate storage(self) just as the self variable, otherwise we look up # the struct in the contract state map arg = self.translate(args[0], res, ctx) contracts = ctx.current_state[mangled.CONTRACTS].local_var(ctx) key_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) value_type = helpers.struct_type(self.viper_ast) get_storage = helpers.map_get(self.viper_ast, contracts, arg, key_type, value_type) self_address = helpers.self_address(self.viper_ast, pos) eq = self.viper_ast.EqCmp(arg, self_address) self_var = ctx.self_var.local_var(ctx, pos) if ctx.inside_trigger: return get_storage else: return self.viper_ast.CondExp(eq, self_var, get_storage, pos) elif name == names.RECEIVED: self_var = ctx.self_var.local_var(ctx) if node.args: arg = self.translate(node.args[0], res, ctx) return self.balance_translator.get_received(self_var, arg, ctx, pos) else: return self.balance_translator.received(self_var, ctx, pos) elif name == names.SENT: self_var = ctx.self_var.local_var(ctx) if node.args: arg = self.translate(node.args[0], res, ctx) return self.balance_translator.get_sent(self_var, arg, ctx, pos) else: return self.balance_translator.sent(self_var, ctx, pos) elif name == names.INTERPRETED: with ctx.interpreted_scope(): interpreted_arg = self.translate(node.args[0], res, ctx) res.append(self.viper_ast.Assert(interpreted_arg, pos)) uninterpreted_arg = self.translate(node.args[0], res, ctx) res.append(self.viper_ast.Inhale(uninterpreted_arg, pos)) with ctx.lemma_scope(is_inside=False): with ctx.interpreted_scope(is_inside=False): uninterpreted_arg = self.translate(node.args[0], res, ctx) res.append(self.viper_ast.Inhale(uninterpreted_arg, pos)) return self.viper_ast.TrueLit(pos) elif name == names.CONDITIONAL: self._caller_private_condition = self.translate(node.args[0], res, ctx) return self.translate(node.args[1], res, ctx) elif name == names.ALLOCATED: resource = self.resource_translator.translate(node.resource, res, ctx) allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx) if node.args: address = self.translate(node.args[0], res, ctx) return self.allocation_translator.get_allocated(allocated, resource, address, ctx) else: return self.allocation_translator.get_allocated_map(allocated, resource, ctx, pos) elif name == names.OFFERED: from_resource, to_resource = self.resource_translator.translate_exchange(node.resource, res, ctx) offered = ctx.current_state[mangled.OFFERED].local_var(ctx) args = [self.translate(arg, res, ctx) for arg in node.args] return self.allocation_translator.get_offered(offered, from_resource, to_resource, *args, ctx, pos) elif name == names.NO_OFFERS: offered = ctx.current_state[mangled.OFFERED].local_var(ctx) resource = self.resource_translator.translate(node.resource, res, ctx) address = self.translate(node.args[0], res, ctx) return helpers.no_offers(self.viper_ast, offered, resource, address, pos) elif name == names.ALLOWED_TO_DECOMPOSE: resource, underlying_resource = self.resource_translator.translate_with_underlying(node, res, ctx) offered = ctx.current_state[mangled.OFFERED].local_var(ctx) const_one = self.viper_ast.IntLit(1, pos) address = self.translate(node.args[0], res, ctx) return self.allocation_translator.get_offered(offered, resource, underlying_resource, const_one, const_one, address, address, ctx, pos) elif name == names.TRUSTED: address = self.translate(node.args[0], res, ctx) by = None where = ctx.self_address or helpers.self_address(self.viper_ast, pos) for kw in node.keywords: if kw.name == names.TRUSTED_BY: by = self.translate(kw.value, res, ctx) elif kw.name == names.TRUSTED_WHERE: where = self.translate(kw.value, res, ctx) assert by is not None trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx) return self.allocation_translator.get_trusted(trusted, where, address, by, ctx, pos) elif name == names.TRUST_NO_ONE: trusted = ctx.current_state[mangled.TRUSTED].local_var(ctx) address = self.translate(node.args[0], res, ctx) where = self.translate(node.args[1], res, ctx) return helpers.trust_no_one(self.viper_ast, trusted, address, where, pos) elif name == names.ACCESSIBLE: # The function necessary for accessible is either the one used as the third argument # or the one the heuristics determined if len(node.args) == 2: func_name = ctx.program.analysis.accessible_function.name else: func_name = node.args[2].name is_wrong_func = ctx.function and func_name != ctx.function.name # If we ignore accessibles or if we are in a function not mentioned in the accessible # expression we just use True as the body # Triggers, however, always need to be translated correctly, because every trigger # has to mention all quantified variables if (self._ignore_accessible or is_wrong_func) and not ctx.inside_trigger: return self.viper_ast.TrueLit(pos) else: stmts = [] tag = self.viper_ast.IntLit(ctx.program.analysis.accessible_tags[node], pos) to = self.translate(node.args[0], stmts, ctx) amount = self.translate(node.args[1], stmts, ctx) if len(node.args) == 2: func_args = [amount] if ctx.program.analysis.accessible_function.args else [] else: args = node.args[2].args func_args = [self.translate(arg, stmts, ctx) for arg in args] acc_name = mangled.accessible_name(func_name) acc_args = [tag, to, amount, *func_args] pred_acc = self.viper_ast.PredicateAccess(acc_args, acc_name, pos) # Inside triggers we need to use the predicate access, not the permission amount if ctx.inside_trigger: assert not stmts return pred_acc res.extend(stmts) return self.viper_ast.PredicateAccessPredicate(pred_acc, self.viper_ast.FullPerm(pos), pos) elif name == names.INDEPENDENT: res = self.translate(node.args[0], res, ctx) def unless(node): if isinstance(node, ast.FunctionCall): # An old expression with ctx.state_scope(ctx.current_old_state, ctx.current_old_state): return unless(node.args[0]) elif isinstance(node, ast.Attribute): struct_type = node.value.type stmts = [] ref = self.translate(node.value, stmts, ctx) assert not stmts tt = lambda t: self.type_translator.translate(t, ctx) get = lambda m, t: helpers.struct_get(self.viper_ast, ref, m, tt(t), struct_type, pos) members = struct_type.member_types.items() gets = [get(member, member_type) for member, member_type in members if member != node.attr] lows = [self.viper_ast.Low(get, position=pos) for get in gets] return unless(node.value) + lows elif isinstance(node, ast.Name): variables = [ctx.old_self_var, ctx.msg_var, ctx.block_var, ctx.chain_var, ctx.tx_var, *ctx.args.values()] return [self.viper_ast.Low(var.local_var(ctx, pos), position=pos) for var in variables if var.name != node.id] lows = unless(node.args[1]) lhs = reduce(lambda v1, v2: self.viper_ast.And(v1, v2, pos), lows) rhs = self._low(res, node.args[0].type, ctx, pos) return self.viper_ast.Implies(lhs, rhs, pos) elif name == names.REORDER_INDEPENDENT: arg = self.translate(node.args[0], res, ctx) # Using the current msg_var is ok since we don't use msg.gas, but always return fresh values, # therefore msg is constant variables = [ctx.issued_self_var, ctx.chain_var, ctx.tx_var, ctx.msg_var, *ctx.args.values()] low_variables = [self.viper_ast.Low(var.local_var(ctx), position=pos) for var in variables] cond = reduce(lambda v1, v2: self.viper_ast.And(v1, v2, pos), low_variables) implies = self.viper_ast.Implies(cond, self._low(arg, node.args[0].type, ctx, pos), pos) return implies elif name == names.EVENT: event = node.args[0] assert isinstance(event, ast.FunctionCall) event_name = mangled.event_name(event.name) args = [self.translate(arg, res, ctx) for arg in event.args] pred_acc = self.viper_ast.PredicateAccess(args, event_name, pos) # If this is a trigger, we just return the predicate access without the surrounding perm-expression and # comparison (which is not valid as a trigger). if ctx.inside_trigger: return pred_acc else: one = self.viper_ast.IntLit(1, pos) num = self.translate(node.args[1], res, ctx) if len(node.args) == 2 else one full_perm = self.viper_ast.FullPerm(pos) perm_mul = self.viper_ast.IntPermMul(num, full_perm, pos) current_perm = self.viper_ast.CurrentPerm(pred_acc, pos) eq_comp = self.viper_ast.EqCmp(current_perm, perm_mul, pos) if self._translating_check: return eq_comp else: cond = self.viper_ast.GtCmp(num, self.viper_ast.IntLit(0, pos), pos) pred_acc_pred = self.viper_ast.PredicateAccessPredicate(pred_acc, perm_mul, pos) if self._assume_events: local_event_args = ctx.event_vars.get(event_name) assert local_event_args assert len(local_event_args) == len(args) args_cond = self.viper_ast.TrueLit(pos) for local_event_arg, event_arg in zip(local_event_args, args): arg_eq = self.viper_ast.NeCmp(local_event_arg, event_arg, pos) args_cond = self.viper_ast.And(args_cond, arg_eq, pos) pred_acc_pred = self.viper_ast.And(args_cond, pred_acc_pred, pos) cond_pred_acc_pred = self.viper_ast.CondExp(cond, pred_acc_pred, args_cond, pos) return cond_pred_acc_pred else: implies = self.viper_ast.Implies(cond, pred_acc_pred, pos) return self.viper_ast.And(eq_comp, implies, pos) elif name == names.SELFDESTRUCT: self_var = ctx.self_var.local_var(ctx) self_type = ctx.self_type member = mangled.SELFDESTRUCT_FIELD type = self.type_translator.translate(self_type.member_types[member], ctx) sget = helpers.struct_get(self.viper_ast, self_var, member, type, self_type, pos) return sget elif name == names.OVERFLOW: return helpers.overflow_var(self.viper_ast, pos).localVar() elif name == names.OUT_OF_GAS: return helpers.out_of_gas_var(self.viper_ast, pos).localVar() elif name == names.FAILED: addr = self.translate(node.args[0], res, ctx) return helpers.check_call_failed(self.viper_ast, addr, pos) elif name == names.IMPLEMENTS: if ctx.program.config.has_option(names.CONFIG_TRUST_CASTS): return self.viper_ast.TrueLit(pos) address = self.translate(node.args[0], res, ctx) interface = node.args[1].id return helpers.implements(self.viper_ast, address, interface, ctx, pos) elif name in ctx.program.ghost_functions: return self._ghost_function(node, name, None, res, ctx) elif name == names.CALLER: return ctx.all_vars[mangled.CALLER].local_var(ctx) elif name not in names.NOT_ALLOWED_IN_SPEC: return super().translate_FunctionCall(node, res, ctx) else: assert False def _translate_pure_success(self, node, res, ctx, pos=None): call = node.args[0] assert isinstance(call, ast.ReceiverCall) func = ctx.program.functions[call.name] mangled_name = mangled.pure_function_name(call.name) function_args = call.args.copy() for (name, _), arg in zip_longest(func.args.items(), call.args): if not arg: function_args.append(func.defaults[name]) args = [self.translate(arg, res, ctx) for arg in [call.receiver] + function_args] func_app = self.viper_ast.FuncApp(mangled_name, args, pos, type=helpers.struct_type(self.viper_ast)) return self.viper_ast.FuncApp(mangled.PURE_SUCCESS, [func_app], pos, type=self.viper_ast.Bool) def translate_ReceiverCall(self, node: ast.ReceiverCall, res: List[Stmt], ctx: Context) -> Expr: receiver = node.receiver if isinstance(receiver, ast.Name): if receiver.id == names.LEMMA: return super().translate_ReceiverCall(node, res, ctx) elif receiver.id in ctx.current_program.interfaces: interface_file = ctx.current_program.interfaces[receiver.id].file return self._ghost_function(node, node.name, interface_file, res, ctx) assert False def _ghost_function(self, node, ghost_function: str, interface_file: Optional[str], res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) functions = ctx.program.ghost_functions[ghost_function] if interface_file: function = first(func for func in functions if func.file == interface_file) elif (isinstance(ctx.current_program, VyperInterface) and ctx.current_program.own_ghost_functions.get(ghost_function) is not None): function = ctx.current_program.own_ghost_functions[ghost_function] elif len(functions) == 1: function = functions[0] else: functions = ctx.current_program.ghost_functions[ghost_function] assert len(functions) == 1 function = functions[0] args = [self.translate(arg, res, ctx) for arg in node.args] address = args[0] contracts = ctx.current_state[mangled.CONTRACTS].local_var(ctx) key_type = self.type_translator.translate(types.VYPER_ADDRESS, ctx) value_type = helpers.struct_type(self.viper_ast) struct = helpers.map_get(self.viper_ast, contracts, address, key_type, value_type) # If we are not inside a trigger and the ghost function in question has an # implementation, we pass the self struct to it if the argument is the self address, # as the verifier does not know that $contracts[self] is equal to the self struct. if not ctx.inside_trigger and ghost_function in ctx.program.ghost_function_implementations: self_address = helpers.self_address(self.viper_ast, pos) eq = self.viper_ast.EqCmp(args[0], self_address) self_var = ctx.self_var.local_var(ctx, pos) struct = self.viper_ast.CondExp(eq, self_var, struct, pos) return_type = self.type_translator.translate(function.type.return_type, ctx) rpos = self.to_position(node, ctx, rules.PRECONDITION_IMPLEMENTS_INTERFACE) return helpers.ghost_function(self.viper_ast, function, address, struct, args[1:], return_type, rpos) def _low(self, expr, type: VyperType, ctx: Context, pos=None) -> Expr: comp = self.type_translator.comparator(type, ctx) if comp: return self.viper_ast.Low(expr, *comp, pos) else: return self.viper_ast.Low(expr, position=pos) def _injectivity_check(self, node: ast.Node, qvars: Iterable[TranslatedVar], resource: Optional[ast.Expr], args: List[ast.Expr], amount: Optional[ast.Expr], rule: rules.Rule, res: List[Stmt], ctx: Context): # To check injectivity we do the following: # forall q1_1, q1_2, q2_1, q2_2, ... :: q1_1 != q1_2 or q2_1 != q2_2 or ... ==> # arg1(q1_1, q2_1, ...) != arg1(q1_2, q2_2, ...) or arg2(q1_1, q2_1, ...) != arg2(q1_2, q2_2, ...) or ... # or amount(q1_1, q2_1, ...) == 0 or amount(q1_2, q2_2) == 0 or ... # i.e. that if any two quantified variables are different, at least one pair of arguments is also different if # the amount offered is non-zero. assert qvars all_args = ([] if resource is None else _ResourceArgumentExtractor().extract_args(resource)) + args pos = self.to_position(node, ctx) true = self.viper_ast.TrueLit(pos) false = self.viper_ast.FalseLit(pos) qtvars = [[], []] qtlocals = [[], []] type_assumptions = [[], []] for i in range(2): for idx, var in enumerate(qvars): new_var = TranslatedVar(var.name, f'$arg{idx}{i}', var.type, self.viper_ast, pos) qtvars[i].append(new_var) local = new_var.local_var(ctx) qtlocals[i].append(local) type_assumptions[i].extend(self.type_translator.type_assumptions(local, var.type, ctx)) tas = reduce(lambda a, b: self.viper_ast.And(a, b, pos), chain(*type_assumptions), true) or_op = lambda a, b: self.viper_ast.Or(a, b, pos) ne_op = lambda a, b: self.viper_ast.NeCmp(a, b, pos) cond = reduce(or_op, starmap(ne_op, zip(*qtlocals))) zero = self.viper_ast.IntLit(0, pos) targs = [[], []] is_zero = [] for i in range(2): with ctx.quantified_var_scope(): ctx.quantified_vars.update((var.name, var) for var in qtvars[i]) for arg in all_args: targ = self.translate(arg, res, ctx) targs[i].append(targ) if amount: tamount = self.translate(amount, res, ctx) is_zero.append(self.viper_ast.EqCmp(tamount, zero, pos)) arg_neq = reduce(or_op, starmap(ne_op, zip(*targs)), false) if is_zero: arg_neq = self.viper_ast.Or(arg_neq, reduce(or_op, is_zero), pos) expr = self.viper_ast.Implies(tas, self.viper_ast.Implies(cond, arg_neq, pos), pos) quant = self.viper_ast.Forall([var.var_decl(ctx) for var in chain(*qtvars)], [], expr, pos) modelt = self.model_translator.save_variables(res, ctx, pos) combined_rule = rules.combine(rules.INJECTIVITY_CHECK_FAIL, rule) apos = self.to_position(node, ctx, combined_rule, modelt=modelt) res.append(self.viper_ast.Assert(quant, apos)) def translate_ghost_statement(self, node: ast.FunctionCall, res: List[Stmt], ctx: Context, is_performs: bool = False) -> Expr: pos = self.to_position(node, ctx) name = node.name if name == names.REALLOCATE: resource, resource_expr = self.resource_translator.translate(node.resource, res, ctx, return_resource=True) amount = self.translate(node.args[0], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) to = None frm = msg_sender for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.REALLOCATE_TO: to = kw_val elif kw.name == names.REALLOCATE_ACTOR: frm = kw_val else: assert False performs_args = node, name, [resource_expr, frm, to, amount], [amount], res, ctx, pos if ctx.inside_derived_resource_performs: # If there is a derived resource for resource # If helper.self_address is frm -> deallocate amount derived resource from msg.sender # If helper.self_address is to -> allocate amount derived resource to msg.sender for derived_resource in resource.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource_expr, frm, to, amount, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.reallocate(node, resource_expr, frm, to, amount, msg_sender, res, ctx, pos) return None elif name == names.OFFER: from_resource_expr, to_resource_expr = self.resource_translator.translate_exchange(node.resource, res, ctx) left = self.translate(node.args[0], res, ctx) right = self.translate(node.args[1], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) all_args = node.args.copy() frm = msg_sender to = None times = None times_arg = None for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.OFFER_TO: to = kw_val all_args.append(kw.value) elif kw.name == names.OFFER_ACTOR: frm = kw_val elif kw.name == names.OFFER_TIMES: times = kw_val times_arg = kw.value else: assert False assert to is not None assert times is not None assert times_arg is not None performs_args = (node, name, [from_resource_expr, to_resource_expr, left, right, frm, to, times], [left, times], res, ctx, pos) if ctx.inside_derived_resource_performs: if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if ctx.quantified_vars: self._injectivity_check(node, ctx.quantified_vars.values(), node.resource, all_args, times_arg, rules.OFFER_FAIL, res, ctx) if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.offer(node, from_resource_expr, to_resource_expr, left, right, frm, to, times, msg_sender, res, ctx, pos) return None elif name == names.ALLOW_TO_DECOMPOSE: if ctx.inside_derived_resource_performs: return None resource_expr, underlying_resource_expr = self.resource_translator.translate_with_underlying(node, res, ctx) amount = self.translate(node.args[0], res, ctx) address = self.translate(node.args[1], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) const_one = self.viper_ast.IntLit(1, pos) performs_args = (node, names.OFFER, [resource_expr, underlying_resource_expr, const_one, const_one, address, address, amount], amount, res, ctx, pos) if ctx.inside_derived_resource_performs: if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.allow_to_decompose(node, resource_expr, underlying_resource_expr, address, amount, msg_sender, res, ctx, pos) elif name == names.REVOKE: from_resource_expr, to_resource_expr = self.resource_translator.translate_exchange(node.resource, res, ctx) left = self.translate(node.args[0], res, ctx) right = self.translate(node.args[1], res, ctx) to = self.translate(node.keywords[0].value, res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) all_args = node.args.copy() frm = msg_sender for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.REVOKE_TO: to = kw_val all_args.append(kw.value) elif kw.name == names.REVOKE_ACTOR: frm = kw_val else: assert False performs_args = (node, name, [from_resource_expr, to_resource_expr, left, right, frm, to], [left], res, ctx, pos) if ctx.inside_derived_resource_performs: if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if ctx.quantified_vars: self._injectivity_check(node, ctx.quantified_vars.values(), node.resource, all_args, None, rules.REVOKE_FAIL, res, ctx) if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.revoke(node, from_resource_expr, to_resource_expr, left, right, frm, to, msg_sender, res, ctx, pos) return None elif name == names.EXCHANGE: (resource1, resource1_expr), (resource2, resource2_expr) = self.resource_translator.translate_exchange( node.resource, res, ctx, return_resource=True) left = self.translate(node.args[0], res, ctx) right = self.translate(node.args[1], res, ctx) left_owner = self.translate(node.args[2], res, ctx) right_owner = self.translate(node.args[3], res, ctx) times = self.translate(node.keywords[0].value, res, ctx) performs_args = (node, name, [resource1_expr, resource2_expr, left, right, left_owner, right_owner, times], [self.viper_ast.Add(left, right), times], res, ctx, pos) if ctx.inside_derived_resource_performs: # If there is a derived resource for resource1 # If helper.self_address is left_owner -> deallocate amount derived resource from msg.sender # If helper.self_address is right_owner -> allocate amount derived resource to msg.sender amount1 = self.viper_ast.Mul(times, left) for derived_resource in resource1.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource1_expr, left_owner, right_owner, amount1, res, ctx) # If there is a derived resource for resource2 # If helper.self_address is right_owner -> deallocate amount derived resource from msg.sender # If helper.self_address is left_owner -> allocate amount derived resource to msg.sender amount2 = self.viper_ast.Mul(times, right) for derived_resource in resource2.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource2_expr, right_owner, left_owner, amount2, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.exchange(node, resource1_expr, resource2_expr, left, right, left_owner, right_owner, times, res, ctx, pos) return None elif name == names.CREATE: resource, resource_expr = self.resource_translator.translate(node.resource, res, ctx, return_resource=True) amount = self.translate(node.args[0], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) to = msg_sender frm = msg_sender args = [] for kw in node.keywords: if kw.name == names.CREATE_TO: to = self.translate(kw.value, res, ctx) args.append(kw.value) elif kw.name == names.CREATE_ACTOR: frm = self.translate(kw.value, res, ctx) # The 'by' parameter is not part of the injectivity check as # it does not make a difference as to which resource is created else: assert False performs_args = node, name, [resource_expr, frm, to, amount], [amount], res, ctx, pos if ctx.inside_derived_resource_performs: # If there is a derived resource for resource # If helper.self_address is to -> allocate amount derived resource from msg.sender for derived_resource in resource.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource_expr, None, to, amount, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if ctx.quantified_vars: self._injectivity_check(node, ctx.quantified_vars.values(), node.resource, args, node.args[0], rules.CREATE_FAIL, res, ctx) if is_performs: self.allocation_translator.performs(*performs_args) else: is_init = ctx.function.name == names.INIT self.allocation_translator.create(node, resource_expr, frm, to, amount, msg_sender, is_init, res, ctx, pos) return None elif name == names.DESTROY: resource, resource_expr = self.resource_translator.translate(node.resource, res, ctx, return_resource=True) amount = self.translate(node.args[0], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) frm = msg_sender for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.DESTROY_ACTOR: frm = kw_val performs_args = node, name, [resource_expr, frm, amount], [amount], res, ctx, pos if ctx.inside_derived_resource_performs: # If there is a derived resource for resource # If helper.self_address is frm -> deallocate amount derived resource from msg.sender for derived_resource in resource.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource_expr, frm, None, amount, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if ctx.quantified_vars: self._injectivity_check(node, ctx.quantified_vars.values(), node.resource, [], node.args[0], rules.DESTROY_FAIL, res, ctx) if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.destroy(node, resource_expr, frm, amount, msg_sender, res, ctx, pos) return None elif name == names.RESOURCE_PAYABLE: resource, resource_expr = self.resource_translator.translate(node.resource, res, ctx, return_resource=True) amount = self.translate(node.args[0], res, ctx) to = helpers.msg_sender(self.viper_ast, ctx, pos) for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.RESOURCE_PAYABLE_ACTOR: to = kw_val performs_args = node, name, [resource_expr, to, amount], [amount], res, ctx, pos if ctx.inside_derived_resource_performs: # If there is a derived resource for resource # If helper.self_address is msg.sender -> deallocate amount derived resource from msg.sender for derived_resource in resource.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource_expr, None, to, amount, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None assert is_performs self.allocation_translator.performs(*performs_args) elif name == names.RESOURCE_PAYOUT: resource, resource_expr = self.resource_translator.translate(node.resource, res, ctx, return_resource=True) amount = self.translate(node.args[0], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) frm = msg_sender for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.RESOURCE_PAYOUT_ACTOR: frm = kw_val performs_args = node, name, [resource_expr, frm, amount], [amount], res, ctx, pos if ctx.inside_derived_resource_performs: # If there is a derived resource for resource # If helper.self_address is frm -> deallocate amount derived resource from msg.sender for derived_resource in resource.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource_expr, frm, None, amount, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None assert is_performs self.allocation_translator.performs(*performs_args) elif name == names.TRUST: address = self.translate(node.args[0], res, ctx) val = self.translate(node.args[1], res, ctx) msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) actor = msg_sender keyword_args = [] for kw in node.keywords: kw_val = self.translate(kw.value, res, ctx) if kw.name == names.TRUST_ACTOR: actor = kw_val keyword_args.append(kw.value) performs_args = node, name, [address, actor, val], [], res, ctx, pos if ctx.inside_derived_resource_performs: if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if ctx.quantified_vars: rule = rules.TRUST_FAIL self._injectivity_check(node, ctx.quantified_vars.values(), None, [node.args[0], *keyword_args], None, rule, res, ctx) if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.trust(node, address, actor, val, res, ctx, pos) return None elif name == names.ALLOCATE_UNTRACKED: resource, resource_expr, underlying_resource_expr = self.resource_translator.translate_with_underlying( node, res, ctx, return_resource=True) address = self.translate(node.args[0], res, ctx) if resource.name == names.WEI: balance = self.balance_translator.get_balance(ctx.self_var.local_var(ctx), ctx, pos) else: allocated = ctx.current_state[mangled.ALLOCATED].local_var(ctx) self_address = helpers.self_address(self.viper_ast) balance = self.allocation_translator.get_allocated(allocated, underlying_resource_expr, self_address, ctx) performs_args = node, name, [resource_expr, address], [], res, ctx, pos if ctx.inside_derived_resource_performs: msg_sender = helpers.msg_sender(self.viper_ast, ctx, pos) amount = self.allocation_translator.allocation_difference_to_balance(balance, resource, ctx) # If there is a derived resource for resource # If helper.self_address is to -> allocate amount derived resource from msg.sender for derived_resource in resource.derived_resources: self.update_allocation_for_derived_resource( node, derived_resource, resource_expr, None, msg_sender, amount, res, ctx) if is_performs: self.allocation_translator.interface_performed(*performs_args) return None if is_performs: self.allocation_translator.performs(*performs_args) else: self.allocation_translator.allocate_untracked(node, resource_expr, address, balance, res, ctx, pos) return None elif name == names.FOREACH: assert len(node.args) > 0 dict_arg = node.args[0] assert isinstance(dict_arg, ast.Dict) with ctx.quantified_var_scope(): quants, _ = self._translate_quantified_vars(dict_arg, ctx) for var in quants: ctx.quantified_vars[var.name] = var body = node.args[-1] assert isinstance(body, ast.FunctionCall) return self.translate_ghost_statement(body, res, ctx, is_performs) else: assert False def update_allocation_for_derived_resource(self, node: ast.Node, derived_resource, underlying_resource_expr: Expr, frm: Optional[Expr], to: Optional[Expr], amount: Expr, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) self_address = helpers.self_address(self.viper_ast) args = self.viper_ast.to_list(underlying_resource_expr.getArgs()) args.pop() args.append(self_address) derived_resource_expr = helpers.struct_init(self.viper_ast, args, derived_resource.type) msg_var = ctx.all_vars[mangled.ORIGINAL_MSG].local_var(ctx) original_msg_sender = helpers.struct_get(self.viper_ast, msg_var, names.MSG_SENDER, self.viper_ast.Int, types.MSG_TYPE) stmts = [] if to is not None: to_eq_self = self.viper_ast.EqCmp(self_address, to) allocate_stmts = [] self.allocation_translator.allocate_derived(node, derived_resource_expr, frm or original_msg_sender, original_msg_sender, amount, allocate_stmts, ctx, pos) stmts.append(self.viper_ast.If(to_eq_self, allocate_stmts, [])) if frm is not None: frm_eq_self = self.viper_ast.EqCmp(self_address, frm) deallocate_stmts = [] self.allocation_translator.deallocate_derived(node, derived_resource_expr, underlying_resource_expr, to or original_msg_sender, amount, deallocate_stmts, ctx, pos) stmts.append(self.viper_ast.If(frm_eq_self, deallocate_stmts, [])) if to is not None and frm is not None: frm_neq_to = self.viper_ast.NeCmp(frm, to) res.extend(helpers.flattened_conditional(self.viper_ast, frm_neq_to, stmts, [], pos)) else: res.extend(helpers.flattened_conditional(self.viper_ast, self.viper_ast.TrueLit(), stmts, [], pos)) class _ResourceArgumentExtractor(NodeVisitor): def extract_args(self, node: ast.Expr) -> List[ast.Expr]: return self.visit(node) @staticmethod def visit_Name(_: ast.Name) -> List[ast.Expr]: return [] def visit_Exchange(self, node: ast.Exchange) -> List[ast.Expr]: return self.visit(node.left) + self.visit(node.right) def visit_FunctionCall(self, node: ast.FunctionCall) -> List[ast.Expr]: if node.name == names.CREATOR: return self.visit(node.args[0]) else: return node.args def generic_visit(self, node, *args): assert False
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/specification.py
specification.py
from itertools import chain from typing import List, Optional, Tuple from twovyper.ast import names, types from twovyper.ast.arithmetic import Decimal from twovyper.ast.types import StructType, DecimalType from twovyper.translation import helpers, mangled from twovyper.translation.context import Context from twovyper.translation.abstract import CommonTranslator from twovyper.translation.type import TypeTranslator from twovyper.verification.model import ModelTransformation from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Stmt class ModelTranslator(CommonTranslator): def __init__(self, viper_ast: ViperAST): self.viper_ast = viper_ast self.type_translator = TypeTranslator(viper_ast) def save_variables(self, res: List[Stmt], ctx: Context, pos=None) -> Optional[ModelTransformation]: # Viper only gives a model for variables, therefore we save all important expressions # in variables and provide a mapping back to the Vyper expression. Also, we give a value # transformation to change, e.g., 12 to 0.0000000012 for decimals. if not ctx.options.create_model: return [], None self_var = ctx.self_var.local_var(ctx) old_self_var = ctx.old_self_var.local_var(ctx) transform = {} type_map = {} def add_model_var(name, var_type, rhs, components): new_var_name = ctx.new_local_var_name(mangled.model_var_name(*components)) vtype = self.type_translator.translate(var_type, ctx) new_var = self.viper_ast.LocalVarDecl(new_var_name, vtype, pos) ctx.new_local_vars.append(new_var) transform[new_var_name] = name type_map[new_var_name] = var_type if hasattr(rhs, 'isSubtype') and rhs.isSubtype(helpers.wrapped_int_type(self.viper_ast)): rhs = helpers.w_unwrap(self.viper_ast, rhs) res.append(self.viper_ast.LocalVarAssign(new_var.localVar(), rhs, pos)) def add_struct_members(struct, struct_type, components, wrapped=None): for member, member_type in struct_type.member_types.items(): new_components = components + [member] mtype = self.type_translator.translate(member_type, ctx) get = helpers.struct_get(self.viper_ast, struct, member, mtype, struct_type, pos) if isinstance(member_type, StructType): add_struct_members(get, member_type, new_components, wrapped) else: if member == mangled.SELFDESTRUCT_FIELD: name = f'{names.SELFDESTRUCT}()' elif member == mangled.SENT_FIELD: name = f'{names.SENT}()' elif member == mangled.RECEIVED_FIELD: name = f'{names.RECEIVED}()' else: name = '.'.join(new_components) if wrapped: name = wrapped(name) add_model_var(name, member_type, get, new_components) add_struct_members(self_var, ctx.program.type, [names.SELF]) add_struct_members(old_self_var, ctx.program.type, [names.SELF], lambda n: f'{names.OLD}({n})') if ctx.function.analysis.uses_issued: issued_self_var = ctx.pre_self_var.local_var(ctx) add_struct_members(issued_self_var, ctx.program.type, [names.SELF], lambda n: f'{names.ISSUED}({n})') for var in chain(ctx.args.values(), ctx.locals.values()): if isinstance(var.type, StructType): add_struct_members(var.local_var(ctx), var.type, [var.name]) else: transform[var.mangled_name] = var.name type_map[var.mangled_name] = var.type if ctx.success_var is not None: transform[ctx.success_var.mangled_name] = f'{names.SUCCESS}()' type_map[ctx.success_var.mangled_name] = ctx.success_var.type if ctx.result_var is not None: transform[ctx.result_var.mangled_name] = f'{names.RESULT}()' type_map[ctx.result_var.mangled_name] = ctx.result_var.type transform[mangled.OUT_OF_GAS] = f'{names.OUT_OF_GAS}()' type_map[mangled.OUT_OF_GAS] = types.VYPER_BOOL transform[mangled.OVERFLOW] = f'{names.OVERFLOW}()' type_map[mangled.OVERFLOW] = types.VYPER_BOOL return (transform, type_map)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/model.py
model.py
from typing import Optional from twovyper.translation import helpers from twovyper.ast.types import VyperType from twovyper.translation.context import Context from twovyper.translation.type import TypeTranslator from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Var, VarDecl class TranslatedVar: def __init__(self, vyper_name: str, viper_name: str, vyper_type: VyperType, viper_ast: ViperAST, pos=None, info=None, is_local=True): self.name = vyper_name self.mangled_name = viper_name self.type = vyper_type self.viper_ast = viper_ast self.pos = pos self.info = info self.is_local = is_local self._type_translator = TypeTranslator(viper_ast) def var_decl(self, ctx: Context, pos=None, info=None) -> VarDecl: pos = pos or self.pos info = info or self.info vtype = self._type_translator.translate(self.type, ctx, is_local=self.is_local) return self.viper_ast.LocalVarDecl(self.mangled_name, vtype, pos, info) def local_var(self, ctx: Context, pos=None, info=None) -> Var: pos = pos or self.pos info = info or self.info vtype = self._type_translator.translate(self.type, ctx, is_local=self.is_local) return self.viper_ast.LocalVar(self.mangled_name, vtype, pos, info) class TranslatedPureIndexedVar(TranslatedVar): def __init__(self, vyper_name: str, viper_name: str, vyper_type: VyperType, viper_ast: ViperAST, pos=None, info=None, is_local=True): super().__init__(vyper_name, viper_name, vyper_type, viper_ast, pos, info, is_local) self.idx: Optional[int] = None self.viper_struct_type = helpers.struct_type(self.viper_ast) self.function_result = self.viper_ast.Result(self.viper_struct_type) def var_decl(self, ctx: Context, pos=None, info=None) -> VarDecl: pos = pos or self.pos info = info or self.info return self.viper_ast.TrueLit(pos, info) def local_var(self, ctx: Context, pos=None, info=None) -> Expr: pos = pos or self.pos info = info or self.info self.evaluate_idx(ctx) viper_type = self._type_translator.translate(self.type, ctx, is_local=self.is_local) return helpers.struct_get_idx(self.viper_ast, self.function_result, self.idx, viper_type, pos, info) def evaluate_idx(self, ctx: Context) -> int: if not self.idx: self.idx = ctx.next_pure_var_index() return self.idx def new_idx(self): self.idx = None
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/variable.py
variable.py
from contextlib import contextmanager, ExitStack from typing import List from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.types import MapType, ArrayType, StructType, VYPER_UINT256 from twovyper.ast.visitors import NodeVisitor from twovyper.exceptions import UnsupportedException from twovyper.translation import helpers, mangled from twovyper.translation.context import Context from twovyper.translation.abstract import NodeTranslator, CommonTranslator from twovyper.translation.arithmetic import ArithmeticTranslator from twovyper.translation.expression import ExpressionTranslator from twovyper.translation.model import ModelTranslator from twovyper.translation.specification import SpecificationTranslator from twovyper.translation.state import StateTranslator from twovyper.translation.type import TypeTranslator from twovyper.translation.variable import TranslatedVar from twovyper.verification import rules from twovyper.verification.error import Via from twovyper.viper.ast import ViperAST from twovyper.viper.typedefs import Expr, Stmt def add_new_var(self: CommonTranslator, node: ast.Name, ctx: Context, is_local: bool): """ Adds the local variable to the context. """ pos = self.to_position(node, ctx) variable_name = node.id mangled_name = ctx.new_local_var_name(variable_name) var = TranslatedVar(variable_name, mangled_name, node.type, self.viper_ast, pos, is_local=is_local) ctx.locals[variable_name] = var ctx.new_local_vars.append(var.var_decl(ctx)) class StatementTranslator(NodeTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.expression_translator = ExpressionTranslator(viper_ast) self.assignment_translator = AssignmentTranslator(viper_ast) self.arithmetic_translator = ArithmeticTranslator(viper_ast) self.model_translator = ModelTranslator(viper_ast) self.specification_translator = SpecificationTranslator(viper_ast) self.state_translator = StateTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) def translate_stmts(self, stmts: List[ast.Stmt], res: List[Stmt], ctx: Context): for s in stmts: self.translate(s, res, ctx) def translate_AnnAssign(self, node: ast.AnnAssign, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) if node.value is None: vyper_type = node.target.type rhs = self.type_translator.default_value(None, vyper_type, res, ctx) elif types.is_numeric(node.value.type): rhs = self.expression_translator.translate_top_level_expression(node.value, res, ctx) else: # Ignore the $wrap information, if the node is not numeric rhs = self.expression_translator.translate(node.value, res, ctx) is_wrapped = False if self.expression_translator.arithmetic_translator.is_wrapped(rhs): if types.is_numeric(node.value.type): is_wrapped = True else: rhs = helpers.w_unwrap(self.viper_ast, rhs) add_new_var(self, node.target, ctx, not is_wrapped) # An annotated assignment can only have a local variable on the lhs, # therefore we can simply use the expression translator lhs = self.expression_translator.translate(node.target, res, ctx) res.append(self.viper_ast.LocalVarAssign(lhs, rhs, pos)) def translate_Assign(self, node: ast.Assign, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) target = node.target rhs = self.expression_translator.translate_top_level_expression(node.value, res, ctx) if isinstance(target, ast.Tuple): for idx, element in enumerate(target.elements): element_type = self.type_translator.translate(element.type, ctx) rhs_element = helpers.struct_get_idx(self.viper_ast, rhs, idx, element_type, pos) self.assignment_translator.assign_to(element, rhs_element, res, ctx) else: self.assignment_translator.assign_to(target, rhs, res, ctx) def translate_AugAssign(self, node: ast.AugAssign, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) lhs = self.expression_translator.translate_top_level_expression(node.target, res, ctx) rhs = self.expression_translator.translate_top_level_expression(node.value, res, ctx) value = self.arithmetic_translator.arithmetic_op(lhs, node.op, rhs, node.value.type, res, ctx, pos) self.assignment_translator.assign_to(node.target, value, res, ctx) def translate_Log(self, node: ast.Log, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) event_function = node.body assert isinstance(event_function, ast.FunctionCall) event = ctx.program.events[event_function.name] args = [self.expression_translator.translate(arg, res, ctx) for arg in event_function.args] self.expression_translator.log_event(event, args, res, ctx, pos) def translate_ExprStmt(self, node: ast.ExprStmt, res: List[Stmt], ctx: Context): # Check if we are translating a call to clear # We handle clear in the StatementTranslator because it is essentially an assignment if isinstance(node.value, ast.FunctionCall) and node.value.name == names.CLEAR: arg = node.value.args[0] value = self.type_translator.default_value(node, arg.type, res, ctx) self.assignment_translator.assign_to(arg, value, res, ctx) else: # Ignore the expression, return the stmts _ = self.expression_translator.translate(node.value, res, ctx) def translate_Raise(self, node: ast.Raise, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) # If UNREACHABLE is used, we assert that the exception is unreachable, # i.e., that it never happens; else, we revert if isinstance(node.msg, ast.Name) and node.msg.id == names.UNREACHABLE: modelt = self.model_translator.save_variables(res, ctx, pos) mpos = self.to_position(node, ctx, modelt=modelt) false = self.viper_ast.FalseLit(pos) res.append(self.viper_ast.Assert(false, mpos)) else: res.append(self.viper_ast.Goto(ctx.revert_label, pos)) def translate_Assert(self, node: ast.Assert, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) translator = self.specification_translator if node.is_ghost_code else self.expression_translator with ctx.lemma_scope() if node.is_lemma else ExitStack(): expr = translator.translate(node.test, res, ctx) # If UNREACHABLE is used, we try to prove that the assertion holds by # translating it directly as an assert; else, revert if the condition # is false. if node.is_lemma or (isinstance(node.msg, ast.Name) and node.msg.id == names.UNREACHABLE): modelt = self.model_translator.save_variables(res, ctx, pos) mpos = self.to_position(node, ctx, modelt=modelt) res.append(self.viper_ast.Assert(expr, mpos)) else: cond = self.viper_ast.Not(expr, pos) self.fail_if(cond, [], res, ctx, pos) def translate_Return(self, node: ast.Return, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) if node.value: lhs = ctx.result_var.local_var(ctx, pos) expr = self.expression_translator.translate_top_level_expression(node.value, res, ctx) if (self.expression_translator.arithmetic_translator.is_unwrapped(lhs) and self.expression_translator.arithmetic_translator.is_wrapped(expr)): expr = helpers.w_unwrap(self.viper_ast, expr) assign = self.viper_ast.LocalVarAssign(lhs, expr, pos) res.append(assign) res.append(self.viper_ast.Goto(ctx.return_label, pos)) def translate_If(self, node: ast.If, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) translator = self.specification_translator if node.is_ghost_code else self.expression_translator cond = translator.translate(node.test, res, ctx) old_locals = dict(ctx.locals) with self.assignment_translator.assume_everything_has_wrapped_information(): then_body = [] with ctx.new_local_scope(): self.translate_stmts(node.body, then_body, ctx) else_body = [] with ctx.new_local_scope(): self.translate_stmts(node.orelse, else_body, ctx) if_stmt = self.viper_ast.If(cond, then_body, else_body, pos) for overwritten_var_name in self.assignment_translator.overwritten_vars: if old_locals.get(overwritten_var_name): lhs = ctx.locals[overwritten_var_name].local_var(ctx) rhs = old_locals[overwritten_var_name].local_var(ctx) if self.arithmetic_translator.is_unwrapped(rhs): rhs = helpers.w_wrap(self.viper_ast, rhs) res.append(self.viper_ast.LocalVarAssign(lhs, rhs)) res.append(if_stmt) def translate_For(self, node: ast.For, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) stmts = [] times = node.iter.type.size lpos = self.to_position(node.target, ctx) rpos = self.to_position(node.iter, ctx) if times > 0: old_locals = dict(ctx.locals) overwritten_vars = set() has_numeric_array = types.is_numeric(node.target.type) array = self.expression_translator.translate_top_level_expression(node.iter, stmts, ctx) add_new_var(self, node.target, ctx, False) loop_var_name = node.target.id loop_invariants = ctx.current_function.loop_invariants.get(node) if loop_invariants: ctx.loop_arrays[loop_var_name] = array # New variable loop-idx idx_var_name = '$idx' mangled_name = ctx.new_local_var_name(idx_var_name) via = [Via('index of array', rpos)] idx_pos = self.to_position(node.target, ctx, vias=via) var = TranslatedVar(idx_var_name, mangled_name, VYPER_UINT256, self.viper_ast, idx_pos) ctx.loop_indices[loop_var_name] = var ctx.new_local_vars.append(var.var_decl(ctx)) loop_idx_var = var.local_var(ctx) # New variable loop-var loop_var = ctx.all_vars[loop_var_name].local_var(ctx) # Base case loop_idx_eq_zero = self.viper_ast.EqCmp(loop_idx_var, self.viper_ast.IntLit(0), rpos) assume_base_case = self.viper_ast.Inhale(loop_idx_eq_zero, rpos) array_at = self.viper_ast.SeqIndex(array, loop_idx_var, rpos) if has_numeric_array: array_at = helpers.w_wrap(self.viper_ast, array_at, rpos) set_loop_var = self.viper_ast.LocalVarAssign(loop_var, array_at, lpos) self.seqn_with_info([assume_base_case, set_loop_var], "Base case: Known property about loop variable", stmts) with ctx.state_scope(ctx.current_state, ctx.current_state): # Loop Invariants are translated the same as pre- or postconditions translated_loop_invariant_asserts = \ [(loop_invariant, self.specification_translator.translate_pre_or_postcondition(loop_invariant, stmts, ctx)) for loop_invariant in loop_invariants] loop_invariant_stmts = [] for loop_invariant, cond in translated_loop_invariant_asserts: cond_pos = self.to_position(loop_invariant, ctx, rules.LOOP_INVARIANT_BASE_FAIL) loop_invariant_stmts.append(self.viper_ast.Exhale(cond, cond_pos)) self.seqn_with_info(loop_invariant_stmts, "Check loop invariants before iteration 0", stmts) # Step case # Havoc state havoc_stmts = [] # Create pre states of loop def loop_pre_state(name: str) -> str: return ctx.all_vars[loop_var_name].mangled_name + mangled.pre_state_var_name(name) pre_state_of_loop = self.state_translator.state(loop_pre_state, ctx) for val in pre_state_of_loop.values(): ctx.new_local_vars.append(val.var_decl(ctx, pos)) # Copy present state to this created pre_state self.state_translator.copy_state(ctx.current_state, pre_state_of_loop, havoc_stmts, ctx) # Havoc loop variables havoc_var = helpers.havoc_var(self.viper_ast, self.viper_ast.Int, ctx) havoc_loop_idx = self.viper_ast.LocalVarAssign(loop_idx_var, havoc_var) havoc_stmts.append(havoc_loop_idx) havoc_loop_var_type = self.type_translator.translate(node.target.type, ctx) havoc_var = helpers.havoc_var(self.viper_ast, havoc_loop_var_type, ctx) if has_numeric_array: havoc_var = helpers.w_wrap(self.viper_ast, havoc_var) havoc_loop_var = self.viper_ast.LocalVarAssign(loop_var, havoc_var) havoc_stmts.append(havoc_loop_var) # Havoc old and current state self.state_translator.havoc_old_and_current_state(self.specification_translator, havoc_stmts, ctx, pos) # Havoc used variables loop_used_var = {} for var_name in ctx.current_function.analysis.loop_used_names.get(loop_var_name, []): if var_name == loop_var_name: continue var = ctx.locals.get(var_name) if var: # Create new variable mangled_name = ctx.new_local_var_name(var.name) # Since these variables changed in the loop may not be constant, we have to assume, that # they are not local anymore. new_var = TranslatedVar(var.name, mangled_name, var.type, var.viper_ast, var.pos, var.info, is_local=False) ctx.new_local_vars.append(new_var.var_decl(ctx)) ctx.locals[var_name] = new_var loop_used_var[var_name] = var new_var_local = new_var.local_var(ctx) havoc_var = helpers.havoc_var(self.viper_ast, new_var_local.typ(), ctx) havoc_stmts.append(self.viper_ast.LocalVarAssign(new_var_local, havoc_var)) var_type_assumption = self.type_translator.type_assumptions(new_var_local, new_var.type, ctx) var_type_assumption = [self.viper_ast.Inhale(expr) for expr in var_type_assumption] self.seqn_with_info(var_type_assumption, f"Type assumption for {var_name}", havoc_stmts) # Mark that this variable got overwritten self.assignment_translator.overwritten_vars.append(var_name) self.seqn_with_info(havoc_stmts, "Havoc state", stmts) # Havoc events event_handling = [] self.expression_translator.forget_about_all_events(event_handling, ctx, pos) self.expression_translator.log_all_events_zero_or_more_times(event_handling, ctx, pos) self.seqn_with_info(event_handling, "Assume we know nothing about events", stmts) # Loop invariants loop_idx_ge_zero = self.viper_ast.GeCmp(loop_idx_var, self.viper_ast.IntLit(0), rpos) times_lit = self.viper_ast.IntLit(times) loop_idx_lt_array_size = self.viper_ast.LtCmp(loop_idx_var, times_lit, rpos) loop_idx_assumption = self.viper_ast.And(loop_idx_ge_zero, loop_idx_lt_array_size, rpos) assume_step_case = self.viper_ast.Inhale(loop_idx_assumption, rpos) array_at = self.viper_ast.SeqIndex(array, loop_idx_var, rpos) if has_numeric_array: array_at = helpers.w_wrap(self.viper_ast, array_at, rpos) set_loop_var = self.viper_ast.LocalVarAssign(loop_var, array_at, lpos) self.seqn_with_info([assume_step_case, set_loop_var], "Step case: Known property about loop variable", stmts) with ctx.old_local_variables_scope(loop_used_var): with ctx.state_scope(ctx.current_state, pre_state_of_loop): # Translate the loop invariants with assume-events-flag translated_loop_invariant_assumes = \ [(loop_invariant, self.specification_translator .translate_pre_or_postcondition(loop_invariant, stmts, ctx, assume_events=True)) for loop_invariant in loop_invariants] loop_invariant_stmts = [] for loop_invariant, cond_inhale in translated_loop_invariant_assumes: cond_pos = self.to_position(loop_invariant, ctx, rules.INHALE_LOOP_INVARIANT_FAIL) loop_invariant_stmts.append(self.viper_ast.Inhale(cond_inhale, cond_pos)) self.seqn_with_info(loop_invariant_stmts, "Assume loop invariants", stmts) with ctx.break_scope(): with ctx.continue_scope(): with self.assignment_translator.assume_everything_has_wrapped_information(): # Loop Body with ctx.new_local_scope(): loop_body_stmts = [] self.translate_stmts(node.body, loop_body_stmts, ctx) self.seqn_with_info(loop_body_stmts, "Loop body", stmts) overwritten_vars.update(self.assignment_translator.overwritten_vars) continue_info = self.to_info(["End of loop body"]) stmts.append(self.viper_ast.Label(ctx.continue_label, pos, continue_info)) # After loop body loop_idx_inc = self.viper_ast.Add(loop_idx_var, self.viper_ast.IntLit(1), pos) stmts.append(self.viper_ast.LocalVarAssign(loop_idx_var, loop_idx_inc, pos)) loop_idx_eq_times = self.viper_ast.EqCmp(loop_idx_var, times_lit, pos) goto_break = self.viper_ast.Goto(ctx.break_label, pos) stmts.append(self.viper_ast.If(loop_idx_eq_times, [goto_break], [], pos)) array_at = self.viper_ast.SeqIndex(array, loop_idx_var, rpos) if has_numeric_array: array_at = helpers.w_wrap(self.viper_ast, array_at, rpos) stmts.append(self.viper_ast.LocalVarAssign(loop_var, array_at, lpos)) # Check loop invariants with ctx.old_local_variables_scope(loop_used_var): with ctx.state_scope(ctx.current_state, pre_state_of_loop): # Re-translate the loop invariants since the context might have changed translated_loop_invariant_asserts = \ [(loop_invariant, self.specification_translator.translate_pre_or_postcondition(loop_invariant, stmts, ctx)) for loop_invariant in loop_invariants] loop_invariant_stmts = [] for loop_invariant, cond in translated_loop_invariant_asserts: cond_pos = self.to_position(loop_invariant, ctx, rules.LOOP_INVARIANT_STEP_FAIL) loop_invariant_stmts.append(self.viper_ast.Exhale(cond, cond_pos)) self.seqn_with_info(loop_invariant_stmts, "Check loop invariants for iteration idx + 1", stmts) # Kill this branch stmts.append(self.viper_ast.Inhale(self.viper_ast.FalseLit(), pos)) break_info = self.to_info(["After loop"]) stmts.append(self.viper_ast.Label(ctx.break_label, pos, break_info)) else: with ctx.break_scope(): loop_var = ctx.all_vars[loop_var_name].local_var(ctx) for i in range(times): with ctx.continue_scope(): loop_info = self.to_info(["Start of loop iteration."]) idx = self.viper_ast.IntLit(i, lpos) array_at = self.viper_ast.SeqIndex(array, idx, rpos) if has_numeric_array: array_at = helpers.w_wrap(self.viper_ast, array_at) var_set = self.viper_ast.LocalVarAssign(loop_var, array_at, lpos, loop_info) stmts.append(var_set) with self.assignment_translator.assume_everything_has_wrapped_information(): with ctx.new_local_scope(): self.translate_stmts(node.body, stmts, ctx) overwritten_vars.update(self.assignment_translator.overwritten_vars) continue_info = self.to_info(["End of loop iteration."]) stmts.append(self.viper_ast.Label(ctx.continue_label, pos, continue_info)) break_info = self.to_info(["End of loop."]) stmts.append(self.viper_ast.Label(ctx.break_label, pos, break_info)) for overwritten_var_name in overwritten_vars: if old_locals.get(overwritten_var_name): lhs = ctx.locals[overwritten_var_name].local_var(ctx) rhs = old_locals[overwritten_var_name].local_var(ctx) if self.arithmetic_translator.is_unwrapped(rhs): rhs = helpers.w_wrap(self.viper_ast, rhs) res.append(self.viper_ast.LocalVarAssign(lhs, rhs)) res.extend(stmts) def translate_Break(self, node: ast.Break, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) res.append(self.viper_ast.Goto(ctx.break_label, pos)) def translate_Continue(self, node: ast.Continue, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) res.append(self.viper_ast.Goto(ctx.continue_label, pos)) def translate_Pass(self, node: ast.Pass, res: List[Stmt], ctx: Context): pass class AssignmentTranslator(NodeVisitor, CommonTranslator): def __init__(self, viper_ast: ViperAST): super().__init__(viper_ast) self.expression_translator = ExpressionTranslator(viper_ast) self.type_translator = TypeTranslator(viper_ast) self._always_wrap = False self.overwritten_vars: List[str] = [] @contextmanager def assume_everything_has_wrapped_information(self): overwritten_vars = self.overwritten_vars self.overwritten_vars = [] always_wrap = self._always_wrap self._always_wrap = True yield self._always_wrap = always_wrap if always_wrap: # If we are inside another "assume_everything_has_wrapped_information" context, # keep the overwritten_vars information. self.overwritten_vars.extend(overwritten_vars) else: self.overwritten_vars = overwritten_vars @property def method_name(self) -> str: return 'assign_to' def assign_to(self, node: ast.Node, value: Expr, res: List[Stmt], ctx: Context): return self.visit(node, value, res, ctx) def generic_visit(self, node, *args): assert False def assign_to_Name(self, node: ast.Name, value: Expr, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) lhs = self.expression_translator.translate(node, res, ctx) w_value = value if (types.is_numeric(node.type) and self.expression_translator.arithmetic_translator.is_wrapped(lhs) and self.expression_translator.arithmetic_translator.is_unwrapped(value)): w_value = helpers.w_wrap(self.viper_ast, value) elif (types.is_numeric(node.type) and self.expression_translator.arithmetic_translator.is_unwrapped(lhs) and self.expression_translator.arithmetic_translator.is_wrapped(value)): add_new_var(self, node, ctx, False) lhs = self.expression_translator.translate(node, res, ctx) self.overwritten_vars.append(node.id) elif (types.is_numeric(node.type) and self._always_wrap and self.expression_translator.arithmetic_translator.is_unwrapped(lhs) and self.expression_translator.arithmetic_translator.is_unwrapped(value)): add_new_var(self, node, ctx, False) lhs = self.expression_translator.translate(node, res, ctx) self.overwritten_vars.append(node.id) w_value = helpers.w_wrap(self.viper_ast, value) elif (not types.is_numeric(node.type) and self.expression_translator.arithmetic_translator.is_wrapped(value)): w_value = helpers.w_unwrap(self.viper_ast, value) res.append(self.viper_ast.LocalVarAssign(lhs, w_value, pos)) def assign_to_Attribute(self, node: ast.Attribute, value: Expr, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) if isinstance(node.value.type, StructType): rec = self.expression_translator.translate(node.value, res, ctx) vyper_type = self.type_translator.translate(node.type, ctx) new_value = helpers.struct_set(self.viper_ast, rec, value, node.attr, vyper_type, node.value.type, pos) self.assign_to(node.value, new_value, res, ctx) else: lhs = self.expression_translator.translate(node, res, ctx) res.append(self.viper_ast.FieldAssign(lhs, value, pos)) def assign_to_Subscript(self, node: ast.Subscript, value: Expr, res: List[Stmt], ctx: Context): pos = self.to_position(node, ctx) receiver = self.expression_translator.translate(node.value, res, ctx) index = self.expression_translator.translate(node.index, res, ctx) vyper_type = node.value.type if isinstance(vyper_type, MapType): key_type = self.type_translator.translate(vyper_type.key_type, ctx) value_type = self.type_translator.translate(vyper_type.value_type, ctx) new_value = helpers.map_set(self.viper_ast, receiver, index, value, key_type, value_type, pos) elif isinstance(vyper_type, ArrayType): self.type_translator.array_bounds_check(receiver, index, res, ctx) new_value = helpers.array_set(self.viper_ast, receiver, index, value, vyper_type.element_type, pos) else: assert False # We simply evaluate the receiver and index statements here, even though they # might get evaluated again in the recursive call. This is ok as long as the lhs of the # assignment is pure. self.assign_to(node.value, new_value, res, ctx) def assign_to_ReceiverCall(self, node: ast.ReceiverCall, value, ctx: Context): raise UnsupportedException(node, "Assignments to calls are not supported.")
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/statement.py
statement.py
def addition(inputX, positiveX, inputY, positiveY, b, countAdd = 0, countMult = 0): lenX = len(inputX) lenY = len(inputY) inputXY = inputX, inputY maxLen = max(map(len, inputXY)) # add digits for digits in inputXY: while len(digits) <= maxLen: digits.insert(0, 0) if (positiveX == False) and (positiveY == False): # set positive indicator positiveOutput = False # run addition [output, countAdd, countMult] = addition(inputX, True, inputY, True, b, countAdd, countMult)[1:4] elif (positiveX == True) and (positiveY == False): # run subtraction [positiveOutput, output, countAdd, countMult] = subtraction(inputX, True, inputY, True, b, countAdd, countMult) elif (positiveX == False) and (positiveY == True): # run subtraction [positiveOutput, output, countAdd, countMult] = subtraction(inputY, True, inputX, True, b, countAdd, countMult) elif (positiveX == True) and (positiveY == True): # set positive indicator positiveOutput = True # sum the digits from listX with listY according to index in each list sumXY = [sum(x) for x in zip(*inputXY)] output = sumXY.copy() for i in range(1, len(output)): rem, carry = 0, 0 if output[-i] >= b: carry = output[-i] // b output[-i] = output[-i] % b output[-(i+1)] += carry countAdd += 1 i = 0 while i < (len(output) - 1): if (output[i] == 0): output.pop(0) continue break return [positiveOutput, output, countAdd, countMult] def subtraction(inputX, positiveX, inputY, positiveY, b, countAdd = 0, countMult = 0): lenX = len(inputX) lenY = len(inputY) inputXY = inputX, inputY maxLen = max(map(len, inputXY)) # add digits for digits in inputXY: while len(digits) < maxLen: digits.insert(0, 0) if (positiveX == False) and (positiveY == False): # run addition [positiveOutput, output, countAdd, countMult] = subtraction(inputY, True, inputX, True, b, countAdd, countMult) elif (positiveX == True) and (positiveY == False): # run subtraction [positiveOutput, output, countAdd, countMult] = addition(inputX, True, inputY, True, b, countAdd, countMult) elif (positiveX == False) and (positiveY == True): # run subtraction [positiveOutput, output, countAdd, countMult] = addition(inputX, False, inputY, False, b, countAdd, countMult) elif (positiveX == True) and (positiveY == True): # check which number is bigger for i in range(maxLen): if (inputX[i] > inputY[i]): positiveOutput = True elif (inputX[i] < inputY[i]): inputTemp= inputX.copy() inputX = inputY.copy() inputY = inputTemp.copy() inputXY = inputX, inputY positiveOutput = False elif (inputX[i] == inputY[i]): if (i == maxLen - 1): return [True, [0], countAdd, countMult] continue break # sum the digits from listX with listY according to index in each list diffXY = [0] * maxLen for i in range(maxLen): diffXY[i] = inputX[i] - inputY[i] countAdd += 1 output = diffXY.copy() for i in range(1, len(output)): rem = 0 if output[-i] < 0: output[-(i+1)] -= 1 rem = output[-i] + b output[-i] = rem countAdd += 2 i = 0 while i < (len(output) - 1): if (output[i] == 0): output.pop(0) continue break return [positiveOutput, output, countAdd, countMult] def multiplication(inputX, positiveX, inputY, positiveY, b, countAdd = 0, countMult = 0): inputXY = inputX, inputY maxLen = max(map(len, inputXY)) minLen = min(map(len, inputXY)) positiveOutput = not(positiveX ^ positiveY) for digits in inputXY: while len(digits) < maxLen: digits.insert(0, 0) n = len(inputX) output = [0]*2*n for i in range(0, n): digit2 = inputY[-(i+1)] for j in range(0, n): digit1 = inputX[-(j+1)] outputNumber = digit1 * digit2 output[-(1+i+j)] += outputNumber countAdd += 1 countMult += 1 for i in range(1, len(output)+1): if output[-i] >= b: carry = output[-i] // b output[-i] = output[-i] % b output[-(i+1)] += carry countAdd += 1 i = 0 while i < (len(output) - 1): if (output[i] == 0): output.pop(0) continue break return [positiveOutput, output, countAdd, countMult] def karatsuba(inputX, positiveX, inputY, positiveY, b, countAdd = 0, countMult = 0): positiveOutput = not (positiveX ^ positiveY) i = 0; while i < (len(inputX)-1): if (inputX[i] == 0): inputX.pop(0) continue break i = 0; while i < (len(inputY)-1): if (inputY[i] == 0): inputY.pop(0) continue break if (len(inputX) <= 1 or len(inputY) <= 1): [positive, output, countAdd, countMult] = multiplication(inputX, positiveX, inputY, positiveY, b, countAdd, countMult) return [positive, output, countAdd, countMult] inputXY = inputX, inputY maxLen = max(len(inputX), len(inputY)) for digits in inputXY: while len(digits) < maxLen: digits.insert(0, 0) if (len(inputX) % 2 == 1): inputX.insert(0, 0) if (len(inputY) % 2 == 1): inputY.insert(0, 0) n = max(len(inputX), len(inputY)) // 2 # define x_hi, x_lo, y_hi and y_lo x_hi = inputX[:n] x_lo = inputX[n:] y_hi = inputY[:n] y_lo = inputY[n:] # calculate all multiplications with recursion [xy_hi, countAdd, countMult] = karatsuba(x_hi, True, y_hi, True, b, countAdd, countMult)[1:4] [xy_lo, countAdd, countMult] = karatsuba(x_lo, True, y_lo, True, b, countAdd, countMult)[1:4] [sumX, countAdd, countMult] = addition(x_hi, True, x_lo, True, b, countAdd, countMult)[1:4] [sumY, countAdd, countMult] = addition(y_hi, True, y_lo, True, b, countAdd, countMult)[1:4] [sumXY, countAdd, countMult] = karatsuba(sumX, True, sumY, True, b, countAdd, countMult)[1:4] [xy_positive, xy_temp, countAdd, countMult] = subtraction(sumXY, True, xy_hi, True, b, countAdd, countMult) [positiveMix, xy_mix, countAdd, countMult] = subtraction(xy_temp, xy_positive, xy_lo, True, b, countAdd, countMult) output = [0] * n * 10 for i in range(1, len(xy_lo) + 1): output[-i] += xy_lo[-i] countAdd += 1 for i in range(1, len(xy_mix) + 1): if positiveMix: output[-(i + n)] += xy_mix[-i] else: output[-(i + n)] -= xy_mix[-i] countAdd += 1 for i in range(1, len(xy_hi) + 1): output[-(i + 2 * n)] += xy_hi[-i] countAdd += 1 for i in range(1, len(output) + 1): rem = 0 if (output[-i] >= b): carry = output[-i] // b output[-i] = output[-i] % b output[-(i + 1)] += carry countAdd += 1 elif (output[-i] < 0): output[-(i + 1)] -= 1 rem = output[-i] + b output[-i] = rem countAdd += 2 i = 0 while i < (len(output) - 1): if (output[i] == 0): output.pop(0) continue break return [positiveOutput, output, countAdd, countMult] def euclidean(inputX, positiveX, inputY, positiveY, b): x1, x2, y1, y2 = [True, [1]], [True, [0]], [True, [0]], [True, [1]] eqZero = False numberX, numberY = inputX.copy(), inputY.copy() while not eqZero: [r, q] = modular_reduction(numberX, True, numberY, b)[1:3] numberX, numberY = numberY, r qx2 = karatsuba(q, True, x2[1], x2[0], b)[0:2] qy2 = karatsuba(q, True, y2[1], y2[0], b)[0:2] x3 = subtraction(x1[1], x1[0], qx2[1], qx2[0], b)[0:2] y3 = subtraction(y1[1], y1[0], qy2[1], qy2[0], b)[0:2] x1, y1 = x2, y2 x2, y2 = x3, y3 i = 0; while i < (len(numberY)-1): if (numberY[i] == 0): numberY.pop(0) continue break if (numberY[0] == 0): eqZero = True gcd = numberX if positiveX: x = x1 else: x = [not x1[0], x1[1]] if positiveY: y = y1 else: y = [not y1[0], y1[1]] return [gcd, x, y] def modular_reduction(inputX, positiveX, m, b): # len of input X and len of mod lenX = len(inputX) lenM = len(m) difLen = lenX - lenM coefficient = [0]*lenX positive = True eqZero = False output = inputX.copy() # step 2 for i in range(0, difLen + 1): positive = True coeffCounter = -1 n = difLen-i tempX = output.copy() modBase = m.copy() for j in range(n): modBase.append(0) while positive: coeffCounter += 1 output = tempX.copy() [positive, tempX] = subtraction(output, True, modBase, True, b)[0:2] #pak de positive output ding coefficient[-(n+1)] = coeffCounter i = 0; while i < (len(output)-1): if (output[i] == 0): output.pop(0) continue break if (output[0] == 0): eqZero = True if (positiveX or eqZero): return [True, output, coefficient] else: return [True, subtraction(m, True, output, True, b)[1], coefficient] def modular_addition(inputX, positiveX, inputY, positiveY, m, b): [positive, sumXY] = addition(inputX, positiveX, inputY, positiveY, b)[0:2] output = modular_reduction(sumXY, positive, m, b)[0:2] return output def modular_subtraction(inputX, positiveX, inputY, positiveY, m, b): [positive, diffXY] = subtraction(inputX, positiveX, inputY, positiveY, b)[0:2] output = modular_reduction(diffXY, positive, m, b)[0:2] return output def modular_multiplication(inputX, positiveX, inputY, positiveY, m, b): [positive, prodXY] = multiplication(inputX, positiveX, inputY, positiveY, b)[0:2] output = modular_reduction(prodXY, positive, m, b)[0:2] return output def modular_inversion(inputX, positiveX, m , b): a = modular_reduction(inputX, positiveX, m, b)[1] [gcd, x] = euclidean(a, True, m, True, b)[0:2] if (gcd == [1]): return modular_reduction(x[1], x[0], m, b)[0:2] else: return "inverse does not exist"
2wf90-assignment
/2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/algorithmsCombined.py
algorithmsCombined.py
class Integer: """ Class used to store large integers. Detailed documentation is given below, so here are some common use cases: from Integer import * i = Integer('6A', 16, False) i.digits -> [6, 10] i.radix -> 16 i.positive -> False i.digits[0] = 1 print(i) -> '-1A' repr(i) -> '-[1, 10] (radix 16)' i = -i print(i) -> '1A' len(i) -> 2 i = i.pad(6) repr(i) -> +[0, 0, 0, 0, 1, 10] (radix 16) len(i) -> 6 j = Integer([1, 10, 2, 13], 16) print(j) -> '1A2D' """ def __init__(self, digits, radix = 10, positive = True): """ Arguments: digits: A list of numbers - they should all be lower than the radix. The most significant numbers are at the beginning of this list. A string can be used as well, e.g. '13AF'. radix: radix of the number. Decimal by default. positive: True if the number has a positive sign, False if negative. Positive by default. Examples: Integer([1, 0, 14, 2], 16, False) -> -10E2 (radix 16) Integer('-100101', 2) -> -100101 (radix 2) Integer([1, 2, 3]) -> +123 (radix 10) """ if radix > 16: raise ValueError(f'radix is {radix}. radixs beyond 16 are not supported.') if radix < 1: raise ValueError(f'radix is {radix}. radix must be positive.') if len(digits) == 0: raise ValueError('Digit list cannot be empty.') # Sanity checks when digits are given as a list. if type(digits) is list: for digit in digits: if digit >= radix: raise ValueError(f'Digit {digit} is not allowed in radix {radix}.') if (digit < 0): raise ValueError(f'Digit {digit} may not be negative.') # Sanity checks when digits are given as a string. # Also transforms string into its list representation. if type(digits) is str: if digits[0] == '-': positive = False digits = digits[1:] new_digits = [] for digit in digits: num = char_to_number(digit) if num >= radix: raise ValueError(f'Digit {digit} is not allowed in radix {radix}.') new_digits.append(num) digits = new_digits self.digits = digits self.radix = radix self.positive = positive # We could remove leading zeroes here using self.strip(), but for # assignment 1 that shouldn't be neccesary. def __len__(self): """ Useful shortcut. Example: i = new Integer([1, 2, 3], 8) len(i) -> 3 len(i) == len(i.digits) -> True """ return len(self.digits) def __neg__(self): """ Negation operator. Example: i = new Integer('ABC', 16) i -> +[10, 11, 12] (radix 16) -i -> -[10, 11, 12] (radix 16) """ new_int = self.copy() new_int.positive = not new_int.positive return new_int def __str__(self): """ Represent integer as a string. The radix is not given, and a minus sign is added if negative. This is the same as notation found in input. Examples: str(Integer('6A', 16, False)) -> -6A """ return ('' if self.positive else '-') + f'{self.get_digit_string()}' def __repr__(self): """ Represent as string, but with more information. Useful for debugging. The digit list is always printed, along with the sign and radix. Examples: repr(Integer('6A', 16, False)) -> -[6, 10] (radix 16) """ return ('+' if self.positive else '-') + f'{self.digits} (radix {self.radix})' def __abs__(self): if self.positive: return self.copy() else: return -self def pad(self, size): """ Add leading zeroes to the digit list to ensure it becomes a certain size. Returns a new copy of the Integer, so that the original one isn't modified. Example: i = Integer([1]) i = i.pad(4) i.digits -> [0, 0, 0, 1] """ original_size = len(self.digits) if size < original_size: raise ValueError(f'New size {size} is below original size {original_size}') new_int = self.copy() new_int.digits = [0] * (size - original_size) + new_int.digits return new_int def strip(self): """ Remove trailing zeroes from the digit list. Undoes Integer.pad(). Also called in the constructor. """ new_int = self.copy() while new_int.digits[0] == 0 and len(new_int.digits) > 1: new_int.digits = new_int.digits[1:] return new_int def get_digit_string(self): """ Returns the integer's digits as a string, not a list. It converts digits above 9 to the hexadecimal counterparts. Used by the class internally. Don't call it directly, but use print(i) instead. """ s = '' for digit in self.digits: s = s + number_to_char(digit) return s def copy(self): """ Returns a distinct copy of itself. """ digits_copy = self.digits.copy() return Integer(digits_copy, self.radix, self.positive) def char_to_number(character): character = character.upper() index = '0123456789ABCDEF'.find(character) if index == -1: raise ValueError('Character must be hexadecimal notation.') return index def number_to_char(number): return '0123456789abcdef'[number] # ;)
2wf90-assignment
/2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/Integer.py
Integer.py
import re from Integer import * from algorithmsCombined import * class Context(): """ """ def __init__(self): self.reset() def reset(self): self.x = None self.y = None self.radix = None self.op = None self.m = None def read_line(self, line): original_line = line line = re.sub('\s', '', line) # Remove all whitespace if len(line) == 0: if not self.op: return '\n' if self.op in (addition, subtraction): computed = self.op(self.x.digits, self.x.positive, self.y.digits, self.y.positive, self.x.radix) answer = Integer(computed[1], self.radix, computed[0]) self.reset() return f'[answer] {answer}\n\n' elif self.op in (multiplication, karatsuba): computed = self.op(self.x.digits, self.x.positive, self.y.digits, self.y.positive, self.x.radix) answer = Integer(computed[1], self.radix, computed[0]) add = computed[2] mul = computed[3] self.reset() return f'[answer] {answer}\n[count-add] {add}\n[count-mul] {mul}\n\n' elif self.op in (modular_reduction, modular_inversion): computed = self.op(self.x.digits, self.x.positive, self.m.digits, self.x.radix) if isinstance(computed, str): self.reset() return '[answer] inverse does not exist\n\n' else: answer = Integer(computed[1], self.radix, computed[0]) self.reset() return f'[answer] {answer}\n\n' elif self.op in (modular_addition, modular_subtraction, modular_multiplication): computed = self.op(self.x.digits, self.x.positive, self.y.digits, self.y.positive, self.m.digits, self.x.radix) answer = Integer(computed[1], self.radix, computed[0]) self.reset() return f'[answer] {answer}\n\n' elif self.op == euclidean: computed = self.op(self.x.digits, self.x.positive, self.y.digits, self.y.positive, self.x.radix) d = Integer(computed[0], self.x.radix) a = Integer(computed[1][1], self.x.radix, computed[1][0]) b = Integer(computed[2][1], self.x.radix, computed[2][0]) self.reset() return f'[answ-d] {d}\n[answ-a] {a}\n[answ-b] {b}\n\n' if line[0] == '#': # Line is a comment, just return it return original_line bracket_index = line.find(']') command = line[1:bracket_index] # Extract text between brackets argument = line[bracket_index + 1:] # Extract argument after command if command == 'radix': self.radix = int(argument) elif command == 'x': self.x = Integer(argument, self.radix) elif command == 'y': self.y = Integer(argument, self.radix) elif command == 'm': self.m = Integer(argument, self.radix) if self.op == addition: self.op = modular_addition elif self.op == subtraction: self.op = modular_subtraction elif self.op == multiplication: self.op = modular_multiplication elif command == 'add': if self.m: self.op = modular_addition else: self.op = addition elif command == 'subtract': if self.m: self.op = modular_subtraction else: self.op = subtraction elif command == 'multiply': if self.m: self.op = modular_multiplication else: self.op = multiplication elif command == 'karatsuba': self.op = karatsuba elif command == 'reduce': self.op = modular_reduction elif command == 'inverse': self.op = modular_inversion elif command == 'euclid': self.op = euclidean elif command in ('answer', 'count-add', 'count-mul', 'answ-d', 'answ-a', 'answ-b'): # Ignore and don't write to output return '' return original_line
2wf90-assignment
/2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/Context.py
Context.py
def subtract_function(x, y, b, m=None): base = {'0':0,'1':1,'2':2,'3':3, '4':4,'5':5,'6':6,'7':7, '8':8,'9':9,'a':10,'b':11, 'c':12,'d':13,'e':14,'f':15} X = str(x) Y = str(y) carry = 0 dig = 0 maxL = max(len(X), len(Y)) X = X.zfill(maxL) Y = Y.zfill(maxL) X2 = list(X) Y2 = list(Y) # maka sure the modulo has the same length as x and y if m is not None: m = m.zfill(maxL) result = [] if x == 0 and m is None: return -int(y) if y == 0 and m is None: return x if b == 10: if m is None: return str(int(x) - int(y)) else: return (int(x) - int(y)) % int(m) if x == y: return '0' # deal with negative numbers if X[0] == '-' and Y[0] == '-': Y = Y.replace('-','') return add_function(Y,X,b,m) if X[0] == '-': Y = '-' + Y return add_function(X,Y,b,m) if Y[0] == '-': Y = Y.replace('-','') return add_function(X,Y,b,m) if x > y: # convert abcdef into integers for i in range(maxL): X2[i] = base.get(X2[i]) Y2[i] = base.get(Y2[i]) for i in range(1,maxL+1): if X2[-i] >= Y2[-i]: dig = X2[-i] - Y2[-i] if X2[-i] < Y2[-i]: #take a borrow X2[-i-1] -= 1 X2[-i] += b dig = X2[-i] - Y2[-i] result.append(dig) for i in range(maxL): invMap = {v: k for k, v in base.items()} # remap the dictionary such that integers >= 10 # are converted to alphabet result[i] = invMap.get(result[i]) if X2 > Y2: answer = ''.join(result[::-1]) if m is not None: answer = simple_division(answer, m, b) if answer[0] is "0": answer = answer[1:] return answer else: result = subtract_function(y,x,b,m) if x < y: return '-' + subtract_function(y,x,b,m)
2wf90-assignment
/2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/unused/subtract_modulo.py
subtract_modulo.py
def add_function(x, y, b, m=None): base = {'0':0,'1':1,'2':2,'3':3, '4':4,'5':5,'6':6,'7':7, '8':8,'9':9,'a':10,'b':11, 'c':12,'d':13,'e':14,'f':15} X = str(x) Y = str(y) carry = 0 result = '' if x == '0' and m is None: return y if y == '0' and m is None: return x if y == '0' and x == '0': return '0' if b == 10: if m is None: return str(int(x)+int(y)) else: return (int(x) + int(y)) % int(m) if X[0] == '-' and Y[0] == '-': #both inputs are minus, take -sign out and do normal addition count = 1 X = X.replace('-','') Y = Y.replace('-','') return add_function(X,Y,b) if X[0] == '-': X = X.replace('-','') return subtract_function(Y,X,b) if Y[0] == '-': Y = Y.replace('-','') return subtract_function(X,Y,b) if b >= 2 and b <= 16: result = [] maxL = max(len(X), len(Y)) X = X.zfill(maxL) Y = Y.zfill(maxL) X2 = list(X) Y2 = list(Y) # maka sure the modulo has the same length as x and y if m is not None: m = m.zfill(maxL) # convert abcdef into integers for i in range(maxL): X2[i] = base.get(X2[i]) Y2[i] = base.get(Y2[i]) # primary school method of addition for i in range(1,maxL+1): dig = X2[-i] + Y2[-i] + carry if dig >= b: carry = 1 dig %= b else: carry = 0 result.append(dig) if carry == 1: result.append(str(carry)) # remap the dictionary such that integers >= 10 # are converted to alphabet for i in range(maxL): invMap = {v: k for k, v in base.items()} result[i] = invMap.get(result[i]) answer = ''.join(result[::-1]) # if m, divide by m and keep remainder as answer if m is not None: answer = simple_division(answer, m, b)[1] if answer[0] is "0": answer = answer[1:] return answer
2wf90-assignment
/2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/unused/addition_modulo.py
addition_modulo.py
import builtins import logging import progressbar from PIL import ImageColor from sty import fg from .imgcat import imgcat progressbar.streams.wrap_stderr() # TODO: Implement word wrapping # Set to True to have the module name column dynamically resize as it grows # TODO: Set option via different import DYNAMIC_WIDTH = False # Colors taken from https://lospec.com/palette-list/blk-neo colors = [ fg(*ImageColor.getrgb(c)) for c in [ "#909EDD", "#C1D9F2", "#FFCCD0", "#F29FAA", "#E54286", "#FF6EAF", "#FFA5D5", "#8CFF9B", "#42BC7F", "#3E83D1", "#50B9EB", "#8CDAFF", "#B483EF", "#854CBF", "#FFE091", "#FFAA6E", "#78FAE6", "#27D3CB", ] ] log = logging.getLogger("Rack") log.setLevel(logging.DEBUG) current_width = 10 if DYNAMIC_WIDTH else 30 max_width = 30 first_log = True class LoggingFilter(logging.Filter): def filter(self, record): global current_width, first_log name = "%s.%s" % (record.module, record.funcName) lineno = len(str(record.lineno)) lines = record.msg.split("\n") new_lines = [lines[0]] if len(name) + 1 + lineno > current_width and current_width < max_width: gap = current_width current_width = min(len(name) + 1 + lineno, max_width) gap = current_width - gap if not first_log: new_lines.append( " " * 8 + " │ " + " " * 7 + " │ " + " " * (current_width - gap) + f" └{'─' * (gap - 1)}┐ " ) else: first_log = False max_len = current_width - 1 - lineno if len(name) > max_len: name = name[:max_len - 1] + "…" quick_checksum = sum(bytearray(name.encode("utf-8"))) color = colors[quick_checksum % len(colors)] just = current_width - len(name + ":" + str(record.lineno)) record.fullname = f"{color}{name}:{record.lineno}{fg.rs}" + " " * just indent = " " * 8 + " │ " + " " * 7 + " │ " + " " * current_width + " │ " for line in lines[1:]: new_lines.append(indent + line) if hasattr(record, "img"): height_chars = 5 if hasattr(record, "img_height"): height_chars = record.img_height img = imgcat(record.img, height_chars=height_chars) if img: go_up = f"\033[{height_chars}A" new_lines.append(indent) new_lines.append(indent + img + go_up) new_lines.extend([indent] * height_chars) record.msg = "\n".join(new_lines) return True log.addFilter(LoggingFilter()) formatter = logging.Formatter( "{asctime:8} │ {levelname} │ {fullname} │ {message}", # datefmt="%Y-%m-%d %H:%M:%S", datefmt="%H:%M:%S", style="{" ) handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) logging.addLevelName(logging.DEBUG, " debug " ) # noqa logging.addLevelName(logging.INFO, " inf " ) # noqa logging.addLevelName(logging.WARNING, fg(208) + "warning" + fg.rs) logging.addLevelName(logging.ERROR, fg(196) + " error " + fg.rs) logging.addLevelName(logging.CRITICAL, fg(196) + " fatal " + fg.rs) log.addHandler(handler) builtins.log = log # type: ignore class log_progress(object): @staticmethod def progressBar(log_level, iterable): if log_level < log.getEffectiveLevel(): return iterable progress = progressbar.ProgressBar( widgets=[ progressbar.CurrentTime(format="%(current_time)s"), " │ % │ │" " ", progressbar.SimpleProgress(), " ", progressbar.Percentage(format="(%(percentage)d%%)"), " ", progressbar.Bar(left=" ", right=" ", marker="▓", fill="░"), " ", progressbar.Timer(), " ", progressbar.AdaptiveETA(), ], redirect_stdout=True, ) return progress(iterable) @staticmethod def debug(iterable): return log_progress.progressBar(logging.DEBUG, iterable) @staticmethod def info(iterable): return log_progress.progressBar(logging.INFO, iterable) @staticmethod def warning(iterable): return log_progress.progressBar(logging.WARNING, iterable) @staticmethod def error(iterable): return log_progress.progressBar(logging.ERROR, iterable) @staticmethod def critical(iterable): return log_progress.progressBar(logging.CRITICAL, iterable)
2xh-leet
/2xh_leet-1.0.1-py3-none-any.whl/leet/logging.py
logging.py
Copyright (c) 2022 Vladimir Chebotarev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3-py
/3-py-1.1.6.tar.gz/3-py-1.1.6/LICENSE.md
LICENSE.md
# 31 31 is a simple tool you can use to run code in the background on a server. For example ``` 31 c 'sleep 100; echo 2' ``` runs the command `sleep 100; echo 2` in a screen session then sends you an email with the output of the command once it is complete. ## Setup Install 31 by running ``` pip install 31 ``` Then set up your email address by running ``` 31 config email youremail@example.com ``` ### Quick dependency setup On ubuntu you can run ``` sudo apt install screen mailutils ``` to quickly set up the dependencies needed. ### Detailed dependency setup #### Mail program By default, `31` searches for a mail program to use from the following list. You can also force it to use one of the programs by using the command ``` 31 config mail_program <mail program name> ``` - `gnu_mail`. To install on ubuntu you can run ``` sudo apt install mailutils ``` - `mutt`. To install on ubuntu you can run ``` sudo apt install mutt ``` #### Screen Manager Currently 31 only supports `screen`. To install screen on ubuntu run ``` sudo apt install screen ``` ## Options See `31 -h` for a full list of options. This section covers only some of the more complicated ones ### Foreach This option allows you to run multiple commands with text substitution. As a basic usage example, the code ```sh 31 c -f %x 1,2,3 'touch %x.txt' ``` Creates each of the files `1.txt`, `2.txt`, and `3.txt`. The variable substitution is managed via direct text-substitution, and thus your variables do not need to begin with %, this works equally well (though is far less readable) ```sh 31 c -f 2 1,2,3 'touch 2.txt' ``` You can also modify two variables in tandem like this: ```sh 31 c -f2 %x %ext 1,2,3 txt,png,py 'touch %x.%ext' ``` This creates the files `1.txt`, `2.png`, `3.py`. If you instead want to create all combinations, you can run: ```sh 31 c -f %x 1,2,3 -f %ext txt,png,py 'touch %x.%ext' ``` This creates the files `1.txt`, `1.png`, `1.py`, `2.txt`, `2.png`, `2.py`, `3.txt`, `3.png`, `3.py`. The values field is in comma-separated-value form, which means you can use `"` as a CSV escape, as such: ```sh 31 -c -f %x '",",2' `touch %x.txt` ``` which creates the files `,.txt` and `2.txt`.
31
/31-2.2.tar.gz/31-2.2/README.md
README.md
import argparse import sys import os import json from .config import Config, update_config from .notify import notify from .command import Command from .foreach import MAX_FOREACHES, parse_foreach_args, parse_values from .interruptable_runner import InterruptableRunner from .process_manager import list_procesess, stop_process from .utils import format_assignments, sanitize, set_key from .workers import dispatch_workers def main(): def config_argument(p): p.add_argument( "--config-file", default=os.path.expanduser("~/.31rc"), help="The location of the configuration file", ) parser = argparse.ArgumentParser("31") subparsers = parser.add_subparsers(dest="cmd") subparsers.required = True command_parser = subparsers.add_parser( "command", help="Run a command", aliases=["c"] ) config_argument(command_parser) command_parser.add_argument( "-s", "--sync", action="store_true", help="Run the command synchronously, that is, not in a screen session", ) command_parser.add_argument( "-n", "--screen-name", help="The name of the screen session to create" ) command_parser.add_argument( "-l", "--location", help="The location to run the script" ) command_parser.add_argument( "--no-email", help="Do not send an email when the command is done running", action="store_true", ) command_parser.add_argument( "-d", "--dry-run", help="Print out the commands to be run rather than running them", action="store_true", ) command_parser.add_argument( "-f", "--foreach", metavar=("%var", "vals"), nargs=2, action="append", help="Replaces each occurence of the variable with the corresponding value. " "Variables can be any sequence of characters. " "After the variables, values can be provided, each list of values should be a single argument in CSV format. " "See the documentation for details and examples.", ) command_parser.add_argument( "-fw", "--foreach-worker", nargs=2, metavar=("%var", "vals"), action="append", help="Similar to -f but associates each substitution with a particular variable. " "Notably, this does not lead to a combinatoric explosion if multiple are used, they are " "implicitly zipped together by the worker index", ) for k in range(2, 1 + MAX_FOREACHES): meta = tuple("%var{}".format(i) for i in range(1, k + 1)) meta += tuple("vals{}".format(i) for i in range(1, k + 1)) command_parser.add_argument( "-f" + str(k), "--foreach-" + str(k), metavar=meta, nargs=k * 2, action="append", help="See -f for details, -f2 through -f{0} allow you to zip the values for 2-{0} variables together.".format( MAX_FOREACHES ) if k == 2 else argparse.SUPPRESS, ) # internal use only, specifies which foreach args to use, in json format [(name, value)] command_parser.add_argument( "--foreach-specified-args", type=json.loads, help=argparse.SUPPRESS ) command_parser.add_argument( "-w", "--max-workers", type=int, help="Limit the number of threads that are to be launched at any point. " "This forces the creation of a monitoring thread, for which --sync is applied to", ) command_parser.add_argument( "-wn", "--worker-monitor-name", default="worker-monitor", help="Names the screen for the worker thread. By default is 'worker-monitor'", ) # internal use only, specifies that when the process is done, it should set the given key of the given file. command_parser.add_argument( "--when-done-set", nargs=2, metavar=("file", "key"), help=argparse.SUPPRESS ) command_parser.add_argument("command", help="Command to run") command_parser.set_defaults(action=command_action) config_parser = subparsers.add_parser("config", help="Modify configuration") config_argument(config_parser) config_parser.add_argument("key", help="The configuration key to modify") config_parser.add_argument("value", help="The value to assign the given key to") config_parser.set_defaults(action=config_action) list_parser = subparsers.add_parser("list", help="List all commands", aliases=["l"]) config_argument(list_parser) list_parser.add_argument( "prefix", help="Only list commands whose names start with the given prefix", nargs="?", ) list_parser.add_argument( "-o", "--ordering", help="The ordering to use", choices=["timestamp", "name"], default="timestamp", ) list_parser.set_defaults(action=list_action) stop_parser = subparsers.add_parser("stop", help="Stop a command", aliases=["s"]) config_argument(stop_parser) stop_parser.add_argument("name", help="The name of the command to stop") stop_parser.add_argument( "-m", "--multi", help="Stop all commands with the given prefix, even if there are multiple or it isn't the full name", action="store_true", ) stop_parser.set_defaults(action=stop_action) args = parser.parse_args() try: args.action(args) except RuntimeError as e: print(e, file=sys.stderr) def command_action(args): try: return do_command_action(args) finally: if args.when_done_set is not None: set_key(*args.when_done_set) def do_command_action(args): config = Config(args.config_file) assignments = ( [args.foreach_specified_args] if args.foreach_specified_args is not None else parse_foreach_args(args) ) worker_assignments = [] # Validation if args.foreach_worker is not None: for variable, vals in args.foreach_worker: if args.max_workers is None: raise RuntimeError("Cannot provide -fw without -w") vals = parse_values(vals) if len(vals) != args.max_workers: raise RuntimeError( "Mismatch between number of workers and number of provided values" ) worker_assignments.append((variable, vals)) commands = [] for assignment in assignments: screen_name = sanitize( format_assignments(args.screen_name or args.command, assignment) ) cmd = Command(cmd_line=args.command, location=args.location) cmd_to_use = cmd.replace(assignment) commands.append((screen_name, cmd_to_use, assignment)) if args.dry_run: for screen_name, cmd_to_use, _ in commands: if not args.sync: print("# on screen {}".format(screen_name)) cmd_to_use.dry_run() return if not args.sync: if args.max_workers is not None: config.launch_screen(sys.argv + ["--sync"], args.worker_monitor_name) return for screen_name, _, assignment in commands: config.launch_screen( sys.argv + ["--sync", "--foreach-specified-args", json.dumps(assignment)], screen_name, ) return if args.max_workers is not None and args.foreach_specified_args is None: # if foreach-specified-args is set, this is a dispatch thread def launch_worker(worker_idx, assignment, output_file, token): assignment = assignment + [ (var, vals[worker_idx]) for var, vals in worker_assignments ] screen_name = sanitize( format_assignments(args.screen_name or args.command, assignment) ) print("Launching {}".format(screen_name)) # don't need the --sync since at this point it is guaranteed config.launch_screen( sys.argv + [ "--foreach-specified-args", json.dumps(assignment), "--when-done-set", output_file, token, ], screen_name, ) dispatch_workers(args.max_workers, launch_worker, assignments) return for screen_name, cmd_to_use, _ in commands: runner = InterruptableRunner(screen_name, os.getpid(), cmd_to_use) if args.no_email: runner.run_checking_interrupt(cmd_to_use.run) else: notify(config, cmd_to_use, runner) def config_action(args): update_config(args.config_file, {args.key: args.value}) def list_action(args): list_procesess(args.prefix, args.ordering) def stop_action(args): stop_process(args.name)
31
/31-2.2.tar.gz/31-2.2/s31/main.py
main.py
import time import uuid import threading import random from .active_process_table import active_process_table INTERRUPTED_BANNER = """ ======================================= INTERRUPTED BY USER ======================================= """ POLL_INTERVAL = 2 class InterruptableRunner: def __init__(self, name, pid, cmd_to_use): self.name = name self.pid = pid self.cmd_to_use = cmd_to_use self.guid = str(uuid.uuid4()) self.timestamp = time.time() self.alive = False def pre(self): with active_process_table() as t: t[self.guid] = dict( name=self.name, pid=self.pid, cmd=self.cmd_to_use.cmd_line, timestamp=self.timestamp, last_update=self.timestamp, ) self.alive = True while_alive_thread = threading.Thread(target=self.while_alive) while_alive_thread.start() def post(self): self.alive = False with active_process_table() as t: del t[self.guid] def while_alive(self): while self.alive: with active_process_table() as t: if self.guid in t: val = t[self.guid] val["last_update"] = time.time() t[self.guid] = val time.sleep(random.uniform(0.5 * POLL_INTERVAL, 1.5 * POLL_INTERVAL)) def run_checking_interrupt(self, fn, interrupted_banner_path=None): try: self.pre() exitcode = fn() except KeyboardInterrupt: exitcode = "interrupted" if interrupted_banner_path is not None: with open(interrupted_banner_path, "ab") as f: f.write(INTERRUPTED_BANNER.encode("utf-8")) finally: self.post() return exitcode def clean_table(apt): now = time.time() for guid, val in apt.items(): if now - val["last_update"] > 2 * POLL_INTERVAL: del apt[guid]
31
/31-2.2.tar.gz/31-2.2/s31/interruptable_runner.py
interruptable_runner.py
"use strict"; (self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []).push([["lib_index_js"],{ /***/ "./lib/index.js": /*!**********************!*\ !*** ./lib/index.js ***! \**********************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/mainmenu */ "webpack/sharing/consume/default/@jupyterlab/mainmenu"); /* harmony import */ var _jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/widgets */ "webpack/sharing/consume/default/@lumino/widgets"); /* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_widgets__WEBPACK_IMPORTED_MODULE_1__); const extension = { id: '310_notebook', autoStart: true, requires: [_jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0__.IMainMenu], optional: [], activate: (app, mainMenu) => { console.log('menu2'); // Add an application command const { commands } = app; const command = '310notebook:logout'; commands.addCommand(command, { label: 'Logout 310.ai notebook panel', execute: () => { location.href = 'https://310.ai/notebook/signout'; } }); // Create a new menu const menu = new _lumino_widgets__WEBPACK_IMPORTED_MODULE_1__.Menu({ commands }); menu.title.label = '310.ai'; // Open Zethus // menu.addItem({ type: 'separator' }); menu.addItem({ command: '310notebook:logout', args: {} }); mainMenu.addMenu(menu, { rank: 100 }); // // Open Logger // menu.addItem({ command: 'jupyterlab-ros/logConsole:open' }); // menu.addItem({ type: 'separator' }); // // Open Settings // menu.addItem({ command: 'jupyterlab-ros/settings:open' }); } }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (extension); /***/ }) }]); //# sourceMappingURL=lib_index_js.13f87d19a930eafd5230.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook-0.1.0.data/data/share/jupyter/labextensions/310_notebook/static/lib_index_js.13f87d19a930eafd5230.js
lib_index_js.13f87d19a930eafd5230.js
"use strict"; (self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []).push([["style_index_js"],{ /***/ "./node_modules/css-loader/dist/cjs.js!./style/base.css": /*!**************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js!./style/base.css ***! \**************************************************************/ /***/ ((module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../node_modules/css-loader/dist/runtime/cssWithMappingToString.js */ "./node_modules/css-loader/dist/runtime/cssWithMappingToString.js"); /* harmony import */ var _node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../node_modules/css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js"); /* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__); // Imports var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0___default())); // Module ___CSS_LOADER_EXPORT___.push([module.id, "/*\n See the JupyterLab Developer Guide for useful CSS Patterns:\n\n https://jupyterlab.readthedocs.io/en/stable/developer/css.html\n*/\n\n.my-apodWidget {\n display: flex;\n flex-direction: column;\n align-items: center;\n overflow: auto;\n }", "",{"version":3,"sources":["webpack://./style/base.css"],"names":[],"mappings":"AAAA;;;;CAIC;;AAED;IACI,aAAa;IACb,sBAAsB;IACtB,mBAAmB;IACnB,cAAc;EAChB","sourcesContent":["/*\n See the JupyterLab Developer Guide for useful CSS Patterns:\n\n https://jupyterlab.readthedocs.io/en/stable/developer/css.html\n*/\n\n.my-apodWidget {\n display: flex;\n flex-direction: column;\n align-items: center;\n overflow: auto;\n }"],"sourceRoot":""}]); // Exports /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___); /***/ }), /***/ "./style/base.css": /*!************************!*\ !*** ./style/base.css ***! \************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js"); /* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _node_modules_css_loader_dist_cjs_js_base_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !!../node_modules/css-loader/dist/cjs.js!./base.css */ "./node_modules/css-loader/dist/cjs.js!./style/base.css"); var options = {}; options.insert = "head"; options.singleton = false; var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_base_css__WEBPACK_IMPORTED_MODULE_1__["default"], options); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_base_css__WEBPACK_IMPORTED_MODULE_1__["default"].locals || {}); /***/ }), /***/ "./style/index.js": /*!************************!*\ !*** ./style/index.js ***! \************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony import */ var _base_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.css */ "./style/base.css"); /***/ }) }]); //# sourceMappingURL=style_index_js.547b86f938c46e9f74f6.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook-0.1.0.data/data/share/jupyter/labextensions/310_notebook/static/style_index_js.547b86f938c46e9f74f6.js
style_index_js.547b86f938c46e9f74f6.js
"use strict"; (self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []).push([["vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1"],{ /***/ "./node_modules/css-loader/dist/runtime/api.js": /*!*****************************************************!*\ !*** ./node_modules/css-loader/dist/runtime/api.js ***! \*****************************************************/ /***/ ((module) => { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader // eslint-disable-next-line func-names module.exports = function (cssWithMappingToString) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item); if (item[2]) { return "@media ".concat(item[2], " {").concat(content, "}"); } return content; }).join(""); }; // import a list of modules into the list // eslint-disable-next-line func-names list.i = function (modules, mediaQuery, dedupe) { if (typeof modules === "string") { // eslint-disable-next-line no-param-reassign modules = [[null, modules, ""]]; } var alreadyImportedModules = {}; if (dedupe) { for (var i = 0; i < this.length; i++) { // eslint-disable-next-line prefer-destructuring var id = this[i][0]; if (id != null) { alreadyImportedModules[id] = true; } } } for (var _i = 0; _i < modules.length; _i++) { var item = [].concat(modules[_i]); if (dedupe && alreadyImportedModules[item[0]]) { // eslint-disable-next-line no-continue continue; } if (mediaQuery) { if (!item[2]) { item[2] = mediaQuery; } else { item[2] = "".concat(mediaQuery, " and ").concat(item[2]); } } list.push(item); } }; return list; }; /***/ }), /***/ "./node_modules/css-loader/dist/runtime/cssWithMappingToString.js": /*!************************************************************************!*\ !*** ./node_modules/css-loader/dist/runtime/cssWithMappingToString.js ***! \************************************************************************/ /***/ ((module) => { function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = function cssWithMappingToString(item) { var _item = _slicedToArray(item, 4), content = _item[1], cssMapping = _item[3]; if (!cssMapping) { return content; } if (typeof btoa === "function") { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping)))); var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64); var sourceMapping = "/*# ".concat(data, " */"); var sourceURLs = cssMapping.sources.map(function (source) { return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */"); }); return [content].concat(sourceURLs).concat([sourceMapping]).join("\n"); } return [content].join("\n"); }; /***/ }), /***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js": /*!****************************************************************************!*\ !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var isOldIE = function isOldIE() { var memo; return function memorize() { if (typeof memo === 'undefined') { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 memo = Boolean(window && document && document.all && !window.atob); } return memo; }; }(); var getTarget = function getTarget() { var memo = {}; return function memorize(target) { if (typeof memo[target] === 'undefined') { var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { try { // This will throw an exception if access to iframe is blocked // due to cross-origin restrictions styleTarget = styleTarget.contentDocument.head; } catch (e) { // istanbul ignore next styleTarget = null; } } memo[target] = styleTarget; } return memo[target]; }; }(); var stylesInDom = []; function getIndexByIdentifier(identifier) { var result = -1; for (var i = 0; i < stylesInDom.length; i++) { if (stylesInDom[i].identifier === identifier) { result = i; break; } } return result; } function modulesToDom(list, options) { var idCountMap = {}; var identifiers = []; for (var i = 0; i < list.length; i++) { var item = list[i]; var id = options.base ? item[0] + options.base : item[0]; var count = idCountMap[id] || 0; var identifier = "".concat(id, " ").concat(count); idCountMap[id] = count + 1; var index = getIndexByIdentifier(identifier); var obj = { css: item[1], media: item[2], sourceMap: item[3] }; if (index !== -1) { stylesInDom[index].references++; stylesInDom[index].updater(obj); } else { stylesInDom.push({ identifier: identifier, updater: addStyle(obj, options), references: 1 }); } identifiers.push(identifier); } return identifiers; } function insertStyleElement(options) { var style = document.createElement('style'); var attributes = options.attributes || {}; if (typeof attributes.nonce === 'undefined') { var nonce = true ? __webpack_require__.nc : 0; if (nonce) { attributes.nonce = nonce; } } Object.keys(attributes).forEach(function (key) { style.setAttribute(key, attributes[key]); }); if (typeof options.insert === 'function') { options.insert(style); } else { var target = getTarget(options.insert || 'head'); if (!target) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid."); } target.appendChild(style); } return style; } function removeStyleElement(style) { // istanbul ignore if if (style.parentNode === null) { return false; } style.parentNode.removeChild(style); } /* istanbul ignore next */ var replaceText = function replaceText() { var textStore = []; return function replace(index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; }(); function applyToSingletonTag(style, index, remove, obj) { var css = remove ? '' : obj.media ? "@media ".concat(obj.media, " {").concat(obj.css, "}") : obj.css; // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = style.childNodes; if (childNodes[index]) { style.removeChild(childNodes[index]); } if (childNodes.length) { style.insertBefore(cssNode, childNodes[index]); } else { style.appendChild(cssNode); } } } function applyToTag(style, options, obj) { var css = obj.css; var media = obj.media; var sourceMap = obj.sourceMap; if (media) { style.setAttribute('media', media); } else { style.removeAttribute('media'); } if (sourceMap && typeof btoa !== 'undefined') { css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */"); } // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = css; } else { while (style.firstChild) { style.removeChild(style.firstChild); } style.appendChild(document.createTextNode(css)); } } var singleton = null; var singletonCounter = 0; function addStyle(obj, options) { var style; var update; var remove; if (options.singleton) { var styleIndex = singletonCounter++; style = singleton || (singleton = insertStyleElement(options)); update = applyToSingletonTag.bind(null, style, styleIndex, false); remove = applyToSingletonTag.bind(null, style, styleIndex, true); } else { style = insertStyleElement(options); update = applyToTag.bind(null, style, options); remove = function remove() { removeStyleElement(style); }; } update(obj); return function updateStyle(newObj) { if (newObj) { if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { return; } update(obj = newObj); } else { remove(); } }; } module.exports = function (list, options) { options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (!options.singleton && typeof options.singleton !== 'boolean') { options.singleton = isOldIE(); } list = list || []; var lastIdentifiers = modulesToDom(list, options); return function update(newList) { newList = newList || []; if (Object.prototype.toString.call(newList) !== '[object Array]') { return; } for (var i = 0; i < lastIdentifiers.length; i++) { var identifier = lastIdentifiers[i]; var index = getIndexByIdentifier(identifier); stylesInDom[index].references--; } var newLastIdentifiers = modulesToDom(newList, options); for (var _i = 0; _i < lastIdentifiers.length; _i++) { var _identifier = lastIdentifiers[_i]; var _index = getIndexByIdentifier(_identifier); if (stylesInDom[_index].references === 0) { stylesInDom[_index].updater(); stylesInDom.splice(_index, 1); } } lastIdentifiers = newLastIdentifiers; }; }; /***/ }) }]); //# sourceMappingURL=vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1.a3ba3318a5d7528b56d6.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook-0.1.0.data/data/share/jupyter/labextensions/310_notebook/static/vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1.a3ba3318a5d7528b56d6.js
vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1.a3ba3318a5d7528b56d6.js
var _JUPYTERLAB; /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "webpack/container/entry/310_notebook": /*!***********************!*\ !*** container entry ***! \***********************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var moduleMap = { "./index": () => { return __webpack_require__.e("lib_index_js").then(() => (() => ((__webpack_require__(/*! ./lib/index.js */ "./lib/index.js"))))); }, "./extension": () => { return __webpack_require__.e("lib_index_js").then(() => (() => ((__webpack_require__(/*! ./lib/index.js */ "./lib/index.js"))))); }, "./style": () => { return Promise.all([__webpack_require__.e("vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1"), __webpack_require__.e("style_index_js")]).then(() => (() => ((__webpack_require__(/*! ./style/index.js */ "./style/index.js"))))); } }; var get = (module, getScope) => { __webpack_require__.R = getScope; getScope = ( __webpack_require__.o(moduleMap, module) ? moduleMap[module]() : Promise.resolve().then(() => { throw new Error('Module "' + module + '" does not exist in container.'); }) ); __webpack_require__.R = undefined; return getScope; }; var init = (shareScope, initScope) => { if (!__webpack_require__.S) return; var name = "default" var oldScope = __webpack_require__.S[name]; if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope"); __webpack_require__.S[name] = shareScope; return __webpack_require__.I(name, initScope); }; // This exports getters to disallow modifications __webpack_require__.d(exports, { get: () => (get), init: () => (init) }); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = __webpack_modules__; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = __webpack_module_cache__; /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/ensure chunk */ /******/ (() => { /******/ __webpack_require__.f = {}; /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = (chunkId) => { /******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => { /******/ __webpack_require__.f[key](chunkId, promises); /******/ return promises; /******/ }, [])); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/get javascript chunk filename */ /******/ (() => { /******/ // This function allow to reference async chunks /******/ __webpack_require__.u = (chunkId) => { /******/ // return url for filenames based on template /******/ return "" + chunkId + "." + {"lib_index_js":"13f87d19a930eafd5230","vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1":"a3ba3318a5d7528b56d6","style_index_js":"547b86f938c46e9f74f6"}[chunkId] + ".js"; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/load script */ /******/ (() => { /******/ var inProgress = {}; /******/ var dataWebpackPrefix = "310_notebook:"; /******/ // loadScript function to load a script via script tag /******/ __webpack_require__.l = (url, done, key, chunkId) => { /******/ if(inProgress[url]) { inProgress[url].push(done); return; } /******/ var script, needAttach; /******/ if(key !== undefined) { /******/ var scripts = document.getElementsByTagName("script"); /******/ for(var i = 0; i < scripts.length; i++) { /******/ var s = scripts[i]; /******/ if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; } /******/ } /******/ } /******/ if(!script) { /******/ needAttach = true; /******/ script = document.createElement('script'); /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.setAttribute("data-webpack", dataWebpackPrefix + key); /******/ script.src = url; /******/ } /******/ inProgress[url] = [done]; /******/ var onScriptComplete = (prev, event) => { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var doneFns = inProgress[url]; /******/ delete inProgress[url]; /******/ script.parentNode && script.parentNode.removeChild(script); /******/ doneFns && doneFns.forEach((fn) => (fn(event))); /******/ if(prev) return prev(event); /******/ } /******/ ; /******/ var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000); /******/ script.onerror = onScriptComplete.bind(null, script.onerror); /******/ script.onload = onScriptComplete.bind(null, script.onload); /******/ needAttach && document.head.appendChild(script); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/sharing */ /******/ (() => { /******/ __webpack_require__.S = {}; /******/ var initPromises = {}; /******/ var initTokens = {}; /******/ __webpack_require__.I = (name, initScope) => { /******/ if(!initScope) initScope = []; /******/ // handling circular init calls /******/ var initToken = initTokens[name]; /******/ if(!initToken) initToken = initTokens[name] = {}; /******/ if(initScope.indexOf(initToken) >= 0) return; /******/ initScope.push(initToken); /******/ // only runs once /******/ if(initPromises[name]) return initPromises[name]; /******/ // creates a new share scope if needed /******/ if(!__webpack_require__.o(__webpack_require__.S, name)) __webpack_require__.S[name] = {}; /******/ // runs all init snippets from all modules reachable /******/ var scope = __webpack_require__.S[name]; /******/ var warn = (msg) => (typeof console !== "undefined" && console.warn && console.warn(msg)); /******/ var uniqueName = "310_notebook"; /******/ var register = (name, version, factory, eager) => { /******/ var versions = scope[name] = scope[name] || {}; /******/ var activeVersion = versions[version]; /******/ if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager }; /******/ }; /******/ var initExternal = (id) => { /******/ var handleError = (err) => (warn("Initialization of sharing external failed: " + err)); /******/ try { /******/ var module = __webpack_require__(id); /******/ if(!module) return; /******/ var initFn = (module) => (module && module.init && module.init(__webpack_require__.S[name], initScope)) /******/ if(module.then) return promises.push(module.then(initFn, handleError)); /******/ var initResult = initFn(module); /******/ if(initResult && initResult.then) return promises.push(initResult['catch'](handleError)); /******/ } catch(err) { handleError(err); } /******/ } /******/ var promises = []; /******/ switch(name) { /******/ case "default": { /******/ register("310_notebook", "0.1.0", () => (__webpack_require__.e("lib_index_js").then(() => (() => (__webpack_require__(/*! ./lib/index.js */ "./lib/index.js")))))); /******/ } /******/ break; /******/ } /******/ if(!promises.length) return initPromises[name] = 1; /******/ return initPromises[name] = Promise.all(promises).then(() => (initPromises[name] = 1)); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/publicPath */ /******/ (() => { /******/ var scriptUrl; /******/ if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + ""; /******/ var document = __webpack_require__.g.document; /******/ if (!scriptUrl && document) { /******/ if (document.currentScript) /******/ scriptUrl = document.currentScript.src /******/ if (!scriptUrl) { /******/ var scripts = document.getElementsByTagName("script"); /******/ if(scripts.length) scriptUrl = scripts[scripts.length - 1].src /******/ } /******/ } /******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration /******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic. /******/ if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser"); /******/ scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/"); /******/ __webpack_require__.p = scriptUrl; /******/ })(); /******/ /******/ /* webpack/runtime/consumes */ /******/ (() => { /******/ var parseVersion = (str) => { /******/ // see webpack/lib/util/semver.js for original code /******/ var p=p=>{return p.split(".").map((p=>{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r; /******/ } /******/ var versionLt = (a, b) => { /******/ // see webpack/lib/util/semver.js for original code /******/ a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r<b.length&&"u"!=(typeof b[r])[0];var e=a[r],n=(typeof e)[0];if(r>=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e<t;r++} /******/ } /******/ var rangeToString = (range) => { /******/ // see webpack/lib/util/semver.js for original code /******/ var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a<range.length;a++){e--,n+="u"==(typeof(t=range[a]))[0]?"-":(e>0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a<range.length;a++){var t=range[a];g.push(0===t?"not("+o()+")":1===t?"("+o()+" || "+o()+")":2===t?g.pop()+" "+g.pop():rangeToString(t))}return o();function o(){return g.pop().replace(/^\((.+)\)$/,"$1")} /******/ } /******/ var satisfy = (range, version) => { /******/ // see webpack/lib/util/semver.js for original code /******/ if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i<range.length?(typeof range[i])[0]:"";if(n>=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f<range[i])return!1;f!=range[i]&&(a=!1)}else if("s"!=g&&"n"!=g){if(r||i<=e)return!1;a=!1,i--}else{if(i<=e||s<g!=r)return!1;a=!1}else"s"!=g&&"n"!=g&&(a=!1,i--)}}var t=[],o=t.pop.bind(t);for(n=1;n<range.length;n++){var u=range[n];t.push(1==u?o()|o():2==u?o()&o():u?satisfy(u,version):!o())}return!!o(); /******/ } /******/ var ensureExistence = (scopeName, key) => { /******/ var scope = __webpack_require__.S[scopeName]; /******/ if(!scope || !__webpack_require__.o(scope, key)) throw new Error("Shared module " + key + " doesn't exist in shared scope " + scopeName); /******/ return scope; /******/ }; /******/ var findVersion = (scope, key) => { /******/ var versions = scope[key]; /******/ var key = Object.keys(versions).reduce((a, b) => { /******/ return !a || versionLt(a, b) ? b : a; /******/ }, 0); /******/ return key && versions[key] /******/ }; /******/ var findSingletonVersionKey = (scope, key) => { /******/ var versions = scope[key]; /******/ return Object.keys(versions).reduce((a, b) => { /******/ return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a; /******/ }, 0); /******/ }; /******/ var getInvalidSingletonVersionMessage = (scope, key, version, requiredVersion) => { /******/ return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")" /******/ }; /******/ var getSingleton = (scope, scopeName, key, requiredVersion) => { /******/ var version = findSingletonVersionKey(scope, key); /******/ return get(scope[key][version]); /******/ }; /******/ var getSingletonVersion = (scope, scopeName, key, requiredVersion) => { /******/ var version = findSingletonVersionKey(scope, key); /******/ if (!satisfy(requiredVersion, version)) typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion)); /******/ return get(scope[key][version]); /******/ }; /******/ var getStrictSingletonVersion = (scope, scopeName, key, requiredVersion) => { /******/ var version = findSingletonVersionKey(scope, key); /******/ if (!satisfy(requiredVersion, version)) throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion)); /******/ return get(scope[key][version]); /******/ }; /******/ var findValidVersion = (scope, key, requiredVersion) => { /******/ var versions = scope[key]; /******/ var key = Object.keys(versions).reduce((a, b) => { /******/ if (!satisfy(requiredVersion, b)) return a; /******/ return !a || versionLt(a, b) ? b : a; /******/ }, 0); /******/ return key && versions[key] /******/ }; /******/ var getInvalidVersionMessage = (scope, scopeName, key, requiredVersion) => { /******/ var versions = scope[key]; /******/ return "No satisfying version (" + rangeToString(requiredVersion) + ") of shared module " + key + " found in shared scope " + scopeName + ".\n" + /******/ "Available versions: " + Object.keys(versions).map((key) => { /******/ return key + " from " + versions[key].from; /******/ }).join(", "); /******/ }; /******/ var getValidVersion = (scope, scopeName, key, requiredVersion) => { /******/ var entry = findValidVersion(scope, key, requiredVersion); /******/ if(entry) return get(entry); /******/ throw new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion)); /******/ }; /******/ var warnInvalidVersion = (scope, scopeName, key, requiredVersion) => { /******/ typeof console !== "undefined" && console.warn && console.warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion)); /******/ }; /******/ var get = (entry) => { /******/ entry.loaded = 1; /******/ return entry.get() /******/ }; /******/ var init = (fn) => (function(scopeName, a, b, c) { /******/ var promise = __webpack_require__.I(scopeName); /******/ if (promise && promise.then) return promise.then(fn.bind(fn, scopeName, __webpack_require__.S[scopeName], a, b, c)); /******/ return fn(scopeName, __webpack_require__.S[scopeName], a, b, c); /******/ }); /******/ /******/ var load = /*#__PURE__*/ init((scopeName, scope, key) => { /******/ ensureExistence(scopeName, key); /******/ return get(findVersion(scope, key)); /******/ }); /******/ var loadFallback = /*#__PURE__*/ init((scopeName, scope, key, fallback) => { /******/ return scope && __webpack_require__.o(scope, key) ? get(findVersion(scope, key)) : fallback(); /******/ }); /******/ var loadVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key)); /******/ }); /******/ var loadSingleton = /*#__PURE__*/ init((scopeName, scope, key) => { /******/ ensureExistence(scopeName, key); /******/ return getSingleton(scope, scopeName, key); /******/ }); /******/ var loadSingletonVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return getSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var loadStrictVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return getValidVersion(scope, scopeName, key, version); /******/ }); /******/ var loadStrictSingletonVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return getStrictSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var loadVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key)); /******/ }); /******/ var loadSingletonFallback = /*#__PURE__*/ init((scopeName, scope, key, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return getSingleton(scope, scopeName, key); /******/ }); /******/ var loadSingletonVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return getSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var loadStrictVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ var entry = scope && __webpack_require__.o(scope, key) && findValidVersion(scope, key, version); /******/ return entry ? get(entry) : fallback(); /******/ }); /******/ var loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return getStrictSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var installedModules = {}; /******/ var moduleToHandlerMapping = { /******/ "webpack/sharing/consume/default/@jupyterlab/mainmenu": () => (loadSingletonVersionCheck("default", "@jupyterlab/mainmenu", [1,3,4,3])), /******/ "webpack/sharing/consume/default/@lumino/widgets": () => (loadSingletonVersionCheck("default", "@lumino/widgets", [1,1,30,0])) /******/ }; /******/ // no consumes in initial chunks /******/ var chunkMapping = { /******/ "lib_index_js": [ /******/ "webpack/sharing/consume/default/@jupyterlab/mainmenu", /******/ "webpack/sharing/consume/default/@lumino/widgets" /******/ ] /******/ }; /******/ __webpack_require__.f.consumes = (chunkId, promises) => { /******/ if(__webpack_require__.o(chunkMapping, chunkId)) { /******/ chunkMapping[chunkId].forEach((id) => { /******/ if(__webpack_require__.o(installedModules, id)) return promises.push(installedModules[id]); /******/ var onFactory = (factory) => { /******/ installedModules[id] = 0; /******/ __webpack_require__.m[id] = (module) => { /******/ delete __webpack_require__.c[id]; /******/ module.exports = factory(); /******/ } /******/ }; /******/ var onError = (error) => { /******/ delete installedModules[id]; /******/ __webpack_require__.m[id] = (module) => { /******/ delete __webpack_require__.c[id]; /******/ throw error; /******/ } /******/ }; /******/ try { /******/ var promise = moduleToHandlerMapping[id](); /******/ if(promise.then) { /******/ promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError)); /******/ } else onFactory(promise); /******/ } catch(e) { onError(e); } /******/ }); /******/ } /******/ } /******/ })(); /******/ /******/ /* webpack/runtime/jsonp chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "310_notebook": 0 /******/ }; /******/ /******/ __webpack_require__.f.j = (chunkId, promises) => { /******/ // JSONP chunk loading for javascript /******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ if(true) { // all chunks have JS /******/ // setup Promise in chunk cache /******/ var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject])); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var url = __webpack_require__.p + __webpack_require__.u(chunkId); /******/ // create error before stack unwound to get useful stacktrace later /******/ var error = new Error(); /******/ var loadingEnded = (event) => { /******/ if(__webpack_require__.o(installedChunks, chunkId)) { /******/ installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) installedChunks[chunkId] = undefined; /******/ if(installedChunkData) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; /******/ error.name = 'ChunkLoadError'; /******/ error.type = errorType; /******/ error.request = realSrc; /******/ installedChunkData[1](error); /******/ } /******/ } /******/ }; /******/ __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId); /******/ } else installedChunks[chunkId] = 0; /******/ } /******/ } /******/ }; /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no HMR /******/ /******/ // no HMR manifest /******/ /******/ // no on chunks loaded /******/ /******/ // install a JSONP callback for chunk loading /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { /******/ var [chunkIds, moreModules, runtime] = data; /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) { /******/ for(moduleId in moreModules) { /******/ if(__webpack_require__.o(moreModules, moduleId)) { /******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(runtime) var result = runtime(__webpack_require__); /******/ } /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ /******/ } /******/ /******/ var chunkLoadingGlobal = self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []; /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); /******/ })(); /******/ /******/ /* webpack/runtime/nonce */ /******/ (() => { /******/ __webpack_require__.nc = undefined; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // module cache are used so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports /******/ var __webpack_exports__ = __webpack_require__("webpack/container/entry/310_notebook"); /******/ (_JUPYTERLAB = typeof _JUPYTERLAB === "undefined" ? {} : _JUPYTERLAB)["310_notebook"] = __webpack_exports__; /******/ /******/ })() ; //# sourceMappingURL=remoteEntry.cc8f33c82a29a8d64c2d.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook-0.1.0.data/data/share/jupyter/labextensions/310_notebook/static/remoteEntry.cc8f33c82a29a8d64c2d.js
remoteEntry.cc8f33c82a29a8d64c2d.js
"use strict"; (self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []).push([["lib_index_js"],{ /***/ "./lib/index.js": /*!**********************!*\ !*** ./lib/index.js ***! \**********************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/mainmenu */ "webpack/sharing/consume/default/@jupyterlab/mainmenu"); /* harmony import */ var _jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/widgets */ "webpack/sharing/consume/default/@lumino/widgets"); /* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_widgets__WEBPACK_IMPORTED_MODULE_1__); const extension = { id: '310_notebook', autoStart: true, requires: [_jupyterlab_mainmenu__WEBPACK_IMPORTED_MODULE_0__.IMainMenu], optional: [], activate: (app, mainMenu) => { console.log('menu2'); // Add an application command const { commands } = app; const command = '310notebook:logout'; commands.addCommand(command, { label: 'Logout 310.ai notebook panel', execute: () => { location.href = 'https://310.ai/notebook/signout'; } }); // Create a new menu const menu = new _lumino_widgets__WEBPACK_IMPORTED_MODULE_1__.Menu({ commands }); menu.title.label = '310.ai'; // Open Zethus // menu.addItem({ type: 'separator' }); menu.addItem({ command: '310notebook:logout', args: {} }); mainMenu.addMenu(menu, { rank: 100 }); // // Open Logger // menu.addItem({ command: 'jupyterlab-ros/logConsole:open' }); // menu.addItem({ type: 'separator' }); // // Open Settings // menu.addItem({ command: 'jupyterlab-ros/settings:open' }); } }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (extension); /***/ }) }]); //# sourceMappingURL=lib_index_js.13f87d19a930eafd5230.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook/labextension/static/lib_index_js.13f87d19a930eafd5230.js
lib_index_js.13f87d19a930eafd5230.js
"use strict"; (self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []).push([["style_index_js"],{ /***/ "./node_modules/css-loader/dist/cjs.js!./style/base.css": /*!**************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js!./style/base.css ***! \**************************************************************/ /***/ ((module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../node_modules/css-loader/dist/runtime/cssWithMappingToString.js */ "./node_modules/css-loader/dist/runtime/cssWithMappingToString.js"); /* harmony import */ var _node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../node_modules/css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js"); /* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__); // Imports var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_cssWithMappingToString_js__WEBPACK_IMPORTED_MODULE_0___default())); // Module ___CSS_LOADER_EXPORT___.push([module.id, "/*\n See the JupyterLab Developer Guide for useful CSS Patterns:\n\n https://jupyterlab.readthedocs.io/en/stable/developer/css.html\n*/\n\n.my-apodWidget {\n display: flex;\n flex-direction: column;\n align-items: center;\n overflow: auto;\n }", "",{"version":3,"sources":["webpack://./style/base.css"],"names":[],"mappings":"AAAA;;;;CAIC;;AAED;IACI,aAAa;IACb,sBAAsB;IACtB,mBAAmB;IACnB,cAAc;EAChB","sourcesContent":["/*\n See the JupyterLab Developer Guide for useful CSS Patterns:\n\n https://jupyterlab.readthedocs.io/en/stable/developer/css.html\n*/\n\n.my-apodWidget {\n display: flex;\n flex-direction: column;\n align-items: center;\n overflow: auto;\n }"],"sourceRoot":""}]); // Exports /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___); /***/ }), /***/ "./style/base.css": /*!************************!*\ !*** ./style/base.css ***! \************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js"); /* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _node_modules_css_loader_dist_cjs_js_base_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !!../node_modules/css-loader/dist/cjs.js!./base.css */ "./node_modules/css-loader/dist/cjs.js!./style/base.css"); var options = {}; options.insert = "head"; options.singleton = false; var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_base_css__WEBPACK_IMPORTED_MODULE_1__["default"], options); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_base_css__WEBPACK_IMPORTED_MODULE_1__["default"].locals || {}); /***/ }), /***/ "./style/index.js": /*!************************!*\ !*** ./style/index.js ***! \************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony import */ var _base_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.css */ "./style/base.css"); /***/ }) }]); //# sourceMappingURL=style_index_js.547b86f938c46e9f74f6.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook/labextension/static/style_index_js.547b86f938c46e9f74f6.js
style_index_js.547b86f938c46e9f74f6.js
"use strict"; (self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []).push([["vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1"],{ /***/ "./node_modules/css-loader/dist/runtime/api.js": /*!*****************************************************!*\ !*** ./node_modules/css-loader/dist/runtime/api.js ***! \*****************************************************/ /***/ ((module) => { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader // eslint-disable-next-line func-names module.exports = function (cssWithMappingToString) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item); if (item[2]) { return "@media ".concat(item[2], " {").concat(content, "}"); } return content; }).join(""); }; // import a list of modules into the list // eslint-disable-next-line func-names list.i = function (modules, mediaQuery, dedupe) { if (typeof modules === "string") { // eslint-disable-next-line no-param-reassign modules = [[null, modules, ""]]; } var alreadyImportedModules = {}; if (dedupe) { for (var i = 0; i < this.length; i++) { // eslint-disable-next-line prefer-destructuring var id = this[i][0]; if (id != null) { alreadyImportedModules[id] = true; } } } for (var _i = 0; _i < modules.length; _i++) { var item = [].concat(modules[_i]); if (dedupe && alreadyImportedModules[item[0]]) { // eslint-disable-next-line no-continue continue; } if (mediaQuery) { if (!item[2]) { item[2] = mediaQuery; } else { item[2] = "".concat(mediaQuery, " and ").concat(item[2]); } } list.push(item); } }; return list; }; /***/ }), /***/ "./node_modules/css-loader/dist/runtime/cssWithMappingToString.js": /*!************************************************************************!*\ !*** ./node_modules/css-loader/dist/runtime/cssWithMappingToString.js ***! \************************************************************************/ /***/ ((module) => { function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = function cssWithMappingToString(item) { var _item = _slicedToArray(item, 4), content = _item[1], cssMapping = _item[3]; if (!cssMapping) { return content; } if (typeof btoa === "function") { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping)))); var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64); var sourceMapping = "/*# ".concat(data, " */"); var sourceURLs = cssMapping.sources.map(function (source) { return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */"); }); return [content].concat(sourceURLs).concat([sourceMapping]).join("\n"); } return [content].join("\n"); }; /***/ }), /***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js": /*!****************************************************************************!*\ !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***! \****************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var isOldIE = function isOldIE() { var memo; return function memorize() { if (typeof memo === 'undefined') { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 memo = Boolean(window && document && document.all && !window.atob); } return memo; }; }(); var getTarget = function getTarget() { var memo = {}; return function memorize(target) { if (typeof memo[target] === 'undefined') { var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { try { // This will throw an exception if access to iframe is blocked // due to cross-origin restrictions styleTarget = styleTarget.contentDocument.head; } catch (e) { // istanbul ignore next styleTarget = null; } } memo[target] = styleTarget; } return memo[target]; }; }(); var stylesInDom = []; function getIndexByIdentifier(identifier) { var result = -1; for (var i = 0; i < stylesInDom.length; i++) { if (stylesInDom[i].identifier === identifier) { result = i; break; } } return result; } function modulesToDom(list, options) { var idCountMap = {}; var identifiers = []; for (var i = 0; i < list.length; i++) { var item = list[i]; var id = options.base ? item[0] + options.base : item[0]; var count = idCountMap[id] || 0; var identifier = "".concat(id, " ").concat(count); idCountMap[id] = count + 1; var index = getIndexByIdentifier(identifier); var obj = { css: item[1], media: item[2], sourceMap: item[3] }; if (index !== -1) { stylesInDom[index].references++; stylesInDom[index].updater(obj); } else { stylesInDom.push({ identifier: identifier, updater: addStyle(obj, options), references: 1 }); } identifiers.push(identifier); } return identifiers; } function insertStyleElement(options) { var style = document.createElement('style'); var attributes = options.attributes || {}; if (typeof attributes.nonce === 'undefined') { var nonce = true ? __webpack_require__.nc : 0; if (nonce) { attributes.nonce = nonce; } } Object.keys(attributes).forEach(function (key) { style.setAttribute(key, attributes[key]); }); if (typeof options.insert === 'function') { options.insert(style); } else { var target = getTarget(options.insert || 'head'); if (!target) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid."); } target.appendChild(style); } return style; } function removeStyleElement(style) { // istanbul ignore if if (style.parentNode === null) { return false; } style.parentNode.removeChild(style); } /* istanbul ignore next */ var replaceText = function replaceText() { var textStore = []; return function replace(index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; }(); function applyToSingletonTag(style, index, remove, obj) { var css = remove ? '' : obj.media ? "@media ".concat(obj.media, " {").concat(obj.css, "}") : obj.css; // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = style.childNodes; if (childNodes[index]) { style.removeChild(childNodes[index]); } if (childNodes.length) { style.insertBefore(cssNode, childNodes[index]); } else { style.appendChild(cssNode); } } } function applyToTag(style, options, obj) { var css = obj.css; var media = obj.media; var sourceMap = obj.sourceMap; if (media) { style.setAttribute('media', media); } else { style.removeAttribute('media'); } if (sourceMap && typeof btoa !== 'undefined') { css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */"); } // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = css; } else { while (style.firstChild) { style.removeChild(style.firstChild); } style.appendChild(document.createTextNode(css)); } } var singleton = null; var singletonCounter = 0; function addStyle(obj, options) { var style; var update; var remove; if (options.singleton) { var styleIndex = singletonCounter++; style = singleton || (singleton = insertStyleElement(options)); update = applyToSingletonTag.bind(null, style, styleIndex, false); remove = applyToSingletonTag.bind(null, style, styleIndex, true); } else { style = insertStyleElement(options); update = applyToTag.bind(null, style, options); remove = function remove() { removeStyleElement(style); }; } update(obj); return function updateStyle(newObj) { if (newObj) { if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { return; } update(obj = newObj); } else { remove(); } }; } module.exports = function (list, options) { options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (!options.singleton && typeof options.singleton !== 'boolean') { options.singleton = isOldIE(); } list = list || []; var lastIdentifiers = modulesToDom(list, options); return function update(newList) { newList = newList || []; if (Object.prototype.toString.call(newList) !== '[object Array]') { return; } for (var i = 0; i < lastIdentifiers.length; i++) { var identifier = lastIdentifiers[i]; var index = getIndexByIdentifier(identifier); stylesInDom[index].references--; } var newLastIdentifiers = modulesToDom(newList, options); for (var _i = 0; _i < lastIdentifiers.length; _i++) { var _identifier = lastIdentifiers[_i]; var _index = getIndexByIdentifier(_identifier); if (stylesInDom[_index].references === 0) { stylesInDom[_index].updater(); stylesInDom.splice(_index, 1); } } lastIdentifiers = newLastIdentifiers; }; }; /***/ }) }]); //# sourceMappingURL=vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1.a3ba3318a5d7528b56d6.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook/labextension/static/vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1.a3ba3318a5d7528b56d6.js
vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1.a3ba3318a5d7528b56d6.js
var _JUPYTERLAB; /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "webpack/container/entry/310_notebook": /*!***********************!*\ !*** container entry ***! \***********************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { var moduleMap = { "./index": () => { return __webpack_require__.e("lib_index_js").then(() => (() => ((__webpack_require__(/*! ./lib/index.js */ "./lib/index.js"))))); }, "./extension": () => { return __webpack_require__.e("lib_index_js").then(() => (() => ((__webpack_require__(/*! ./lib/index.js */ "./lib/index.js"))))); }, "./style": () => { return Promise.all([__webpack_require__.e("vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1"), __webpack_require__.e("style_index_js")]).then(() => (() => ((__webpack_require__(/*! ./style/index.js */ "./style/index.js"))))); } }; var get = (module, getScope) => { __webpack_require__.R = getScope; getScope = ( __webpack_require__.o(moduleMap, module) ? moduleMap[module]() : Promise.resolve().then(() => { throw new Error('Module "' + module + '" does not exist in container.'); }) ); __webpack_require__.R = undefined; return getScope; }; var init = (shareScope, initScope) => { if (!__webpack_require__.S) return; var name = "default" var oldScope = __webpack_require__.S[name]; if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope"); __webpack_require__.S[name] = shareScope; return __webpack_require__.I(name, initScope); }; // This exports getters to disallow modifications __webpack_require__.d(exports, { get: () => (get), init: () => (init) }); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = __webpack_modules__; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = __webpack_module_cache__; /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/ensure chunk */ /******/ (() => { /******/ __webpack_require__.f = {}; /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = (chunkId) => { /******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => { /******/ __webpack_require__.f[key](chunkId, promises); /******/ return promises; /******/ }, [])); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/get javascript chunk filename */ /******/ (() => { /******/ // This function allow to reference async chunks /******/ __webpack_require__.u = (chunkId) => { /******/ // return url for filenames based on template /******/ return "" + chunkId + "." + {"lib_index_js":"13f87d19a930eafd5230","vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_css-loader_dist_runtime_cssW-72eba1":"a3ba3318a5d7528b56d6","style_index_js":"547b86f938c46e9f74f6"}[chunkId] + ".js"; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/load script */ /******/ (() => { /******/ var inProgress = {}; /******/ var dataWebpackPrefix = "310_notebook:"; /******/ // loadScript function to load a script via script tag /******/ __webpack_require__.l = (url, done, key, chunkId) => { /******/ if(inProgress[url]) { inProgress[url].push(done); return; } /******/ var script, needAttach; /******/ if(key !== undefined) { /******/ var scripts = document.getElementsByTagName("script"); /******/ for(var i = 0; i < scripts.length; i++) { /******/ var s = scripts[i]; /******/ if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; } /******/ } /******/ } /******/ if(!script) { /******/ needAttach = true; /******/ script = document.createElement('script'); /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.setAttribute("data-webpack", dataWebpackPrefix + key); /******/ script.src = url; /******/ } /******/ inProgress[url] = [done]; /******/ var onScriptComplete = (prev, event) => { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var doneFns = inProgress[url]; /******/ delete inProgress[url]; /******/ script.parentNode && script.parentNode.removeChild(script); /******/ doneFns && doneFns.forEach((fn) => (fn(event))); /******/ if(prev) return prev(event); /******/ } /******/ ; /******/ var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000); /******/ script.onerror = onScriptComplete.bind(null, script.onerror); /******/ script.onload = onScriptComplete.bind(null, script.onload); /******/ needAttach && document.head.appendChild(script); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/sharing */ /******/ (() => { /******/ __webpack_require__.S = {}; /******/ var initPromises = {}; /******/ var initTokens = {}; /******/ __webpack_require__.I = (name, initScope) => { /******/ if(!initScope) initScope = []; /******/ // handling circular init calls /******/ var initToken = initTokens[name]; /******/ if(!initToken) initToken = initTokens[name] = {}; /******/ if(initScope.indexOf(initToken) >= 0) return; /******/ initScope.push(initToken); /******/ // only runs once /******/ if(initPromises[name]) return initPromises[name]; /******/ // creates a new share scope if needed /******/ if(!__webpack_require__.o(__webpack_require__.S, name)) __webpack_require__.S[name] = {}; /******/ // runs all init snippets from all modules reachable /******/ var scope = __webpack_require__.S[name]; /******/ var warn = (msg) => (typeof console !== "undefined" && console.warn && console.warn(msg)); /******/ var uniqueName = "310_notebook"; /******/ var register = (name, version, factory, eager) => { /******/ var versions = scope[name] = scope[name] || {}; /******/ var activeVersion = versions[version]; /******/ if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager }; /******/ }; /******/ var initExternal = (id) => { /******/ var handleError = (err) => (warn("Initialization of sharing external failed: " + err)); /******/ try { /******/ var module = __webpack_require__(id); /******/ if(!module) return; /******/ var initFn = (module) => (module && module.init && module.init(__webpack_require__.S[name], initScope)) /******/ if(module.then) return promises.push(module.then(initFn, handleError)); /******/ var initResult = initFn(module); /******/ if(initResult && initResult.then) return promises.push(initResult['catch'](handleError)); /******/ } catch(err) { handleError(err); } /******/ } /******/ var promises = []; /******/ switch(name) { /******/ case "default": { /******/ register("310_notebook", "0.1.0", () => (__webpack_require__.e("lib_index_js").then(() => (() => (__webpack_require__(/*! ./lib/index.js */ "./lib/index.js")))))); /******/ } /******/ break; /******/ } /******/ if(!promises.length) return initPromises[name] = 1; /******/ return initPromises[name] = Promise.all(promises).then(() => (initPromises[name] = 1)); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/publicPath */ /******/ (() => { /******/ var scriptUrl; /******/ if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + ""; /******/ var document = __webpack_require__.g.document; /******/ if (!scriptUrl && document) { /******/ if (document.currentScript) /******/ scriptUrl = document.currentScript.src /******/ if (!scriptUrl) { /******/ var scripts = document.getElementsByTagName("script"); /******/ if(scripts.length) scriptUrl = scripts[scripts.length - 1].src /******/ } /******/ } /******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration /******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic. /******/ if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser"); /******/ scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/"); /******/ __webpack_require__.p = scriptUrl; /******/ })(); /******/ /******/ /* webpack/runtime/consumes */ /******/ (() => { /******/ var parseVersion = (str) => { /******/ // see webpack/lib/util/semver.js for original code /******/ var p=p=>{return p.split(".").map((p=>{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r; /******/ } /******/ var versionLt = (a, b) => { /******/ // see webpack/lib/util/semver.js for original code /******/ a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r<b.length&&"u"!=(typeof b[r])[0];var e=a[r],n=(typeof e)[0];if(r>=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e<t;r++} /******/ } /******/ var rangeToString = (range) => { /******/ // see webpack/lib/util/semver.js for original code /******/ var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a<range.length;a++){e--,n+="u"==(typeof(t=range[a]))[0]?"-":(e>0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a<range.length;a++){var t=range[a];g.push(0===t?"not("+o()+")":1===t?"("+o()+" || "+o()+")":2===t?g.pop()+" "+g.pop():rangeToString(t))}return o();function o(){return g.pop().replace(/^\((.+)\)$/,"$1")} /******/ } /******/ var satisfy = (range, version) => { /******/ // see webpack/lib/util/semver.js for original code /******/ if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i<range.length?(typeof range[i])[0]:"";if(n>=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f<range[i])return!1;f!=range[i]&&(a=!1)}else if("s"!=g&&"n"!=g){if(r||i<=e)return!1;a=!1,i--}else{if(i<=e||s<g!=r)return!1;a=!1}else"s"!=g&&"n"!=g&&(a=!1,i--)}}var t=[],o=t.pop.bind(t);for(n=1;n<range.length;n++){var u=range[n];t.push(1==u?o()|o():2==u?o()&o():u?satisfy(u,version):!o())}return!!o(); /******/ } /******/ var ensureExistence = (scopeName, key) => { /******/ var scope = __webpack_require__.S[scopeName]; /******/ if(!scope || !__webpack_require__.o(scope, key)) throw new Error("Shared module " + key + " doesn't exist in shared scope " + scopeName); /******/ return scope; /******/ }; /******/ var findVersion = (scope, key) => { /******/ var versions = scope[key]; /******/ var key = Object.keys(versions).reduce((a, b) => { /******/ return !a || versionLt(a, b) ? b : a; /******/ }, 0); /******/ return key && versions[key] /******/ }; /******/ var findSingletonVersionKey = (scope, key) => { /******/ var versions = scope[key]; /******/ return Object.keys(versions).reduce((a, b) => { /******/ return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a; /******/ }, 0); /******/ }; /******/ var getInvalidSingletonVersionMessage = (scope, key, version, requiredVersion) => { /******/ return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")" /******/ }; /******/ var getSingleton = (scope, scopeName, key, requiredVersion) => { /******/ var version = findSingletonVersionKey(scope, key); /******/ return get(scope[key][version]); /******/ }; /******/ var getSingletonVersion = (scope, scopeName, key, requiredVersion) => { /******/ var version = findSingletonVersionKey(scope, key); /******/ if (!satisfy(requiredVersion, version)) typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion)); /******/ return get(scope[key][version]); /******/ }; /******/ var getStrictSingletonVersion = (scope, scopeName, key, requiredVersion) => { /******/ var version = findSingletonVersionKey(scope, key); /******/ if (!satisfy(requiredVersion, version)) throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion)); /******/ return get(scope[key][version]); /******/ }; /******/ var findValidVersion = (scope, key, requiredVersion) => { /******/ var versions = scope[key]; /******/ var key = Object.keys(versions).reduce((a, b) => { /******/ if (!satisfy(requiredVersion, b)) return a; /******/ return !a || versionLt(a, b) ? b : a; /******/ }, 0); /******/ return key && versions[key] /******/ }; /******/ var getInvalidVersionMessage = (scope, scopeName, key, requiredVersion) => { /******/ var versions = scope[key]; /******/ return "No satisfying version (" + rangeToString(requiredVersion) + ") of shared module " + key + " found in shared scope " + scopeName + ".\n" + /******/ "Available versions: " + Object.keys(versions).map((key) => { /******/ return key + " from " + versions[key].from; /******/ }).join(", "); /******/ }; /******/ var getValidVersion = (scope, scopeName, key, requiredVersion) => { /******/ var entry = findValidVersion(scope, key, requiredVersion); /******/ if(entry) return get(entry); /******/ throw new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion)); /******/ }; /******/ var warnInvalidVersion = (scope, scopeName, key, requiredVersion) => { /******/ typeof console !== "undefined" && console.warn && console.warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion)); /******/ }; /******/ var get = (entry) => { /******/ entry.loaded = 1; /******/ return entry.get() /******/ }; /******/ var init = (fn) => (function(scopeName, a, b, c) { /******/ var promise = __webpack_require__.I(scopeName); /******/ if (promise && promise.then) return promise.then(fn.bind(fn, scopeName, __webpack_require__.S[scopeName], a, b, c)); /******/ return fn(scopeName, __webpack_require__.S[scopeName], a, b, c); /******/ }); /******/ /******/ var load = /*#__PURE__*/ init((scopeName, scope, key) => { /******/ ensureExistence(scopeName, key); /******/ return get(findVersion(scope, key)); /******/ }); /******/ var loadFallback = /*#__PURE__*/ init((scopeName, scope, key, fallback) => { /******/ return scope && __webpack_require__.o(scope, key) ? get(findVersion(scope, key)) : fallback(); /******/ }); /******/ var loadVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key)); /******/ }); /******/ var loadSingleton = /*#__PURE__*/ init((scopeName, scope, key) => { /******/ ensureExistence(scopeName, key); /******/ return getSingleton(scope, scopeName, key); /******/ }); /******/ var loadSingletonVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return getSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var loadStrictVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return getValidVersion(scope, scopeName, key, version); /******/ }); /******/ var loadStrictSingletonVersionCheck = /*#__PURE__*/ init((scopeName, scope, key, version) => { /******/ ensureExistence(scopeName, key); /******/ return getStrictSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var loadVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key)); /******/ }); /******/ var loadSingletonFallback = /*#__PURE__*/ init((scopeName, scope, key, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return getSingleton(scope, scopeName, key); /******/ }); /******/ var loadSingletonVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return getSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var loadStrictVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ var entry = scope && __webpack_require__.o(scope, key) && findValidVersion(scope, key, version); /******/ return entry ? get(entry) : fallback(); /******/ }); /******/ var loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init((scopeName, scope, key, version, fallback) => { /******/ if(!scope || !__webpack_require__.o(scope, key)) return fallback(); /******/ return getStrictSingletonVersion(scope, scopeName, key, version); /******/ }); /******/ var installedModules = {}; /******/ var moduleToHandlerMapping = { /******/ "webpack/sharing/consume/default/@jupyterlab/mainmenu": () => (loadSingletonVersionCheck("default", "@jupyterlab/mainmenu", [1,3,4,3])), /******/ "webpack/sharing/consume/default/@lumino/widgets": () => (loadSingletonVersionCheck("default", "@lumino/widgets", [1,1,30,0])) /******/ }; /******/ // no consumes in initial chunks /******/ var chunkMapping = { /******/ "lib_index_js": [ /******/ "webpack/sharing/consume/default/@jupyterlab/mainmenu", /******/ "webpack/sharing/consume/default/@lumino/widgets" /******/ ] /******/ }; /******/ __webpack_require__.f.consumes = (chunkId, promises) => { /******/ if(__webpack_require__.o(chunkMapping, chunkId)) { /******/ chunkMapping[chunkId].forEach((id) => { /******/ if(__webpack_require__.o(installedModules, id)) return promises.push(installedModules[id]); /******/ var onFactory = (factory) => { /******/ installedModules[id] = 0; /******/ __webpack_require__.m[id] = (module) => { /******/ delete __webpack_require__.c[id]; /******/ module.exports = factory(); /******/ } /******/ }; /******/ var onError = (error) => { /******/ delete installedModules[id]; /******/ __webpack_require__.m[id] = (module) => { /******/ delete __webpack_require__.c[id]; /******/ throw error; /******/ } /******/ }; /******/ try { /******/ var promise = moduleToHandlerMapping[id](); /******/ if(promise.then) { /******/ promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError)); /******/ } else onFactory(promise); /******/ } catch(e) { onError(e); } /******/ }); /******/ } /******/ } /******/ })(); /******/ /******/ /* webpack/runtime/jsonp chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "310_notebook": 0 /******/ }; /******/ /******/ __webpack_require__.f.j = (chunkId, promises) => { /******/ // JSONP chunk loading for javascript /******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ if(true) { // all chunks have JS /******/ // setup Promise in chunk cache /******/ var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject])); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var url = __webpack_require__.p + __webpack_require__.u(chunkId); /******/ // create error before stack unwound to get useful stacktrace later /******/ var error = new Error(); /******/ var loadingEnded = (event) => { /******/ if(__webpack_require__.o(installedChunks, chunkId)) { /******/ installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) installedChunks[chunkId] = undefined; /******/ if(installedChunkData) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; /******/ error.name = 'ChunkLoadError'; /******/ error.type = errorType; /******/ error.request = realSrc; /******/ installedChunkData[1](error); /******/ } /******/ } /******/ }; /******/ __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId); /******/ } else installedChunks[chunkId] = 0; /******/ } /******/ } /******/ }; /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no HMR /******/ /******/ // no HMR manifest /******/ /******/ // no on chunks loaded /******/ /******/ // install a JSONP callback for chunk loading /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { /******/ var [chunkIds, moreModules, runtime] = data; /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) { /******/ for(moduleId in moreModules) { /******/ if(__webpack_require__.o(moreModules, moduleId)) { /******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(runtime) var result = runtime(__webpack_require__); /******/ } /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ /******/ } /******/ /******/ var chunkLoadingGlobal = self["webpackChunk_310_notebook"] = self["webpackChunk_310_notebook"] || []; /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); /******/ })(); /******/ /******/ /* webpack/runtime/nonce */ /******/ (() => { /******/ __webpack_require__.nc = undefined; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // module cache are used so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports /******/ var __webpack_exports__ = __webpack_require__("webpack/container/entry/310_notebook"); /******/ (_JUPYTERLAB = typeof _JUPYTERLAB === "undefined" ? {} : _JUPYTERLAB)["310_notebook"] = __webpack_exports__; /******/ /******/ })() ; //# sourceMappingURL=remoteEntry.cc8f33c82a29a8d64c2d.js.map
310-notebook
/310_notebook-0.1.0-py3-none-any.whl/310_notebook/labextension/static/remoteEntry.cc8f33c82a29a8d64c2d.js
remoteEntry.cc8f33c82a29a8d64c2d.js
import importlib import pkgutil from . import formatters class AssetFormatter(): _by_name = {} _by_extension = {} def __init__(self, components=None, extensions=None): self.components = components if components else (None, ) self.extensions = extensions def __call__(self, fragment_func): """Decorator method to create a formatter instance from a fragment function.""" self.name = fragment_func.__name__ self.fragments = fragment_func return self def joiner(self, join_func): """Decorator method to attach a join function to a formatter and register it.""" self.join = join_func # Now we have all we need to register. self._by_name[self.name] = self for ext in self.extensions: self._by_extension[ext] = self return self def __repr__(self): return self.name @staticmethod def fragments(symbol, data): raise NotImplementedError @staticmethod def join(ext, filename, data): raise NotImplementedError @classmethod def names(cls): return cls._by_name.keys() @classmethod def parse(cls, value): """Fetch a formatter by name.""" if isinstance(value, cls): return value else: try: return cls._by_name[value] except KeyError: raise ValueError(f'Invalid format {value}, choices {cls.names()}.') @classmethod def guess(cls, path): """Fetch a formatter which can generate the requested filename.""" try: return cls._by_extension[path.suffix] except KeyError: raise TypeError(f"Unable to identify format for {path}.") # Load all the implementations dynamically. for loader, module_name, is_pkg in pkgutil.walk_packages(formatters.__path__, formatters.__name__ + '.'): # We don't need to import anything from the modules. We just need to load them. # This will cause the decorators to run, which registers the formatters. importlib.import_module(module_name, formatters.__name__)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/asset/formatter.py
formatter.py
import logging from .formatter import AssetFormatter class AssetWriter: def __init__(self): self._assets = {} def add_asset(self, symbol, data): if symbol in self._assets: raise NameError(f'Symbol {symbol} has already been added.') self._assets[symbol] = data def _sorted(self, sort): if sort is None: return self._assets.items() elif sort == 'symbol': return sorted(self._assets.items()) elif sort == 'size': return sorted(self._assets.items(), key=lambda i: len(i[1])) else: raise ValueError(f"Don't know how to sort by {sort}.") def _get_format(self, value, path, default='c_header'): if value is None: if path is None: logging.warning(f"No output filename, writing to stdout assuming {default}") return AssetFormatter.parse(default) else: fmt = AssetFormatter.guess(path) logging.info(f"Guessed output format {fmt} for {path}") return fmt else: return AssetFormatter.parse(value) def write(self, fmt=None, path=None, force=False, report=True, sort=None): fmt = self._get_format(fmt, path) assets = self._sorted(sort) fragments = [fmt.fragments(symbol, data) for symbol, data in assets] components = {key: [f[key] for f in fragments] for key in fragments[0]} outpaths = [] for component, data in fmt.join(path, components).items(): if path is None: print(data) else: outpath = path if component is None else path.with_suffix(f'.{component}') if outpath.exists() and not force: raise FileExistsError(f'Refusing to overwrite {path} (use force)') else: logging.info(f'Writing {outpath}') if type(data) is str: outpath.write_text(data, encoding='utf8') else: outpath.write_bytes(data) outpaths.append(outpath) if path and report: lines = [ f'Formatter: {fmt.name}', 'Files:', *(f' {path}' for path in outpaths), 'Assets:', *(' {}: {}'.format(symbol, len(data)) for symbol, data in assets), 'Total size: {}'.format(sum(len(data) for symbol, data in assets)), '', ] path.with_name(path.stem + '_report.txt').write_text('\n'.join(lines))
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/asset/writer.py
writer.py
import functools import importlib import pathlib import pkgutil import re import click from . import builders from .formatter import AssetFormatter from .writer import AssetWriter def make_symbol_name(base=None, working_path=None, input_file=None, input_type=None, input_subtype=None, prefix=None): if base is None: if input_file is None: raise NameError("No base name or input file provided.") if working_path is None: name = '_'.join(input_file.parts) else: name = '_'.join(input_file.relative_to(working_path).parts) else: name = base.format( filename=input_file.with_suffix('').name, filepath=input_file.with_suffix(''), fullname=input_file.name, fullpath=input_file, type=input_type, subtype=input_subtype ) name = name.replace('.', '_') name = re.sub('[^0-9A-Za-z_]', '_', name) name = name.lower() if type(prefix) is str: name = prefix + name return name class AssetBuilder: _by_name = {} _by_extension = {} def __init__(self, typemap): self.typemap = typemap def __call__(self, build_func): self.name = build_func.__name__ self.build = build_func self._by_name[self.name] = self for subtype, extensions in self.typemap.items(): for ext, auto in extensions.items(): if auto: if ext in self._by_extension: raise KeyError(f'An automatic handler for {ext} has already been registered ({self._by_extension[ext]}).') self._by_extension[ext] = f'{self.name}/{subtype}' return self def __repr__(self): return self.name @staticmethod def build(self, data, subtype, **kwargs): raise NotImplementedError def from_file(self, path, subtype, **kwargs): if subtype is None: subtype = self.guess_subtype(path) elif subtype not in self.typemap.keys(): raise ValueError(f'Invalid subtype {subtype}, choices {self.typemap.keys()}') return self.build(path.read_bytes(), subtype, **kwargs) def guess_subtype(self, path): for input_type, extensions in self.typemap.items(): if path.suffix in extensions: return input_type raise TypeError(f"Unable to identify type of input file {path.name}.") @classmethod def guess_builder(cls, path): try: return cls._by_extension[path.suffix] except KeyError: raise TypeError('Could not find a builder for {path}.') class AssetTool: _commands = {} def __init__(self, builder, help): self.builder = builder self.name = builder.name self.help = help def __call__(self, f): @click.command(self.name, help=self.help) @click.option('--input_file', type=pathlib.Path, required=True, help='Input file') @click.option('--input_type', type=click.Choice(self.builder.typemap.keys(), case_sensitive=False), default=None, help='Input file type') @click.option('--output_file', type=pathlib.Path, default=None, help='Output file') @click.option('--output_format', type=click.Choice(AssetFormatter.names(), case_sensitive=False), default=None, help='Output file format') @click.option('--symbol_name', type=str, default=None, help='Output symbol name') @click.option('--force/--keep', default=False, help='Force file overwriting') @functools.wraps(f) def cmd(input_file, input_type, output_file, output_format, symbol_name, force, **kwargs): aw = AssetWriter() aw.add_asset(symbol_name, f(input_file, input_type, **kwargs)) aw.write(output_format, output_file, force, report=False) self._commands[self.name] = cmd # Load all the implementations dynamically. for loader, module_name, is_pkg in pkgutil.walk_packages(builders.__path__, builders.__name__ + '.'): # We don't need to import anything from the modules. We just need to load them. # This will cause the decorators to run, which registers the builders. importlib.import_module(module_name, builders.__name__)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/asset/builder.py
builder.py
import logging import struct import click from ..builder import AssetBuilder, AssetTool from .raw import csv_to_list map_typemap = { 'tiled': { '.tmx': True, '.raw': False, }, } def tiled_to_binary(data, empty_tile, output_struct): from xml.etree import ElementTree as ET root = ET.fromstring(data) layers = root.findall('layer') layer_data = [] transform_data = [] # Sort layers by ID (since .tmx files can have them in arbitrary orders) layers.sort(key=lambda l: int(l.get('id'))) use_16bits = False for layer_csv in layers: raw_layer = csv_to_list(layer_csv.find('data').text, 10) # Shift 1-indexed tiles to 0-indexed, and remap empty tile (0) to specified index # The highest three bits store the transform layer = [empty_tile if i == 0 else (i & 0x1FFFFFFF) - 1 for i in raw_layer] # This matches the flags used by the TileMap class, but doesn't match SpriteTransform... layer_transforms = [i >> 29 for i in raw_layer] if max(layer) > 255 and not use_16bits: # Let's assume it's got 2-byte tile indices logging.info('Found a tile index > 255, using 16bit tile sizes!') use_16bits = True # Always build up a 1d array of layer data layer_data += layer transform_data += layer_transforms if use_16bits: layer_data = struct.pack(f'<{len(layer_data)}H', *layer_data) else: layer_data = struct.pack(f'<{len(layer_data)}B', *layer_data) if output_struct: # Fancy struct layer_count = len(layers) width = int(root.get("width")) height = int(root.get("height")) flags = 0 have_transforms = any(v != 0 for v in transform_data) if use_16bits: flags |= (1 << 0) if have_transforms: flags |= (1 << 1) else: transform_data = [] return struct.pack( '<4sHHHHHH', bytes('MTMX', encoding='utf-8'), 16, flags, empty_tile, width, height, layer_count ) + layer_data + bytes(transform_data) else: # Just return the raw layer data return layer_data + bytes(transform_data) @AssetBuilder(typemap=map_typemap) def map(data, subtype, empty_tile=0, output_struct=False): if subtype == 'tiled': return tiled_to_binary(data, empty_tile, output_struct) @AssetTool(map, 'Convert popular tilemap formats for 32Blit') @click.option('--empty-tile', type=int, default=0, help='Remap .tmx empty tiles') @click.option('--output-struct', type=bool, default=False, help='Output .tmx as struct with level width/height, etc') def map_cli(input_file, input_type, **kwargs): return map.from_file(input_file, input_type, **kwargs)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/asset/builders/map.py
map.py
import io import logging import pathlib import click from PIL import Image from ...core.palette import Colour, Palette from ...core.struct import struct_blit_image from ..builder import AssetBuilder, AssetTool image_typemap = { 'image': { '.png': True, '.gif': True, } } @AssetBuilder(typemap=image_typemap) def image(data, subtype, palette=None, transparent=None, strict=False, packed=True): if palette is None: palette = Palette() else: palette = Palette(palette) if transparent is not None: transparent = Colour(transparent) p = palette.set_transparent_colour(*transparent) if p is not None: logging.info(f'Found transparent {transparent} in palette') else: logging.warning(f'Could not find transparent {transparent} in palette') # Since we already have bytes, we need to pass PIL an io.BytesIO object image = Image.open(io.BytesIO(data)).convert('RGBA') image = palette.quantize_image(image, transparent=transparent, strict=strict) return struct_blit_image.build({ 'type': None if packed else 'RW', # None means let the compressor decide 'data': { 'width': image.size[0], 'height': image.size[1], 'palette': palette.tostruct(), 'pixels': image.tobytes(), }, }) @AssetTool(image, 'Convert images/sprites for 32Blit') @click.option('--palette', type=pathlib.Path, help='Image or palette file of colours to use') @click.option('--transparent', type=Colour, default=None, help='Transparent colour') @click.option('--packed', type=click.Choice(['yes', 'no'], case_sensitive=False), default='yes', help='Pack into bits depending on palette colour count') @click.option('--strict/--no-strict', default=False, help='Reject colours not in the palette') def image_cli(input_file, input_type, packed, **kwargs): packed = (packed.lower() == 'yes') return image.from_file(input_file, input_type, packed=packed, **kwargs)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/asset/builders/image.py
image.py
import io import struct import click from PIL import Image from ..builder import AssetBuilder, AssetTool font_typemap = { 'image': { '.png': False, '.gif': False, }, 'font': { # possibly other freetype supported formats... '.ttf': True, } } def process_image_font(data, num_chars, height, horizontal_spacing, space_width): # Since we already have bytes, we need to pass PIL an io.BytesIO object image = Image.open(io.BytesIO(data)).convert('1') w, h = image.size rows = 1 cols = num_chars # if height is specified calculate rows/cols, otherwise assume a single row with the image height as the character height if height != 0 and height != h: rows = h // height cols = num_chars // rows char_width = w // cols char_height = h // rows font_data = [] font_w = [] # per character width for variable-width mode for c in range(0, num_chars): char_w = 0 char_col = c % cols char_row = c // cols for x in range(0, char_width): byte = 0 for y in range(0, char_height): bit = y % 8 # next byte if bit == 0 and y > 0: font_data.append(byte) byte = 0 if image.getpixel((x + char_col * char_width, y + char_row * char_height)) != 0: byte |= 1 << bit if x + 1 > char_w: char_w = x + 1 font_data.append(byte) if c == 0: # space font_w.append(space_width) else: font_w.append(char_w + horizontal_spacing) return font_data, font_w, char_width, char_height def process_ft_font(data, num_chars, base_char, height): import freetype if height == 0: raise TypeError("Height must be specified for font files") face = freetype.Face(io.BytesIO(data)) # request height face.set_pixel_sizes(0, height) char_width = 0 char_height = 0 min_y = height font_w = [] # measure the actual size of the characters (may not match requested) for c in range(0, num_chars): face.load_char(c + base_char, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO) font_w.append(face.glyph.advance.x >> 6) if face.glyph.bitmap.width + face.glyph.bitmap_left > char_width: char_width = face.glyph.bitmap.width + face.glyph.bitmap_left if (height - face.glyph.bitmap_top) + face.glyph.bitmap.rows > char_height: char_height = height - face.glyph.bitmap_top + face.glyph.bitmap.rows if height - face.glyph.bitmap_top < min_y: min_y = height - face.glyph.bitmap_top char_height -= min_y # trim empty space at the top font_data = [] # now do the conversion for c in range(0, num_chars): face.load_char(c + base_char, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO) x_off = face.glyph.bitmap_left y_off = height - face.glyph.bitmap_top - min_y for x in range(0, char_width): byte = 0 for y in range(0, char_height): bit = y % 8 # next byte if bit == 0 and y > 0: font_data.append(byte) byte = 0 if x < x_off or x - x_off >= face.glyph.bitmap.width or y < y_off or y - y_off >= face.glyph.bitmap.rows: continue # freetype monochrome bitmaps are the other way around if face.glyph.bitmap.buffer[(x - x_off) // 8 + (y - y_off) * face.glyph.bitmap.pitch] & ( 0x80 >> ((x - x_off) & 7)): byte |= 1 << bit font_data.append(byte) return font_data, font_w, char_width, char_height @AssetBuilder(typemap=font_typemap) def font(data, subtype, num_chars=96, base_char=ord(' '), height=0, horizontal_spacing=1, vertical_spacing=1, space_width=3): if subtype == 'image': font_data, font_w_data, char_width, char_height = process_image_font( data, num_chars, height, horizontal_spacing, space_width ) elif subtype == 'font': font_data, font_w_data, char_width, char_height = process_ft_font( data, num_chars, base_char, height ) else: raise TypeError(f'Unknown subtype {subtype} for font.') head_data = struct.pack('<BBBB', num_chars, char_width, char_height, vertical_spacing) data = bytes('FONT', encoding='utf-8') data += head_data data += bytes(font_w_data) data += bytes(font_data) return data @AssetTool(font, 'Convert fonts for 32Blit') @click.option('--height', type=int, default=0, help='Font height (calculated from image if not specified)') @click.option('--horizontal-spacing', type=int, default=1, help='Additional space between characters for variable-width mode') @click.option('--vertical-spacing', type=int, default=1, help='Space between lines') @click.option('--space-width', type=int, default=3, help='Width of the space character') def font_cli(input_file, input_type, **kwargs): return font.from_file(input_file, input_type, **kwargs)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/asset/builders/font.py
font.py
import logging import pathlib import textwrap import click from ..asset.formatter import AssetFormatter from ..core.yamlloader import YamlLoader class CMake(YamlLoader): def run(self, config, cmake, output): self.setup_for_config(config, output) if 'title' in self.config and 'description' in self.config: logging.info('Detected metadata config') self.run_for_metadata_config(cmake) else: logging.info('Detected asset config') self.run_for_asset_config(cmake) def run_for_metadata_config(self, cmake): all_inputs = [] if 'splash' in self.config: file = pathlib.Path(self.config['splash']['file']) if file.is_absolute(): all_inputs += [file] else: all_inputs += list(self.working_path.glob(str(file))) if 'icon' in self.config: file = pathlib.Path(self.config['icon']['file']) if file.is_absolute(): all_inputs += [file] else: all_inputs += list(self.working_path.glob(str(file))) all_inputs = '\n '.join(f'"{x}"'.replace('\\', '/') for x in all_inputs) title = self.config['title'].replace('"', r'\"') author = self.config['author'].replace('"', r'\"') description = self.config['description'].replace('"', r'\"') url = self.config.get('url', '') category = self.config.get('category', 'none') result = textwrap.dedent( '''\ # Auto Generated File - DO NOT EDIT! set(METADATA_DEPENDS {inputs} ) set(METADATA_TITLE "{title}") set(METADATA_AUTHOR "{author}") set(METADATA_DESCRIPTION "{description}") set(METADATA_VERSION "{config[version]}") set(METADATA_URL "{url}") set(METADATA_CATEGORY "{category}") ''' ).format( inputs=all_inputs, config=self.config, title=title, author=author, description=description, url=url, category=category, ) cmake.write_text(result) def run_for_asset_config(self, cmake): all_inputs = [] all_outputs = [] # Top level of our config is filegroups and general settings for target, options in self.config.items(): target = pathlib.Path(target) try: output_formatter = AssetFormatter.guess(target) except TypeError: logging.warning(f'Unable to guess type of {target}, assuming raw/binary') output_formatter = AssetFormatter.parse('raw_binary') for suffix in output_formatter.components: if suffix is None: all_outputs.append(self.destination_path / target.name) else: all_outputs.append(self.destination_path / target.with_suffix(f'.{suffix}').name) # Strip high-level options from the dict # Leaving just file source globs for key in ('prefix', 'type'): options.pop(key, None) for file_glob, file_options in options.items(): # Rewrite a single string option to `name: option` # This handles: `inputfile.bin: filename` entries if type(file_options) is str: file_options = {'name': file_options} # Handle both an array of options dicts or a single dict if type(file_options) is not list: file_options = [file_options] input_files = [] # Parse the options for any references to input files for file_opts in file_options: for key, value in file_opts.items(): if key in ('palette') and type(value) is str: input_files += list(self.working_path.glob(value)) # Treat the input string as a glob, and get an input filelist if type(file_glob) is str: input_files += list(self.working_path.glob(file_glob)) else: input_files += [file_glob] if len(input_files) == 0: logging.warning(f'Input file(s) not found {self.working_path / file_glob}') continue all_inputs += input_files all_inputs = '\n '.join(f'"{x}"'.replace('\\', '/') for x in all_inputs) all_outputs = '\n '.join(f'"{x}"'.replace('\\', '/') for x in all_outputs) result = textwrap.dedent( '''\ # Auto Generated File - DO NOT EDIT! set(ASSET_DEPENDS {inputs} ) set(ASSET_OUTPUTS {outputs} ) ''' ).format( inputs=all_inputs, outputs=all_outputs, ) cmake.write_text(result) @click.command('cmake', help='Generate CMake configuration for the asset packer') @click.option('--config', type=pathlib.Path, help='Asset config file') @click.option('--cmake', type=pathlib.Path, help='Output CMake file', required=True) @click.option('--output', type=pathlib.Path, help='Name for output file(s) or root path when using --config') def cmake_cli(config, cmake, output): CMake().run(config, cmake, output)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/tool/cmake.py
cmake.py
import functools import logging import pathlib import textwrap import click from ..core.blitserial import BlitSerial block_size = 64 * 1024 @click.group('flash', help='Flash a binary or save games/files to 32Blit') @click.option('ports', '--port', multiple=True, help='Serial port') @click.pass_context def flash_cli(ctx, ports): ctx.obj = ports def serial_command(fn): """Set up and tear down serial connections.""" @click.option('ports', '--port', multiple=True, help='Serial port') @click.pass_context @functools.wraps(fn) def _decorated(ctx, ports, **kwargs): if ctx.obj: ports = ctx.obj + ports if not ports or ports[0].lower() == 'auto': ports = BlitSerial.find_comport() for port in ports: with BlitSerial(port) as sp: fn(sp, **kwargs) return _decorated @flash_cli.command(help="Deprecated: use '32blit install' instead. Copy a file to SD card") @serial_command @click.option('--file', type=pathlib.Path, required=True, help='File to save') @click.option('--directory', type=str, default='/', help='Target directory') def save(blitserial, file, directory): blitserial.send_file(file, 'sd', directory=directory) @flash_cli.command(help="Deprecated: use '32blit install' instead. Install a .blit to flash") @serial_command @click.option('--file', type=pathlib.Path, required=True, help='File to save') def flash(blitserial, file): blitserial.send_file(file, 'flash') # TODO: options should be mutually exclusive @flash_cli.command(help="Delete a .blit from flash by block index or offset") @serial_command @click.option('--offset', type=int, help='Flash offset of game to delete') @click.option('--block', type=int, help='Flash block of game to delete') def delete(blitserial, offset, block): if offset is None: offset = block * block_size blitserial.erase(offset) @flash_cli.command(help="List .blits installed in flash memory") @serial_command def list(blitserial): for meta, offset, size in blitserial.list(): offset_blocks = offset // block_size size_blocks = (size - 1) // block_size + 1 print(f"Game at block {offset_blocks}") print(f"Size: {size_blocks:3d} blocks ({size / 1024:.1f}kB)") if meta is not None: print(textwrap.dedent(f"""\ Title: {meta.data.title} Description: {meta.data.description} Version: {meta.data.version} Author: {meta.data.author} """)) @flash_cli.command(help="Not implemented") @serial_command def debug(blitserial): pass @flash_cli.command(help="Reset 32Blit") @serial_command def reset(blitserial): logging.info('Resetting your 32Blit...') blitserial.reset() @flash_cli.command(help="Get current runtime status of 32Blit") @serial_command def info(blitserial): logging.info('Getting 32Blit run status...') print(f'Running: {blitserial.status}') @click.command('install', help="Install files to 32Blit") @serial_command @click.argument("source", type=pathlib.Path, required=True) @click.argument("destination", type=pathlib.PurePosixPath, default=None, required=False) @click.option("--launch/--no-launch", default=False) def install_cli(blitserial, source, destination, launch): if destination is None and source.suffix.lower() == '.blit': drive = 'flash' else: drive = 'sd' if destination is None: destination = pathlib.PurePosixPath('/') elif not destination.is_absolute(): destination = pathlib.PurePosixPath('/') / destination blitserial.send_file(source, drive, destination, launch) @click.command('launch', help="Launch a game/file on 32Blit") @serial_command @click.argument("filename", type=str, required=True) def launch_cli(blitserial, filename): blitserial.launch(filename)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/tool/flasher.py
flasher.py
import io import logging import pathlib import textwrap from datetime import datetime import click from construct.core import StreamError from PIL import Image from ..asset.builder import AssetBuilder from ..asset.formatters.c import c_initializer from ..core.struct import (blit_game, blit_game_with_meta, blit_game_with_meta_and_relo, blit_icns, struct_blit_image, struct_blit_image_bi, struct_blit_meta_standalone, struct_blit_pixel) from ..core.yamlloader import YamlLoader class Metadata(YamlLoader): def prepare_image_asset(self, name, config, working_path): image_file = pathlib.Path(config.get('file', '')) if not image_file.is_file(): image_file = working_path / image_file if not image_file.is_file(): raise ValueError(f'{name} "{image_file}" does not exist!') return AssetBuilder._by_name['image'].from_file(image_file, None) def blit_image_to_pil(self, image): data = b''.join(struct_blit_pixel.build(image.data.palette[i]) for i in image.data.pixels) return Image.frombytes("RGBA", (image.data.width, image.data.height), data) def build_icns(self, config, working_path): image_file = pathlib.Path(config.get('file', '')) if not image_file.is_file(): image_file = working_path / image_file if not image_file.is_file(): raise ValueError(f'splash "{image_file}" does not exist!') blit_icon = Image.frombytes("P", (22, 22), b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x02\x02\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x02\x02\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x02\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x02\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x02\x02\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x02\x02\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x02\x02\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x02\x02\x00\x00\x01\x01\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x01\x01\x01\x01\x02\x02\x00\x00\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x02\x02\x00\x00\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x02\x02\x00\x00\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x02\x02\x00\x00\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x02\x02\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x01\x01\x02\x02\x01\x01\x01\x01\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x00\x00\x01\x01\x01\x01') blit_icon.putpalette([0, 0, 0, 255, 255, 255, 0, 255, 0]) blit_icon = blit_icon.convert("RGBA") source = Image.open(image_file).convert("RGBA") image = Image.new("RGB", (128, 128), (0, 0, 0)) image.paste(source, (0, 0)) image.paste(blit_icon, (101, 101), blit_icon) image_bytes = io.BytesIO() image.convert("RGB").save(image_bytes, format="PNG") image_bytes.seek(0) del image return blit_icns.build({'data': image_bytes.read()}) def dump_game_metadata(self, file, game, dump_images): print(f'\nParsed: {file.name} ({game.bin.length:,} bytes)') if game.relo is not None: print(f'Relocations: Yes ({len(game.relo.relocs)})') else: print('Relocations: No') if game.meta is not None: print('Metadata: Yes') for field in ['title', 'description', 'version', 'author', 'category', 'url']: print(f'{field.title()+":":13s}{getattr(game.meta.data, field)}') if len(game.meta.data.filetypes) > 0: print(' Filetypes: ') for filetype in game.meta.data.filetypes: print(' ', filetype) if game.meta.data.icon is not None: game_icon = game.meta.data.icon print(f' Icon: {game_icon.data.width}x{game_icon.data.height} ({len(game_icon.data.palette)} colours) ({game_icon.type})') if dump_images: image_icon = self.blit_image_to_pil(game_icon) image_icon_filename = file.with_suffix(".icon.png") image_icon.save(image_icon_filename) print(f' Dumped to: {image_icon_filename}') if game.meta.data.splash is not None: game_splash = game.meta.data.splash print(f' Splash: {game_splash.data.width}x{game_splash.data.height} ({len(game_splash.data.palette)} colours) ({game_splash.type})') if dump_images: image_splash = self.blit_image_to_pil(game_splash) image_splash_filename = file.with_suffix('.splash.png') image_splash.save(image_splash_filename) print(f' Dumped to: {image_splash_filename}') else: print('Metadata: No') print('') def write_pico_bi_source(self, pico_bi_file, metadata): title = metadata['title'].replace('"', r'\"') author = metadata['author'].replace('"', r'\"') description = metadata['description'].replace('"', r'\"') icon = struct_blit_image_bi.build({'data': metadata['icon']}) splash = struct_blit_image_bi.build({'data': metadata['splash']}) open(pico_bi_file, "w").write(textwrap.dedent( ''' #include "pico/binary_info.h" #include "binary_info.hpp" bi_decl(bi_program_name("{title}")) bi_decl(bi_program_description("{description}")) bi_decl(bi_program_version_string("{version}")) bi_decl(bi_program_url("{url}")) bi_decl(bi_string(BINARY_INFO_TAG_32BLIT, BINARY_INFO_ID_32BLIT_AUTHOR, "{author}")) bi_decl(bi_string(BINARY_INFO_TAG_32BLIT, BINARY_INFO_ID_32BLIT_CATEGORY, "{category}")) static const uint8_t metadata_icon[]{icon}; static const uint8_t metadata_splash[]{splash}; __bi_decl(bi_metadata_icon, &((binary_info_raw_data_t *)metadata_icon)->core, ".binary_info.keep.", __used); __bi_decl(bi_metadata_splash, &((binary_info_raw_data_t *)metadata_splash)->core, ".binary_info.keep.", __used); ''').format(title=title, description=description, version=metadata['version'], url=metadata['url'], author=author, category=metadata['category'], icon=c_initializer(icon), splash=c_initializer(splash))) logging.info(f'Wrote pico-sdk binary info to {pico_bi_file}') def run(self, config, icns, pico_bi, file, metadata_file, force, dump_images): if file is None and config is None: raise click.UsageError('the following arguments are required: --config and/or --file') if file and not file.is_file(): raise ValueError(f'Unable to find bin file at {file}') icon = None splash = None game = None if file: bin = open(file, 'rb').read() try: game = blit_game.parse(bin) except StreamError: raise ValueError(f'Invalid 32blit binary file {file}') # No config supplied, so dump the game info if config is None: self.dump_game_metadata(file, game, dump_images) return self.setup_for_config(config, None) if 'icon' in self.config: icon = struct_blit_image.parse(self.prepare_image_asset('icon', self.config['icon'], self.working_path)) if icon.data.width != 8 or icon.data.height != 8: icon = None if icon is None: raise ValueError('An 8x8 pixel icon is required!"') if 'splash' in self.config: splash = struct_blit_image.parse(self.prepare_image_asset('splash', self.config['splash'], self.working_path)) if splash.data.width != 128 or splash.data.height != 96: splash = None if icns is not None: if not icns.is_file() or force: open(icns, 'wb').write(self.build_icns(self.config['splash'], self.working_path)) logging.info(f'Saved macOS icon to {icns}') if splash is None: raise ValueError('A 128x96 pixel splash is required!"') title = self.config.get('title', None) description = self.config.get('description', '') version = self.config.get('version', None) author = self.config.get('author', None) url = self.config.get('url', '') category = self.config.get('category', 'none') filetypes = self.config.get('filetypes', []) if type(filetypes) is str: filetypes = filetypes.split(' ') if title is None: raise ValueError('Title is required!') if version is None: raise ValueError('Version is required!') if author is None: raise ValueError('Author is required!') if len(title) > 24: raise ValueError('Title should be a maximum of 24 characters!"') if len(description) > 128: raise ValueError('Description should be a maximum of 128 characters!') if len(version) > 16: raise ValueError('Version should be a maximum of 16 characters! eg: "v1.0.2"') if len(author) > 16: raise ValueError('Author should be a maximum of 16 characters!') if len(category) > 16: raise ValueError('Category should be a maximum of 16 characters!') if len(url) > 128: raise ValueError('URL should be a maximum of 128 characters!') if len(filetypes) > 0: for filetype in filetypes: if len(filetype) > 4: raise ValueError('Filetype should be a maximum of 4 characters! (Hint, don\'t include the .)') metadata = { 'checksum': 0xFFFFFFFF, 'date': datetime.now().strftime("%Y%m%dT%H%M%S"), 'title': title, 'description': description, 'version': version, 'author': author, 'category': category, 'filetypes': filetypes, 'url': url, 'icon': icon, 'splash': splash } if pico_bi is not None: if not pico_bi.is_file() or force: self.write_pico_bi_source(pico_bi, metadata) # Standalone metadata if metadata_file: if metadata_file.exists() and not force: logging.critical(f'Refusing to overwrite metadata in {metadata_file}') return open(metadata_file, 'wb').write(struct_blit_meta_standalone.build({'data': metadata})) # Add to the game file if not game: return if game.meta is not None: if not force: logging.critical(f'Refusing to overwrite metadata in {file}') return 1 game.meta = { 'data': metadata } # Force through a non-optional builder if relo symbols exist # since we might have modified them and want to hit parser errors # if something has messed up if game.relo is not None: bin = blit_game_with_meta_and_relo.build(game) else: bin = blit_game_with_meta.build(game) logging.info(f'Adding metadata to {file}') open(file, 'wb').write(bin) return 0 @click.command('metadata', help='Tag a 32Blit .blit file with metadata') @click.option('--config', type=pathlib.Path, help='Metadata config file') @click.option('--icns', type=pathlib.Path, help='macOS icon output file') @click.option('--pico-bi', type=pathlib.Path, help='pico-sdk binary info source file output') @click.option('--file', type=pathlib.Path, help='Input file') @click.option('--metadata-file', type=pathlib.Path, help='Output standalone metadata file') @click.option('--force', is_flag=True, help='Force file overwrite') @click.option('--dump-images', is_flag=True, help='Dump images from metadata') def metadata_cli(config, icns, pico_bi, file, metadata_file, force, dump_images): Metadata().run(config, icns, pico_bi, file, metadata_file, force, dump_images)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/tool/metadata.py
metadata.py
import pathlib import struct import click from elftools.elf.elffile import ELFFile from elftools.elf.enums import ENUM_RELOC_TYPE_ARM @click.command('relocs', help='Prepend relocations to a game binary') @click.option('--bin-file', type=pathlib.Path, help='Input .bin', required=True) @click.option('--elf-file', type=pathlib.Path, help='Input .elf', required=True) @click.option('--output', type=pathlib.Path, help='Output file', required=True) def relocs_cli(bin_file, elf_file, output): with open(elf_file, 'rb') as f: elffile = ELFFile(f) # get addresses of GOT values that need patched got_offsets = get_flash_addr_offsets(elffile.get_section_by_name('.got')) # and the init/fini arrays init_offsets = get_flash_addr_offsets(elffile.get_section_by_name('.init_array')) fini_offsets = get_flash_addr_offsets(elffile.get_section_by_name('.fini_array')) reloc_offsets = [] # find sidata/sdata sidata = 0 sdata = 0 itcm_data = 0 itcm_text_start = 0 relocs = elffile.get_section_by_name('.rel.text') symtable = elffile.get_section(relocs['sh_link']) for reloc in relocs.iter_relocations(): symbol = symtable.get_symbol(reloc['r_info_sym']) if symbol.name == '_sidata': sidata = symbol['st_value'] elif symbol.name == '_sdata': sdata = symbol['st_value'] elif symbol.name == 'itcm_data': itcm_data = symbol['st_value'] elif symbol.name == 'itcm_text_start': itcm_text_start = symbol['st_value'] if sidata and sdata and itcm_data and itcm_text_start: break assert(sidata != 0 and sdata != 0) # get all .data relocations relocs = elffile.get_section_by_name('.rel.data') symtable = elffile.get_section(relocs['sh_link']) for reloc in relocs.iter_relocations(): symbol = symtable.get_symbol(reloc['r_info_sym']) if reloc['r_info_type'] != ENUM_RELOC_TYPE_ARM['R_ARM_ABS32']: continue # doesn't point to flash if symbol['st_value'] < 0x90000000: continue # map RAM address back to flash flash_offset = (reloc['r_offset'] - sdata) + sidata assert((flash_offset & 3) == 0) reloc_offsets.append(flash_offset) # references to the GOT from ITCM code relocs = elffile.get_section_by_name('.rel.itcm') if relocs: symtable = elffile.get_section(relocs['sh_link']) for reloc in relocs.iter_relocations(): symbol = symtable.get_symbol(reloc['r_info_sym']) # doesn't point to flash if symbol['st_value'] < 0x90000000: continue if symbol.name == '_GLOBAL_OFFSET_TABLE_': flash_offset = (reloc['r_offset'] - itcm_text_start) + itcm_data reloc_offsets.append(flash_offset) # fixup ITCM veneers for long calls back to flash itcm_section = elffile.get_section_by_name('.itcm') if itcm_section: itcm_section_data = itcm_section.data() for i in range(symtable.num_symbols()): sym = symtable.get_symbol(i) if sym.name.endswith('_veneer') and sym['st_value'] < 0xF800: # find where the target function is (strip leading __ and trailing _veneer from name) orig_sym = symtable.get_symbol_by_name(sym.name[2:-7])[0] target_addr = orig_sym['st_value'] # make sure it's in flash if target_addr < 0x90000000: continue # find the function in flash itcm_offset = (sym['st_value'] - itcm_text_start) & ~1 # clear thumb bit flash_offset = itcm_offset + itcm_data # check for the address where we expect it # (ldr.w pc, [pc] followed by the address) ex_addr, = struct.unpack('<I', itcm_section_data[itcm_offset + 4:itcm_offset + 8]) assert ex_addr == target_addr reloc_offsets.append(flash_offset + 4) with open(output, 'wb') as out_f: all_offsets = got_offsets + init_offsets + fini_offsets + reloc_offsets all_offsets.sort() out_f.write(b"RELO") out_f.write(struct.pack("<L", len(all_offsets))) for off in all_offsets: out_f.write(struct.pack("<L", off)) out_f.write(open(bin_file, 'rb').read()) def get_flash_addr_offsets(section): section_data = section.data() section_addrs = struct.unpack(f'<{len(section_data) // 4}I', section_data) section_offsets = [] for i, addr in enumerate(section_addrs): # filter out non-flash if addr < 0x90000000: continue # offset to this address in the section section_offsets.append(section['sh_addr'] + i * 4) return section_offsets
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/tool/relocs.py
relocs.py
import logging import pathlib import click from ..asset.builder import AssetBuilder, make_symbol_name from ..asset.writer import AssetWriter from ..core.yamlloader import YamlLoader class Packer(YamlLoader): def run(self, config, output, files, force): if config is None and not files: raise click.UsageError('You must supply a config or list of input files.') self.targets = [] self.setup_for_config(config, output, files) # Top level of our config is filegroups and general settings for target, options in self.config.items(): output_file = self.working_path / target logging.info(f'Preparing output target {output_file}') asset_sources = [] target_options = {} for key, value in options.items(): if key in ('prefix', 'type'): target_options[key] = value # Strip high-level options from the dict # Leaving just file source globs for key in target_options: options.pop(key) for file_glob, file_options in options.items(): # Treat the input string as a glob, and get an input filelist if type(file_glob) is str: input_files = list(self.working_path.glob(file_glob)) else: input_files = [file_glob] input_files = [f for f in input_files if f.exists()] if len(input_files) == 0: raise RuntimeError(f'Input file(s) {self.working_path / file_glob} not found for output {output_file}.') # Rewrite a single string option to `name: option` # This handles: `inputfile.bin: filename` entries if type(file_options) is str: file_options = {'name': file_options} elif file_options is None: file_options = {} # Handle both an array of options dicts or a single dict if type(file_options) is not list: file_options = [file_options] for file_opts in file_options: asset_sources.append((input_files, file_opts)) if len(asset_sources) == 0: raise RuntimeError(f'No valid input files found for output {output_file}.') self.targets.append(( output_file, asset_sources, target_options )) self.destination_path.mkdir(parents=True, exist_ok=True) for path, sources, options in self.targets: aw = AssetWriter() for input_files, file_opts in sources: for asset in self.build_assets(input_files, self.working_path, prefix=options.get('prefix'), **file_opts): aw.add_asset(*asset) aw.write(options.get('type'), self.destination_path / path.name, force=force) def build_assets(self, input_files, working_path, name=None, type=None, prefix=None, **builder_options): if type is None: # Glob files all have the same suffix, so we only care about the first one try: typestr = AssetBuilder.guess_builder(input_files[0]) except TypeError: logging.warning(f'Unable to guess type, assuming raw/binary {input_files[0]}.') typestr = 'raw/binary' else: typestr = type input_type, input_subtype = typestr.split('/') builder = AssetBuilder._by_name[input_type] # Now we know our target builder, one last iteration through the options # allows some pre-processing stages to remap paths or other idiosyncrasies # of the yml config format. # Currently the only option we need to do this on is 'palette' for images. for option in ['palette']: try: if not pathlib.Path(builder_options[option]).is_absolute(): builder_options[option] = working_path / builder_options[option] except KeyError: pass for file in input_files: symbol_name = make_symbol_name( base=name, working_path=working_path, input_file=file, input_type=input_type, input_subtype=input_subtype, prefix=prefix ) yield symbol_name, builder.from_file(file, input_subtype, **builder_options) logging.info(f' - {typestr} {file} -> {symbol_name}') @click.command('pack', help='Pack a collection of assets for 32Blit') @click.option('--config', type=pathlib.Path, help='Asset config file') @click.option('--output', type=pathlib.Path, help='Name for output file(s) or root path when using --config') @click.option('--files', multiple=True, type=pathlib.Path, help='Input files') @click.option('--force', is_flag='store_true', help='Force file overwrite') def pack_cli(config, output, files, force): Packer().run(config, output, files, force)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/tool/packer.py
packer.py
import pathlib import zlib import construct from construct import (Checksum, Const, CString, Flag, GreedyBytes, GreedyRange, Hex, Int8ul, Int16ul, Int32ul, Padded, Padding, Prefixed, RawCopy, Rebuild, Struct, len_, this) DFU_SIGNATURE = b'DfuSe' DFU_size = Rebuild(Int32ul, 0) def DFU_file_length(ctx): '''Compute the entire file size + 4 bytes for CRC The total DFU file length is ostensibly the actual length in bytes of the resulting file. However DFU File Manager does not seem to agree, since it's output size is 16 bytes short. Since this is suspiciously the same as the suffix length in bytes, we omit that number to match DFU File Manager's output. ''' size = 11 # DFU Header Length # size += 16 # DFU Suffix Length for target in ctx.targets: # Each target has a 274 byte header consisting # of the following fields: size += Const(DFU_SIGNATURE).sizeof() # szSignature ('Target' in bytes) size += Int8ul.sizeof() # bAlternateSetting size += Int8ul.sizeof() # bTargetNamed size += Padding(3).sizeof() # Padding size += Padded(255, CString('utf8')).sizeof() # szTargetName size += Int32ul.sizeof() # dwTargetSize size += Int32ul.sizeof() # dwNbElements size += DFU_target_size(target) return size def DFU_target_size(ctx): '''Returns the size of the target binary data, plus the dwElementAddress header, and dwElementSize byte count. ''' size = 0 try: images = ctx.images except AttributeError: images = ctx['images'] size += sum([DFU_image_size(image) for image in images]) return size def DFU_image_size(image): return len(image['data']) + Int32ul.sizeof() + Int32ul.sizeof() DFU_image = Struct( 'dwElementAddress' / Hex(Int32ul), # Data offset address for image 'data' / Prefixed(Int32ul, GreedyBytes) ) DFU_target = Struct( 'szSignature' / Const(b'Target'), # DFU target identifier 'bAlternateSetting' / Int8ul, # Gives device alternate setting for which this image can be used 'bTargetNamed' / Flag, # Boolean determining if the target is named Padding(3), # Mystery bytes! 'szTargetName' / Padded(255, CString('utf8')), # Target name # DFU File Manager does not initialise this # memory, so our file will not exactly match # its output. 'dwTargetSize' / Rebuild(Int32ul, DFU_target_size), # Total size of target images 'dwNbElements' / Rebuild(Int32ul, len_(this.images)), # Count the number of target images 'images' / GreedyRange(DFU_image) ) DFU_body = Struct( 'szSignature' / Const(DFU_SIGNATURE), # DFU format identifier (changes on major revisions) 'bVersion' / Const(1, Int8ul), # DFU format revision (changes on minor revisions) 'DFUImageSize' / Rebuild(Int32ul, DFU_file_length), # Total DFU file length in bytes 'bTargets' / Rebuild(Int8ul, len_(this.targets)), # Number of targets in the file 'targets' / GreedyRange(DFU_target), 'bcdDevice' / Int16ul, # Firmware version, or 0xffff if ignored 'idProduct' / Hex(Int16ul), # USB product ID or 0xffff to ignore 'idVendor' / Hex(Int16ul), # USB vendor ID or 0xffff to ignore 'bcdDFU' / Const(0x011A, Int16ul), # DFU specification number 'ucDfuSignature' / Const(b'UFD'), # 0x44, 0x46 and 0x55 ie 'DFU' but reversed 'bLength' / Const(16, Int8ul) # Length of the DFU suffix in bytes ) DFU = Struct( 'fields' / RawCopy(DFU_body), 'dwCRC' / Checksum(Int32ul, # CRC calculated over the whole file, except for itself lambda data: 0xffffffff ^ zlib.crc32(data), this.fields.data) ) def display_dfu_info(parsed): print(f''' Device: {parsed.fields.value.bcdDevice} Target: {parsed.fields.value.idProduct:04x}:{parsed.fields.value.idVendor:04x} Size: {parsed.fields.value.DFUImageSize:,} bytes Targets: {parsed.fields.value.bTargets}''') for target in parsed.fields.value.targets: print(f''' Name: {target.szTargetName} Alternate Setting: {target.bAlternateSetting} Size: {target.dwTargetSize:,} bytes Images: {target.dwNbElements}''') for image in target.images: print(f''' Offset: {image.dwElementAddress} Size: {len(image.data):,} bytes ''') def build(input_file, output_file, address, force=False, id_product=0x0000, id_vendor=0x0483): if not output_file.parent.is_dir(): raise RuntimeError(f'Output directory "{output_file.parent}" does not exist!') elif output_file.is_file() and not force: raise RuntimeError(f'Existing output file "{output_file}", use --force to overwrite!') if not input_file.suffix == ".bin": raise RuntimeError(f'Input file "{input_file}", is not a .bin file?') output = DFU.build({'fields': {'value': { 'targets': [{ 'bAlternateSetting': 0, 'bTargetNamed': True, 'szTargetName': 'ST...', 'images': [{ 'dwElementAddress': address, 'data': open(input_file, 'rb').read() }] }], 'bcdDevice': 0, 'idProduct': id_product, 'idVendor': id_vendor }}}) open(output_file, 'wb').write(output) def read(input_file): try: return DFU.parse(open(input_file, 'rb').read()) except construct.core.ConstructError as error: RuntimeError(f'Invalid dfu file {input_file} ({error})') def dump(input_file, force=False): parsed = read(input_file) for target in parsed.fields.value.targets: target_id = target.bAlternateSetting for image in target.images: address = image.dwElementAddress data = image.data dest = str(input_file).replace('.dfu', '') filename = f"{dest}-{target_id}-{address}.bin" if pathlib.Path(filename).is_file() and not force: raise RuntimeError(f'Existing output file "{filename}", use --force to overwrite!') print(f"Dumping image at {address} to {filename} ({len(data)} bytes)") open(filename, 'wb').write(data)
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/core/dfu.py
dfu.py
from math import ceil from bitstring import BitArray, Bits, ConstBitStream from construct import Adapter class RL: @staticmethod def repetitions(seq): """Input: sequence of values, Output: sequence of (value, repeat count).""" i = iter(seq) prev = next(i) count = 1 for v in i: if v == prev: count += 1 else: yield prev, count prev = v count = 1 yield prev, count @staticmethod def compress(data, bit_length): """Input: data bytes, bit length, Output: RLE'd bytes""" # TODO: This could be made more efficient by encoding the run-length # as count-n, ie 0 means a run of n, where n = break_even. Then we # can encode longer runs up to 255+n. But this needs changes in the # blit engine. break_even = ceil(8 / (bit_length + 1)) bits = BitArray() for value, count in RL.repetitions(data): while count > break_even: chunk = min(count, 0x100) bits.append('0b1') bits.append(bytes([chunk - 1])) count -= chunk bits.append(BitArray(uint=value, length=bit_length)) for x in range(count): bits.append('0b0') bits.append(BitArray(uint=value, length=bit_length)) return bits.tobytes() @staticmethod def decompress(data, bit_length, output_length): stream = ConstBitStream(bytes=data) result = [] while len(result) < output_length: t = stream.read(1) if t: count = stream.read(8).uint + 1 else: count = 1 result.extend([stream.read(bit_length).uint] * count) return bytes(result) class PK: @staticmethod def compress(data, bit_length): return BitArray().join(BitArray(uint=x, length=bit_length) for x in data).tobytes() @staticmethod def decompress(data, bit_length, num_pixels): return bytes(i.uint for i in Bits(bytes=data).cut(bit_length)) packers = {cls.__name__: cls for cls in (PK, RL)} class ImageCompressor(Adapter): def bit_length(self, obj): """Compute the required bit length for image data. Uses the count of items in the palette to determine how densely we can pack the image data. """ if obj.get('type', None) == "RW": return 8 else: return max(1, (len(obj['data']['palette']) - 1).bit_length()) def num_pixels(self, obj): return obj['data']['width'] * obj['data']['height'] def _decode(self, obj, context, path): if obj['type'] != 'RW': obj['data']['pixels'] = packers[obj['type']].decompress( obj['data']['pixels'], self.bit_length(obj), self.num_pixels(obj) ) return obj def _encode(self, obj, context, path): obj = obj.copy() # we are going to mutate this, so make a deep copy obj['data'] = obj['data'].copy() bl = self.bit_length(obj) if obj.get('type', None) is None: all_comp = [(k, v.compress(obj['data']['pixels'], bl)) for k, v in packers.items()] best = min(all_comp, key=lambda x: len(x[1])) # Put the best type back into the object. obj['type'] = best[0] obj['data']['pixels'] = best[1] elif obj['type'] != 'RW': obj['data']['pixels'] = packers[obj['type']].compress(obj['data']['pixels'], bl) return obj
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/core/compression.py
compression.py
import logging import pathlib import struct import time import serial.tools.list_ports from construct.core import ConstructError from tqdm import tqdm from ..core.struct import struct_blit_meta_standalone class BlitSerialException(Exception): pass class BlitSerial(serial.Serial): def __init__(self, port): super().__init__(port, timeout=5) @classmethod def find_comport(cls): ret = [] for comport in serial.tools.list_ports.comports(): if comport.vid == 0x0483 and comport.pid == 0x5740: logging.info(f'Found 32Blit on {comport.device}') ret.append(comport.device) if ret: return ret raise RuntimeError('Unable to find 32Blit') @classmethod def validate_comport(cls, device): if device.lower() == 'auto': return cls.find_comport()[:1] if device.lower() == 'all': return cls.find_comport() for comport in serial.tools.list_ports.comports(): if comport.device == device: if comport.vid == 0x0483 and comport.pid == 0x5740: logging.info(f'Found 32Blit on {comport.device}') return [device] # if the user asked for a port with no vid/pid assume they know what they're doing elif comport.vid is None and comport.pid is None: logging.info(f'Using unidentified port {comport.device}') return [device] raise RuntimeError(f'Unable to find 32Blit on {device}') @property def status(self): self.write(b'32BLINFO\x00') response = self.read(8) if response == b'': raise RuntimeError('Timeout waiting for 32Blit status.') return 'game' if response == b'32BL_EXT' else 'firmware' def reset(self, timeout=5.0): self.write(b'32BL_RST\x00') self.flush() self.close() time.sleep(1.0) t_start = time.time() while time.time() - t_start < timeout: try: self.open() return except BlitSerialException: time.sleep(0.1) raise RuntimeError(f"Failed to connect to 32Blit on {serial.port} after reset") def send_file(self, file, drive, directory=pathlib.PurePosixPath('/'), auto_launch=False): sent_byte_count = 0 chunk_size = 64 file_name = file.name file_size = file.stat().st_size if drive == 'sd': logging.info(f'Saving {file} ({file_size} bytes) as {file_name} in {directory}') command = f'32BLSAVE{directory}/{file_name}\x00{file_size}\x00' elif drive == 'flash': logging.info(f'Flashing {file} ({file_size} bytes)') command = f'32BLPROG{file_name}\x00{file_size}\x00' else: raise TypeError(f'Unknown destination {drive}.') self.reset_output_buffer() self.write(command.encode('ascii')) with open(file, 'rb') as input_file: progress = tqdm(total=file_size, desc=f"Flashing {file.name}", unit_scale=True, unit_divisor=1024, unit="B", ncols=70, dynamic_ncols=True) while sent_byte_count < file_size: # if we received something, there was an error if self.in_waiting: progress.close() break data = input_file.read(chunk_size) self.write(data) self.flush() sent_byte_count += chunk_size progress.update(chunk_size) response = self.read(8) if response == b'32BL__OK': # get block for flash if drive == 'flash': block, = struct.unpack('<H', self.read(2)) # do launch if requested if auto_launch: self.launch(f'flash:/{block}') elif auto_launch: self.launch(f'{directory}/{file_name}') logging.info(f'Wrote {file_name} successfully') else: response += self.read(self.in_waiting) raise RuntimeError(f"Failed to save/flash {file_name}: {response.decode()}") def erase(self, offset): self.write(b'32BLERSE\x00') self.write(struct.pack("<I", offset)) def list(self): self.write(b'32BL__LS\x00') offset_str = self.read(4) while offset_str != '' and offset_str != b'\xff\xff\xff\xff': offset, = struct.unpack('<I', offset_str) size, = struct.unpack('<I', self.read(4)) meta_head = self.read(10) meta_size, = struct.unpack('<H', meta_head[8:]) meta = None if meta_size: size += meta_size + 10 try: meta = struct_blit_meta_standalone.parse(meta_head + self.read(meta_size)) except ConstructError: pass yield (meta, offset, size) offset_str = self.read(4) def launch(self, filename): self.write(f'32BLLNCH{filename}\x00'.encode('ascii'))
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/core/blitserial.py
blitserial.py
import binascii from construct import (Adapter, Bytes, Checksum, Const, GreedyBytes, Int8ul, Int16ul, Int32ub, Int32ul, Optional, PaddedString, Prefixed, PrefixedArray, RawCopy, Rebuild, Struct, len_, this) from .compression import ImageCompressor class PaletteCountAdapter(Adapter): def _decode(self, obj, context, path): if obj == 0: obj = 256 return obj def _encode(self, obj, context, path): if obj == 256: obj = 0 return obj class ImageSizeAdapter(Adapter): """ Adds the header and type size to the size field. The size field itself is already counted. """ def _decode(self, obj, context, path): return obj - 8 def _encode(self, obj, context, path): return obj + 8 struct_blit_pixel = Struct( 'r' / Int8ul, 'g' / Int8ul, 'b' / Int8ul, 'a' / Int8ul ) struct_blit_image_compressed = Struct( 'header' / Const(b'SPRITE'), 'type' / PaddedString(2, 'ASCII'), 'data' / Prefixed(ImageSizeAdapter(Int32ul), Struct( 'width' / Int16ul, 'height' / Int16ul, 'format' / Const(0x02, Int8ul), 'palette' / PrefixedArray(PaletteCountAdapter(Int8ul), struct_blit_pixel), 'pixels' / GreedyBytes, ), includelength=True) ) struct_blit_image = ImageCompressor(struct_blit_image_compressed) struct_blit_meta = Struct( 'header' / Const(b'BLITMETA'), 'data' / Prefixed(Int16ul, Struct( 'checksum' / Checksum( Int32ul, lambda data: binascii.crc32(data), this._._.bin.data ), 'date' / PaddedString(16, 'ascii'), 'title' / PaddedString(25, 'ascii'), 'description' / PaddedString(129, 'ascii'), 'version' / PaddedString(17, 'ascii'), 'author' / PaddedString(17, 'ascii'), Const(b'BLITTYPE'), 'category' / PaddedString(17, 'ascii'), 'url' / PaddedString(129, 'ascii'), 'filetypes' / PrefixedArray(Int8ul, PaddedString(5, 'ascii')), 'icon' / struct_blit_image, 'splash' / struct_blit_image )) ) struct_blit_meta_standalone = Struct( 'header' / Const(b'BLITMETA'), 'data' / Prefixed(Int16ul, Struct( 'checksum' / Int32ul, 'date' / PaddedString(16, 'ascii'), 'title' / PaddedString(25, 'ascii'), 'description' / PaddedString(129, 'ascii'), 'version' / PaddedString(17, 'ascii'), 'author' / PaddedString(17, 'ascii'), Const(b'BLITTYPE'), 'category' / PaddedString(17, 'ascii'), 'url' / PaddedString(129, 'ascii'), 'filetypes' / PrefixedArray(Int8ul, PaddedString(5, 'ascii')), 'icon' / struct_blit_image, 'splash' / struct_blit_image )) ) struct_blit_bin = Struct( 'header' / Const(b'BLIT'), 'render' / Int32ul, 'update' / Int32ul, 'init' / Int32ul, 'length' / Int32ul, # The length above is actually the _flash_end symbol from startup_user.s # it includes the offset into 0x90000000 (external flash) # we mask out the highest nibble to correct this into the actual bin length # plus subtract 20 bytes for header, symbol and length dwords 'bin' / Bytes((this.length & 0x0FFFFFFF) - 20) ) struct_blit_relo = Struct( 'header' / Const(b'RELO'), 'relocs' / PrefixedArray(Int32ul, Struct( 'reloc' / Int32ul )) ) blit_game = Struct( 'relo' / Optional(struct_blit_relo), 'bin' / RawCopy(struct_blit_bin), 'meta' / Optional(struct_blit_meta) ) blit_game_with_meta = Struct( 'relo' / Optional(struct_blit_relo), 'bin' / RawCopy(struct_blit_bin), 'meta' / struct_blit_meta ) blit_game_with_meta_and_relo = Struct( 'relo' / struct_blit_relo, 'bin' / RawCopy(struct_blit_bin), 'meta' / struct_blit_meta ) blit_icns = Struct( 'header' / Const(b'icns'), 'size' / Rebuild(Int32ub, len_(this.data) + 16), 'type' / Const(b'ic07'), # 128×128 icon in PNG format 'data_length' / Rebuild(Int32ub, len_(this.data) + 8), 'data' / Bytes(this.data_length - 8) ) struct_blit_image_bi = Struct( 'type' / Const(1, Int16ul), # raw data 'tag' / Const(b'3B'), # 32blit tag 'data' / struct_blit_image )
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/core/struct.py
struct.py
import argparse import logging import pathlib import re import struct from PIL import Image class Colour(): def __init__(self, colour): if type(colour) is Colour: self.r, self.g, self.b = colour elif len(colour) == 6: self.r, self.g, self.b = tuple(bytes.fromhex(colour)) elif ',' in colour: self.r, self.g, self.b = [int(c, 10) for c in colour.split(',')] def __getitem__(self, index): return [self.r, self.g, self.b][index] def __repr__(self): return f'Colour{self.r, self.g, self.b}' class Palette(): def __init__(self, palette_file=None): self.transparent = None self.entries = [] if isinstance(palette_file, Palette): self.transparent = palette_file.transparent self.entries = palette_file.entries return if palette_file is not None: palette_file = pathlib.Path(palette_file) palette_type = palette_file.suffix[1:] palette_loader = f'load_{palette_type}' fn = getattr(self, palette_loader, None) if fn is None: self.load_image(palette_file) else: fn(palette_file, open(palette_file, 'rb').read()) self.extract_palette() def extract_palette(self): self.entries = [] for y in range(self.height): for x in range(self.width): self.entries.append(self.image.getpixel((x, y))) def set_transparent_colour(self, r, g, b): if (r, g, b, 0xff) in self.entries: self.transparent = self.entries.index((r, g, b, 0xff)) self.entries[self.transparent] = (r, g, b, 0x00) return self.transparent return None def load_act(self, palette_file, data): # Adobe Colour Table .act palette = data if len(palette) < 772: raise ValueError(f'palette {palette_file} is not a valid Adobe .act (length {len(palette)} != 772') size, _ = struct.unpack('>HH', palette[-4:]) self.width = 1 self.height = size self.image = Image.frombytes('RGB', (self.width, self.height), palette).convert('RGBA') def load_pal(self, palette_file, data): # Pro Motion NG .pal - MS Palette files and raw palette files share .pal suffix # Raw files are just 768 bytes palette = data if len(palette) < 768: raise ValueError(f'palette {palette_file} is not a valid Pro Motion NG .pal') # There's no length in .pal files, so we just create a 16x16 256 colour palette self.width = 16 self.height = 16 self.image = Image.frombytes('RGB', (self.width, self.height), palette).convert('RGBA') def load_gpl(self, palette_file, data): palette = data palette = palette.decode('utf-8').strip().replace('\r\n', '\n') if not palette.startswith('GIMP Palette'): raise ValueError(f'palette {palette_file} is not a valid GIMP .gpl') # Split the whole file into palette entries palette = palette.split('\n') # drop 'GIMP Palette' from the first entry palette.pop(0) # drop metadata/comments while palette[0].startswith(('Name:', 'Columns:', '#')): palette.pop(0) # calculate our image width/height here because len(palette) # equals the number of palette entries self.width = 1 self.height = len(palette) # Split out the palette entries into R, G, B and drop the hex colour # This convoluted list comprehension does this while also flatenning to a 1d array palette = [int(c) for entry in palette for c in re.split(r'\s+', entry.strip())[0:3]] self.image = Image.frombytes('RGB', (self.width, self.height), bytes(palette)).convert('RGBA') def load_image(self, palette_file): palette = Image.open(palette_file) self.width, self.height = palette.size if self.width * self.height > 256: raise argparse.ArgumentError(None, f'palette {palette_file} has too many pixels {self.width}x{self.height}={self.width*self.height} (max 256)') logging.info(f'Using palette {palette_file} {self.width}x{self.height}') self.image = palette.convert('RGBA') def quantize_image(self, image, transparent=None, strict=False): if strict and len(self) == 0: raise TypeError("Attempting to enforce strict colours with an empty palette, did you really want to do this?") w, h = image.size output_image = Image.new('P', (w, h)) for y in range(h): for x in range(w): r, g, b, a = image.getpixel((x, y)) if transparent is not None and (r, g, b) == tuple(transparent): a = 0x00 index = self.get_entry(r, g, b, a, strict=strict) output_image.putpixel((x, y), index) return output_image def get_entry(self, r, g, b, a, remap_transparent=True, strict=False): if (r, g, b, a) in self.entries: index = self.entries.index((r, g, b, a)) return index # Noisy print # logging.info(f'Re-mapping ({r}, {g}, {b}, {a}) at ({x}x{y}) to ({index})') # Anything with 0 alpha that's not in the palette might as well be the transparent colour elif a == 0 and self.transparent is not None: return self.transparent elif not strict: if len(self.entries) < 256: self.entries.append((r, g, b, a)) if a == 0: # Set this as the transparent colour - if we had one we'd have returned it already. self.transparent = len(self.entries) - 1 return len(self.entries) - 1 else: raise TypeError('Out of palette entries') else: raise TypeError(f'Colour {r}, {g}, {b}, {a} does not exist in palette!') def tostruct(self): return [dict(zip('rgba', c)) for c in self.entries] def __iter__(self): return iter(self.entries) def __len__(self): return len(self.entries) def __getitem__(self, index): return self.entries[index]
32blit
/32blit-0.7.3-py3-none-any.whl/ttblit/core/palette.py
palette.py
36-chambers ===================================================================== 36-chambers is a Python Library which adds common reversing methods and functions for Binary Ninja. The library is designed to be used within Binary Ninja in the Python console. Installation ------------ Use pip to install or upgrade 36-chambers:: $ pip install 36-chambers [--upgrade] Quick Example ------------- Find and print all blocks with a "push" instruction: .. code-block :: python from chambers import Chamber c = Chamber(bv=bv) c.instructions('push') Documentation ------------- For more information you can find documentation on readthedocs_. .. _readthedocs: https://36-chambers.readthedocs.org
36-chambers
/36-chambers-0.0.1.tar.gz/36-chambers-0.0.1/README.rst
README.rst
# 360 Monitoring CLI This repository contains a CLI script for 360 Monitoring that allows you to connect to your 360 Monitoring (https://360monitoring.com) account and list monitoring data, add, update or remove server or website monitors. ## Documentation You can find the full documentation including the feature complete REST API at [docs.360monitoring.com](https://docs.360monitoring.com/docs) and [docs.360monitoring.com/docs/api](https://docs.360monitoring.com/docs/api). ## Preconditions * Make sure to have an account at https://360monitoring.com or https://platform360.io * 360 Monitoring CLI requires a Python version of 3.* or above ## Install 360 Monitoring CLI as ready-to-use package $ pip install 360monitoringcli ## Configure your account First you need to connect your CLI to your existing 360 Monitoring account via your API KEY. If you don't have a 360 Monitoring account yet, please register for free at https://360monitoring.com. To create an API KEY you'll need to upgrade at least to a Pro plan to be able to create your API KEY. $ 360monitoring config save --api-key KEY configure API KEY to connect to 360 Monitoring account ## Test 360 Monitoring CLI locally ### Test 360 Monitoring CLI with pre-configured Docker image You can easily test and run 360 Monitoring CLI for production by running the pre-configured docker image $ docker build -t 360monitoringcli . $ docker run -it --rm 360monitoringcli /bin/bash ### Test 360 Monitoring CLI for specific staging version To test a package from staging you can simply deploy a docker container: $ docker run -it --rm ubuntu /bin/bash $ apt-get update && apt-get install -y python3 && apt-get install -y pip $ pip install -i https://test.pypi.org/simple/ --force-reinstall -v "360monitoringcli==1.0.19" ### For developement, install required Python modules To test the code locally, install the Python modules "requests", "configparser", "argparse" and "prettytable". Use "pip install -e ." to use "360monitoring" command with latest dev build locally based on local code. $ pip install requests $ pip install configparser $ pip install argparse $ pip install prettytable $ pip install -e . #### Run tests to check each function works Test the code: $ ./test_cli.sh ## Usage $ 360monitoring --help display general help $ 360monitoring signup open the sign up page to get your 360 Monitoring account $ 360monitoring config save --api-key KEY configure API KEY to connect to 360 Monitoring account (only for paid plans) $ 360monitoring statistics display all assets of your account $ 360monitoring servers list display all monitored servers $ 360monitoring servers list --issues display monitored servers with issues only $ 360monitoring servers list --tag cpanel display only servers with tag "cpanel" $ 360monitoring sites list display all monitored sites $ 360monitoring sites list --issues display monitored sites with issues only $ 360monitoring sites list --sort 6 --limit 5 display worst 5 monitored sites by uptime $ 360monitoring contacts list display all contacts $ 360monitoring usertokens list display user tokens $ 360monitoring config print display your current settings and where those are stored $ 360monitoring recommendations display upgrade recommendations for servers that exceed their limits $ 360monitoring magiclinks create and open a readonly dashboard for a single server only via magic link $ 360monitoring wptoolkit display statistics of WP Toolkit if installed $ 360monitoring sites add --url domain.tld start monitoring a new website $ 360monitoring servers update --name cpanel123.hoster.com --tag production tag a specific server $ 360monitoring contacts --help display specific help for a sub command $ 360monitoring dashboard open 360 Monitoring in your Web Browser ## Updating 360 Monitoring CLI package You can update the 360monitoringcli package to the latest version using the following command: $ pip install 360monitoringcli --upgrade
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/360monitoringcli-1.0.19.data/data/share/doc/360monitoring-cli/README.md
README.md
import os import argparse import json import subprocess import sys import webbrowser from datetime import datetime, timedelta # suprisingly this works in PyPi, but not locally. For local usage replace ".lib." with "lib." # use "pip install -e ." to use "360monitoring" command with latest dev build locally based on local code. from .lib.config import Config from .lib.contacts import Contacts from .lib.incidents import Incidents from .lib.magiclinks import MagicLinks from .lib.nodes import Nodes from .lib.recommendations import Recommendations from .lib.servers import Servers from .lib.servercharts import ServerCharts from .lib.servernotifications import ServerNotifications from .lib.sites import Sites from .lib.sitecharts import SiteCharts from .lib.sitenotifications import SiteNotifications from .lib.statistics import Statistics from .lib.usertokens import UserTokens from .lib.wptoolkit import WPToolkit __version__ = '1.0.19' # only runs on Python 3.x; throw exception on 2.x if sys.version_info[0] < 3: raise Exception("360 Monitoring CLI requires Python 3.x") cfg = Config(__version__) cli = argparse.ArgumentParser(prog='360monitoring', description='CLI for 360 Monitoring') cli_subcommands = dict() def check_version(): """Check PyPi if there is a newer version of the application, but only once every 24 hours""" # some code parts have been introduced in Python 3.7 and are not supported on older versions if sys.version_info >= (3, 7): # skip version check if the last one was within 24 hours already if cfg.last_version_check and datetime.fromisoformat(cfg.last_version_check) > (datetime.now() - timedelta(hours=24)): return latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '360monitoringcli==random'], capture_output=True, text=True)) latest_version = latest_version[latest_version.find('(from versions:')+15:] latest_version = latest_version[:latest_version.find(')')] latest_version = latest_version.replace(' ','').split(',')[-1] cfg.last_version_check = datetime.now().isoformat() cfg.saveToFile(False) if latest_version > __version__: print('Update available: Please upgrade from', __version__, 'to', latest_version, 'with: pip install 360monitoringcli --upgrade') def check_columns(columns): """Show or hide columns in ASCII table view""" for column in columns: if '0id' == column.lower(): cfg.hide_ids = True elif 'id' == column.lower(): cfg.hide_ids = False # --- config functions --- def config_print(args): """Sub command for config print""" cfg.print() def config_save(args): """Sub command for config save""" if args.api_key: cfg.api_key = args.api_key if args.usertoken: cfg.usertoken = args.usertoken if args.debug: cfg.debug = args.debug == 'on' cfg.saveToFile() def config(args): """Sub command for config""" config_print(args) # --- contacts functions --- def contacts_add(args): """Sub command for contacts add""" contacts = Contacts(cfg) if args.file: if os.path.isfile(args.file): with open(args.file) as file: lines = file.readlines() for line in lines: contacts.add(line.strip()) else: print('ERROR: File', args.file, 'to import not found') elif args.name: contacts.add(name=args.name, email=args.email, sms=args.sms) else: print('You need to specify at least a name with --name [name]') def contacts_list(args): """Sub command for contacts list""" check_columns(args.columns) contacts = Contacts(cfg, format=args.output) contacts.list(id=args.id, name=args.name, email=args.email, phone=args.phone, sort=args.sort, reverse=args.reverse, limit=args.limit) def contacts_remove(args): """Sub command for contacts remove""" contacts = Contacts(cfg) contacts.remove(id=args.id, name=args.name, email=args.email, phone=args.phone) def contacts(args): """Sub command for contacts""" cli_subcommands[args.subparser].print_help() # --- dashboard functions --- def dashboard(args): """Sub command for dashboard""" webbrowser.open('https://monitoring.platform360.io/') # --- incidents functions --- def incidents_add(args): """Sub command for incidents add""" incidents = Incidents(cfg) incidents.add(page_id=args.page_id, name=args.name, body=args.body) def incidents_list(args): """Sub command for incidents list""" incidents = Incidents(cfg, format=args.output) incidents.list(page_id=args.page_id, name=args.name) def incidents_remove(args): """Sub command for incidents remove""" incidents = Incidents(cfg) incidents.remove(page_id=args.page_id, id=args.id, name=args.name) def incidents(args): """Sub command for incidents""" cli_subcommands[args.subparser].print_help() # --- magiclink functions --- def magiclinks_create(args): """Sub command for magiclink create""" serverId = '' usertoken = args.usertoken if args.usertoken else cfg.usertoken if args.id: serverId = args.id elif args.name: # find correct server id for the server with the specified name servers = Servers(cfg) serverId = servers.getServerId(args.name) if usertoken and serverId: magiclinks = MagicLinks(cfg) magiclink = magiclinks.create(usertoken, serverId, 'Dashboard') if magiclink and args.open: webbrowser.open(magiclink) # if usertoken is not yet stored in config, do it now if not cfg.usertoken: cfg.usertoken = usertoken cfg.saveToFile(False) else: print('Please specify an existing server either by "--id id" or "--name hostname" and specifiy your user token "--usertoken token"') def magiclinks(args): """Sub command for magiclink""" cli_subcommands[args.subparser].print_help() # --- nodes functions --- def nodes(args): """Sub command for nodes""" check_columns(args.columns) nodes = Nodes(cfg, format=args.output) nodes.list(id=args.id, name=args.name, sort=args.sort, reverse=args.reverse, limit=args.limit) # --- recommendations functions --- def recommendations(args): """Sub command for recommendations""" recommendations = Recommendations(cfg) recommendations.print(format=args.output) # --- servers functions --- def servers_add(args): """Sub command for servers add""" usertokens = UserTokens(cfg) token = usertokens.token() if not token: print('First create a user token by executing:') print() print('360monitoring usertokens create') print('360monitoring usertokens list') print() token = '[YOUR_USER_TOKEN]' print('Please login via SSH to each of the servers you would like to add and execute the following command:') print() print('wget -q -N monitoring.platform360.io/agent360.sh && bash agent360.sh', token) def servers_charts(args): """Sub command for servers charts""" cli_subcommands[args.subparser].print_help() def servers_charts_create(args): """Sub command for servers charts""" serverId = '' startDate = datetime.strptime(args.start.strip('\"'), '%Y-%m-%d').timestamp() if args.start else 0 endDate = datetime.strptime(args.end.strip('\"'), '%Y-%m-%d').timestamp() if args.end else 0 if args.id: serverId = args.id elif args.name: # find correct server id for the server with the specified name servers = Servers(cfg) serverId = servers.getServerId(args.name) if serverId: charts = ServerCharts(cfg) chart_url = charts.create(serverId, args.metric, startDate, endDate) if chart_url and args.open: webbrowser.open(chart_url) else: print('Please specify an existing server either by "--id id" or "--name hostname"') def servers_events(args): """Sub command for servers events""" serverId = '' startDate = datetime.strptime(args.start.strip('\"'), '%Y-%m-%d') if args.start else (datetime.today() - timedelta(days=365)) endDate = datetime.strptime(args.end.strip('\"'), '%Y-%m-%d') if args.end else datetime.now() if args.id: serverId = args.id elif args.name: servers = Servers(cfg) serverId = servers.getServerId(args.name) if serverId: notifications = ServerNotifications(cfg, format=args.output) notifications.list(serverId, startDate.timestamp(), endDate.timestamp(), args.sort, args.reverse, args.limit) def servers_list(args): """Sub command for servers list""" check_columns(args.columns) servers = Servers(cfg, format=args.output) servers.list(args.issues, args.sort, args.reverse, args.limit, args.tag) def servers_remove(args): """Sub command for servers remove""" print("Please login via SSH to each of the servers you would like to remove.") print("First stop the monitoring agent by running \"service agent360 stop\" then run \"pip3 uninstall agent360\". After 15 minutes you are able to remove the server.") def servers_update(args): """Sub command for servers update""" servers = Servers(cfg) pattern = '' if args.id: pattern = args.id elif args.name: pattern = args.name servers.setTags(pattern, args.tag) def servers(args): """Sub command for servers""" cli_subcommands[args.subparser].print_help() # --- signup functions --- def signup(args): """Sub command for signup""" webbrowser.open('https://360monitoring.com/monitoring-trial/') # --- sites functions --- def sites_add(args): """Sub command for sites add""" sites = Sites(cfg) nodeId = '' if args.node_id: nodeId = args.node_id elif args.node_name: nodes = Nodes(cfg) nodeId = nodes.getNodeId(args.node_name) if args.file: if os.path.isfile(args.file): with open(args.file) as file: lines = file.readlines() for line in lines: sites.add(line.strip(), protocol=args.protocol, name=args.name, port=args.port, keyword=args.keyword, matchType=args.match_type, nodeId=nodeId, force=args.force) else: print('ERROR: File', args.file, 'to import not found') elif args.url: sites.add(args.url, protocol=args.protocol, name=args.name, port=args.port, keyword=args.keyword, matchType=args.match_type, nodeId=nodeId, force=args.force) else: print('You need to specify at least a name with --name [name]') def sites_charts(args): """Sub command for sites charts""" cli_subcommands[args.subparser].print_help() def sites_charts_create(args): """Sub command for sites charts""" siteId = '' startDate = datetime.strptime(args.start.strip('\"'), '%Y-%m-%d').timestamp() if args.start else 0 endDate = datetime.strptime(args.end.strip('\"'), '%Y-%m-%d').timestamp() if args.end else 0 if args.id: siteId = args.id elif args.url: # find correct server id for the server with the specified name sites = Sites(cfg) siteId = sites.getSiteId(args.url) if siteId: charts = SiteCharts(cfg) chart_url = charts.create(siteId, startDate, endDate) if chart_url and args.open: webbrowser.open(chart_url) else: print('Please specify an existing site either by "--id id" or "--url url"') def sites_events(args): """Sub command for sites events""" siteId = '' startDate = datetime.strptime(args.start.strip('\"'), '%Y-%m-%d') if args.start else (datetime.today() - timedelta(days=365)) endDate = datetime.strptime(args.end.strip('\"'), '%Y-%m-%d') if args.end else datetime.now() if args.id: siteId = args.id elif args.url: sites = Sites(cfg) siteId = sites.getSiteId(args.url) if siteId: notifications = SiteNotifications(cfg, format=args.output) notifications.list(siteId, startDate.timestamp(), endDate.timestamp(), args.sort, args.reverse, args.limit) def sites_list(args): """Sub command for sites list""" check_columns(args.columns) sites = Sites(cfg, format=args.output) sites.list(id=args.id, url=args.url, name=args.name, location=args.location, pattern=args.pattern, issuesOnly=args.issues, sort=args.sort, reverse=args.reverse, limit=args.limit) def sites_remove(args): """Sub command for sites remove""" sites = Sites(cfg) sites.remove(id=args.id, url=args.url, name=args.name, location=args.location, pattern=args.pattern) def sites_uptime(args): """Sub command for sites uptime""" siteId = '' startDate = datetime.strptime(args.start.strip('\"'), '%Y-%m-%d') if args.start else (datetime.today() - timedelta(days=365)) endDate = datetime.strptime(args.end.strip('\"'), '%Y-%m-%d') if args.end else datetime.now() sites = Sites(cfg) if args.id: siteId = args.id elif args.url: siteId = sites.getSiteId(args.url) elif args.name: siteId = sites.getSiteId(args.name) if siteId: if args.daily: periods = [] firstDate = startDate while endDate > firstDate: startDate = datetime(endDate.year, endDate.month, endDate.day, 0, 0, 0) endDate = datetime(endDate.year, endDate.month, endDate.day, 23, 59, 59) periods.append([startDate.timestamp(), endDate.timestamp()]) endDate = startDate - timedelta(days=1) sites.listUptimes(siteId, periods) elif args.monthly: periods = [] firstDate = startDate while endDate > firstDate: startDate = datetime(endDate.year, endDate.month, 1, 0, 0, 0) endDate = datetime(endDate.year, endDate.month, endDate.day, 23, 59, 59) periods.append([startDate.timestamp(), endDate.timestamp()]) endDate = startDate - timedelta(days=1) sites.listUptimes(siteId, periods, '%Y-%m') elif args.start or args.end: sites.listUptimes(siteId, [[startDate.timestamp(), endDate.timestamp()]]) else: periods = [] periods.append([(datetime.now() - timedelta(days=1)).timestamp(), datetime.now().timestamp()]) periods.append([(datetime.now() - timedelta(days=7)).timestamp(), datetime.now().timestamp()]) periods.append([(datetime.now() - timedelta(days=30)).timestamp(), datetime.now().timestamp()]) periods.append([(datetime.now() - timedelta(days=90)).timestamp(), datetime.now().timestamp()]) periods.append([(datetime.now() - timedelta(days=365)).timestamp(), datetime.now().timestamp()]) sites.listUptimes(siteId, periods) def sites(args): """Sub command for sites""" cli_subcommands[args.subparser].print_help() # --- statistics functions --- def statistics(args): """Sub command for statistics""" statistics = Statistics(cfg) statistics.print(format=args.output) # --- usertokens functions --- def usertokens_create(args): """Sub command for usertokens create""" usertokens = UserTokens(cfg) usertokens.create(name=args.name, tags=args.tag) def usertokens_list(args): """Sub command for usertokens list""" usertokens = UserTokens(cfg) usertokens.list(format=args.output) def usertokens(args): """Sub command for usertokens""" cli_subcommands[args.subparser].print_help() # --- wptoolkit functions --- def wptoolkit(args): """Sub command for wptoolkit""" check_columns(args.columns) wptoolkit = WPToolkit(cfg) wptoolkit.print(format=args.output, issuesOnly=args.issues, sort=args.sort, reverse=args.reverse, limit=args.limit) # --- configure & parse CLI --- def performCLI(): """Parse the command line parameters and call the related functions""" subparsers = cli.add_subparsers(title='commands', dest='subparser') cli.add_argument('-v', '--version', action='store_true', help='print CLI version') # config cli_config = subparsers.add_parser('config', help='configure connection to 360 Monitoring account') cli_config.set_defaults(func=config) cli_config_subparsers = cli_config.add_subparsers(title='commands', dest='subparser') cli_config_print = cli_config_subparsers.add_parser('print', help='print current settings for 360 Monitoring') cli_config_print.set_defaults(func=config_print) cli_config_save = cli_config_subparsers.add_parser('save', help='save current settings for 360 Monitoring to ' + cfg.filename) cli_config_save.set_defaults(func=config_save) cli_config_save.add_argument('--api-key', metavar='key', help='specify your API KEY for 360 Monitoring') cli_config_save.add_argument('--usertoken', metavar='token', help='specify your USERTOKEN for 360 Monitoring') cli_config_save.add_argument('--debug', choices=['on', 'off'], type=str, help='switch debug mode to print all API calls on or off') # contacts cli_contacts = subparsers.add_parser('contacts', help='list and manage contacts') cli_contacts.set_defaults(func=contacts) cli_contacts_subparsers = cli_contacts.add_subparsers(title='commands', dest='subparser') cli_contacts_add = cli_contacts_subparsers.add_parser('add', help='add a new contact') cli_contacts_add.set_defaults(func=contacts_add) cli_contacts_add.add_argument('--name', nargs='?', metavar='name', help='name of the new contact') cli_contacts_add.add_argument('--email', nargs='?', default='', metavar='email', help='email address of the new contact') cli_contacts_add.add_argument('--sms', nargs='?', default='', metavar='phone', help='mobile phone number of the new contact (optional)') cli_contacts_add.add_argument('--file', nargs='?', default='', metavar='file', help='file containing one contact per line to add') cli_contacts_list = cli_contacts_subparsers.add_parser('list', help='list contacts') cli_contacts_list.set_defaults(func=contacts_list) cli_contacts_list.add_argument('--id', nargs='?', default='', metavar='id', help='list contact with given ID') cli_contacts_list.add_argument('--name', nargs='?', default='', metavar='name', help='list contact with given name') cli_contacts_list.add_argument('--email', nargs='?', default='', metavar='email', help='list contact with given email address') cli_contacts_list.add_argument('--phone', nargs='?', default='', metavar='phone', help='list contact with given phone number') cli_contacts_list.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_contacts_list.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_contacts_list.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_contacts_list.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_contacts_list.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_contacts_list.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_contacts_list.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_contacts_list.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') cli_contacts_remove = cli_contacts_subparsers.add_parser('remove', help='remove a contact') cli_contacts_remove.set_defaults(func=contacts_remove) cli_contacts_remove.add_argument('--id', nargs='?', default='', metavar='id', help='remove contact with given ID') cli_contacts_remove.add_argument('--name', nargs='?', default='', metavar='name', help='remove contact with given name') cli_contacts_remove.add_argument('--email', nargs='?', default='', metavar='email', help='remove contact with given email address') cli_contacts_remove.add_argument('--phone', nargs='?', default='', metavar='phone', help='remove contact with given phone number') # dashboard cli_dashboard = subparsers.add_parser('dashboard', help='open 360 Monitoring Dashboard in your Web Browser') cli_dashboard.set_defaults(func=dashboard) # incidents cli_incidents = subparsers.add_parser('incidents', help='list and manage incidents') cli_incidents.set_defaults(func=incidents) cli_incidents_subparsers = cli_incidents.add_subparsers(title='commands', dest='subparser') cli_incidents_add = cli_incidents_subparsers.add_parser('add', help='add a new incident') cli_incidents_add.set_defaults(func=incidents_add) cli_incidents_add.add_argument('--page-id', required=True, metavar='id', help='list incidents from status page with given ID') cli_incidents_add.add_argument('--name', required=True, metavar='name', help='name of the new incident') cli_incidents_add.add_argument('--body', metavar='body', help='text of the new incident') cli_incidents_list = cli_incidents_subparsers.add_parser('list', help='list incidents') cli_incidents_list.set_defaults(func=incidents_list) cli_incidents_list.add_argument('--page-id', required=True, metavar='id', help='list incidents from status page with given ID') cli_incidents_list.add_argument('--name', nargs='?', default='', metavar='name', help='list incidents with given name') cli_incidents_list.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_incidents_list.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_incidents_list.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_incidents_list.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') cli_incidents_remove = cli_incidents_subparsers.add_parser('remove', help='remove an incident') cli_incidents_remove.set_defaults(func=incidents_remove) cli_incidents_remove.add_argument('--page-id', required=True, metavar='id', help='remove incidents from status page with given ID') cli_incidents_remove.add_argument('--id', nargs='?', default='', metavar='id', help='remove incident with given ID') cli_incidents_remove.add_argument('--name', nargs='?', default='', metavar='name', help='remove incident with given name') # magiclinks cli_magiclinks = subparsers.add_parser('magiclinks', help='create a magic link for the dasboard of a specific server') cli_magiclinks.set_defaults(func=magiclinks) cli_magiclinks_subparsers = cli_magiclinks.add_subparsers(title='commands', dest='subparser') cli_magiclinks_create = cli_magiclinks_subparsers.add_parser('create', help='create new magic link to access the (readonly) dashboard for a specific server only') cli_magiclinks_create.set_defaults(func=magiclinks_create) cli_magiclinks_create.add_argument('--id', nargs='?', default='', metavar='id', help='create magic link for server with given ID') cli_magiclinks_create.add_argument('--name', nargs='?', default='', metavar='name', help='create magic link for server with given name') cli_magiclinks_create.add_argument('--usertoken', nargs='?', default='', metavar='token', help='use this usertoken for authentication') cli_magiclinks_create.add_argument('--open', action='store_true', help='open the server dashboard directly in the default web browser (optional)') # nodes cli_nodes = subparsers.add_parser('nodes', help='show monitoring locations') cli_nodes.set_defaults(func=nodes) cli_nodes.add_argument('--id', nargs='?', default='', metavar='id', help='show node with given ID') cli_nodes.add_argument('--name', nargs='?', default='', metavar='name', help='show node with given name') cli_nodes.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_nodes.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_nodes.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_nodes.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_nodes.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_nodes.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_nodes.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_nodes.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') # recommendations cli_recommendations = subparsers.add_parser('recommendations', help='show upgrade recommendations for servers that exceed their limits') cli_recommendations.set_defaults(func=recommendations) cli_recommendations.add_argument('--output', choices=['csv', 'table'], default='table', help='output format for the data') cli_recommendations.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_recommendations.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') # servers cli_servers = subparsers.add_parser('servers', help='list and manage monitored servers') cli_servers.set_defaults(func=servers) cli_servers_subparsers = cli_servers.add_subparsers(title='commands', dest='subparser') cli_servers_add = cli_servers_subparsers.add_parser('add', help='activate monitoring for a server') cli_servers_add.set_defaults(func=servers_add) cli_servers_charts = cli_servers_subparsers.add_parser('charts', help='create a metrics chart as PNG file and print its url or open it in your browser') cli_servers_charts.set_defaults(func=servers_charts) cli_servers_charts_subparsers = cli_servers_charts.add_subparsers(title='commands', dest='subparser') cli_servers_charts_create = cli_servers_charts_subparsers.add_parser('create', help='create a metrics chart as PNG file and print its url or open it in your browser') cli_servers_charts_create.set_defaults(func=servers_charts_create) cli_servers_charts_create.add_argument('--id', nargs='?', default='', metavar='id', help='show metrics for server with given ID') cli_servers_charts_create.add_argument('--name', nargs='?', default='', metavar='name', help='show metrics for server with given name') cli_servers_charts_create.add_argument('--metric', nargs='?', default='cpu', metavar='metric', help='select the metric to chart, e.g. \"cpu\", \"mem\", \"nginx\", \"bitninja\", \"httpd\", \"network\", \"ping\", \"process\", \"swap\", \"uptime\", \"wp-toolkit\" (optional)') cli_servers_charts_create.add_argument('--start', nargs='?', default='', metavar='start', help='select start date of chart period in form of \"yyyy-mm-dd\" (optional)') cli_servers_charts_create.add_argument('--end', nargs='?', default='', metavar='end', help='select end date of chart period in form of \"yyyy-mm-dd\" (optional)') cli_servers_charts_create.add_argument('--open', action='store_true', help='open the metrics chart directly in the default web browser (optional)') cli_servers_events = cli_servers_subparsers.add_parser('events', help='list event notifications of a specified server') cli_servers_events.set_defaults(func=servers_events) cli_servers_events.add_argument('--id', nargs='?', default='', metavar='id', help='show event notifications for server with given ID') cli_servers_events.add_argument('--name', nargs='?', default='', metavar='name', help='show event notifications for server with given name') cli_servers_events.add_argument('--start', nargs='?', default='', metavar='start', help='select start date of notification period in form of yyyy-mm-dd') cli_servers_events.add_argument('--end', nargs='?', default='', metavar='end', help='select end date of notification period in form of yyyy-mm-dd') cli_servers_events.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_servers_events.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_servers_events.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_servers_events.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_servers_events.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_servers_events.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_servers_events.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_servers_events.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') cli_servers_list = cli_servers_subparsers.add_parser('list', help='list monitored servers') cli_servers_list.set_defaults(func=servers_list) cli_servers_list.add_argument('--id', nargs='?', default='', metavar='id', help='update server with given ID') cli_servers_list.add_argument('--name', nargs='?', default='', metavar='name', help='update server with given name') cli_servers_list.add_argument('--tag', nargs='*', default='', metavar='tag', help='only list servers matching these tags') cli_servers_list.add_argument('--issues', action='store_true', help='show only servers with issues') cli_servers_list.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_servers_list.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_servers_list.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_servers_list.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_servers_list.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_servers_list.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_servers_list.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_servers_list.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') cli_servers_remove = cli_servers_subparsers.add_parser('remove', help='remove monitoring for a server') cli_servers_remove.set_defaults(func=servers_remove) cli_servers_update = cli_servers_subparsers.add_parser('update', help='set tags for a server') cli_servers_update.set_defaults(func=servers_update) cli_servers_update.add_argument('--id', nargs='?', default='', metavar='id', help='update server with given ID') cli_servers_update.add_argument('--name', nargs='?', default='', metavar='name', help='update server with given name') cli_servers_update.add_argument('--tag', nargs='*', default='', metavar='tag', help='set these tags for one or more servers specified') # signup cli_signup = subparsers.add_parser('signup', help='sign up for 360 Monitoring') cli_signup.set_defaults(func=signup) # sites cli_sites = subparsers.add_parser('sites', help='list and manage monitored websites') cli_sites.set_defaults(func=sites) cli_sites_subparsers = cli_sites.add_subparsers(title='commands', dest='subparser') cli_sites_add = cli_sites_subparsers.add_parser('add', help='activate monitoring for a site') cli_sites_add.set_defaults(func=sites_add) cli_sites_add.add_argument('--url', nargs='?', metavar='url', help='url of site that should be monitored') cli_sites_add.add_argument('--name', nargs='?', metavar='name', help='name of site that should be monitored (optional)') cli_sites_add.add_argument('--protocol', choices=['http', 'https', 'icmp', 'tcp'], default='https', metavar='protocol', help='specify a different protocol than https') cli_sites_add.add_argument('--port', nargs='?', default=443, type=int, metavar='port', help='specify a different port than 443') cli_sites_add.add_argument('--keyword', nargs='?', metavar='keyword', help='alert when the specified keyword is found/not found in the page HTML (optional)') cli_sites_add.add_argument('--match-type', choices=['', 'yes', 'no'], default='', metavar='type', help='if set to \"yes\" it will alert when keyword is found on page, if \"no\" alert when keyword not found') cli_sites_add.add_argument('--node-id', nargs='?', metavar='id', help='id of the monitoring node location that should monitor the url (optional)') cli_sites_add.add_argument('--node-name', nargs='?', metavar='id', help='name of the monitoring node location that should monitor the url. In doubt, take the first match. (optional)') cli_sites_add.add_argument('--force', action='store_true', help='add new monitor even if already exists') cli_sites_add.add_argument('--file', nargs='?', default='', metavar='file', help='file containing one URL per line to monitor') cli_sites_charts = cli_sites_subparsers.add_parser('charts', help='create a metrics chart as PNG file and print its url or open it in your browser') cli_sites_charts.set_defaults(func=sites_charts) cli_sites_charts_subparsers = cli_sites_charts.add_subparsers(title='commands', dest='subparser') cli_sites_charts_create = cli_sites_charts_subparsers.add_parser('create', help='create a metrics chart as PNG file and print its url or open it in your browser') cli_sites_charts_create.set_defaults(func=sites_charts_create) cli_sites_charts_create.add_argument('--id', nargs='?', default='', metavar='id', help='show metrics for server with given ID') cli_sites_charts_create.add_argument('--url', nargs='?', default='', metavar='url', help='show metrics for server with given url') cli_sites_charts_create.add_argument('--start', nargs='?', default='', metavar='start', help='select start date of chart period in form of \"yyyy-mm-dd\" (optional)') cli_sites_charts_create.add_argument('--end', nargs='?', default='', metavar='end', help='select end date of chart period in form of \"yyyy-mm-dd\" (optional)') cli_sites_charts_create.add_argument('--open', action='store_true', help='open the metrics chart directly in the default web browser (optional)') cli_sites_events = cli_sites_subparsers.add_parser('events', help='list event notifications of a specified site') cli_sites_events.set_defaults(func=sites_events) cli_sites_events.add_argument('--id', nargs='?', default='', metavar='id', help='show event notifications for site with given ID') cli_sites_events.add_argument('--url', nargs='?', default='', metavar='url', help='show event notifications for site with given url') cli_sites_events.add_argument('--start', nargs='?', default='', metavar='start', help='select start date of notification period in form of yyyy-mm-dd') cli_sites_events.add_argument('--end', nargs='?', default='', metavar='end', help='select end date of notification period in form of yyyy-mm-dd') cli_sites_events.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_sites_events.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_sites_events.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_sites_events.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_sites_events.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_sites_events.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_sites_events.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_sites_events.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') cli_sites_list = cli_sites_subparsers.add_parser('list', help='list sites') cli_sites_list.set_defaults(func=sites_list) cli_sites_list.add_argument('--id', nargs='?', default='', metavar='id', help='list site with given ID') cli_sites_list.add_argument('--url', nargs='?', default='', metavar='url', help='list site with given url') cli_sites_list.add_argument('--name', nargs='?', default='', metavar='name', help='list site with given name') cli_sites_list.add_argument('--location', nargs='?', default='', metavar='location', help='list sites monitored from given location') cli_sites_list.add_argument('--pattern', nargs='?', default='', metavar='pattern', help='list sites with pattern included in URL') cli_sites_list.add_argument('--issues', action='store_true', help='show only sites with issues') cli_sites_list.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_sites_list.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_sites_list.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_sites_list.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_sites_list.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_sites_list.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_sites_list.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_sites_list.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') cli_sites_remove = cli_sites_subparsers.add_parser('remove', help='remove a contact') cli_sites_remove.set_defaults(func=sites_remove) cli_sites_remove.add_argument('--id', nargs='?', default='', metavar='id', help='remove site with given ID') cli_sites_remove.add_argument('--url', nargs='?', default='', metavar='url', help='remove site with given url') cli_sites_remove.add_argument('--name', nargs='?', default='', metavar='name', help='remove site with given name') cli_sites_remove.add_argument('--location', nargs='?', default='', metavar='location', help='remove sites monitored from given location') cli_sites_remove.add_argument('--pattern', nargs='?', default='', metavar='pattern', help='remove sites with pattern included in URL') cli_sites_uptime = cli_sites_subparsers.add_parser('uptime', help='show uptime') cli_sites_uptime.set_defaults(func=sites_uptime) cli_sites_uptime.add_argument('--id', nargs='?', default='', metavar='id', help='show uptime for site with given ID') cli_sites_uptime.add_argument('--url', nargs='?', default='', metavar='url', help='show uptime for site with given url') cli_sites_uptime.add_argument('--name', nargs='?', default='', metavar='name', help='show uptime for site with given name') cli_sites_uptime.add_argument('--start', nargs='?', default='', metavar='start', help='select start date of uptime period in form of yyyy-mm-dd') cli_sites_uptime.add_argument('--end', nargs='?', default='', metavar='end', help='select end date of uptime period in form of yyyy-mm-dd') cli_sites_uptime.add_argument('--daily', action='store_true', help='show uptime per day') cli_sites_uptime.add_argument('--monthly', action='store_true', help='show uptime per month') # statistics cli_statistics = subparsers.add_parser('statistics', help='print statistics') cli_statistics.set_defaults(func=statistics) cli_statistics.add_argument('--output', choices=['csv', 'table'], default='table', help='output format for the data') cli_statistics.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_statistics.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') # user tokens cli_usertokens = subparsers.add_parser('usertokens', help='list or create usertokens') cli_usertokens.set_defaults(func=usertokens) cli_usertokens_subparsers = cli_usertokens.add_subparsers(title='commands', dest='subparser') cli_usertokens_create = cli_usertokens_subparsers.add_parser('create', help='create new user token') cli_usertokens_create.set_defaults(func=usertokens_create) cli_usertokens_create.add_argument('--name', nargs='?', default='', metavar='name', help='name of the new token (optional)') cli_usertokens_create.add_argument('--tag', nargs='?', default='', metavar='tag', help='set a tag for the new token (optional)') cli_usertokens_list = cli_usertokens_subparsers.add_parser('list', help='list usertokens') cli_usertokens_list.set_defaults(func=usertokens_list) cli_usertokens_list.add_argument('--output', choices=['json', 'csv', 'table'], default='table', help='output format for the data') cli_usertokens_list.add_argument('--json', action='store_const', const='json', dest='output', help='print data in JSON format') cli_usertokens_list.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_usertokens_list.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') # wptoolkit cli_wptoolkit = subparsers.add_parser('wptoolkit', help='list statistics of WP Toolkit if installed') cli_wptoolkit.set_defaults(func=wptoolkit) cli_wptoolkit.add_argument('--issues', action='store_true', help='show only servers with WordPress issues') cli_wptoolkit.add_argument('--columns', nargs='*', default='', metavar='col', help='specify columns to print in table view or remove columns with 0 as prefix e.g. "0id"') cli_wptoolkit.add_argument('--sort', nargs='?', default='', metavar='col', help='sort by specified column. Reverse sort by adding --reverse') cli_wptoolkit.add_argument('--reverse', action='store_true', help='show in descending order. Works only together with --sort') cli_wptoolkit.add_argument('--limit', nargs='?', default=0, type=int, metavar='n', help='limit the number of printed items') cli_wptoolkit.add_argument('--output', choices=['csv', 'table'], default='table', help='output format for the data') cli_wptoolkit.add_argument('--csv', action='store_const', const='csv', dest='output', help='print data in CSV format') cli_wptoolkit.add_argument('--table', action='store_const', const='table', dest='output', help='print data as ASCII table') # Parse cli_subcommands['config'] = cli_config cli_subcommands['contacts'] = cli_contacts cli_subcommands['dashboard'] = cli_dashboard cli_subcommands['incidents'] = cli_incidents cli_subcommands['magiclinks'] = cli_magiclinks cli_subcommands['nodes'] = cli_nodes cli_subcommands['recommendations'] = cli_recommendations cli_subcommands['servers'] = cli_servers cli_subcommands['signup'] = cli_signup cli_subcommands['sites'] = cli_sites cli_subcommands['statistics'] = cli_statistics cli_subcommands['usertokens'] = cli_usertokens cli_subcommands['wptoolkit'] = cli_wptoolkit args = cli.parse_args() if args.subparser == None: if args.version: print('360 Monitoring CLI Version:', __version__) elif 'func' in args: # nodes, recommendations, statistics, signup, wptoolkit and dashboard is shown directly without subparser if args.func == config: cli_config.print_help() elif args.func == contacts: cli_contacts.print_help() elif args.func == incidents: cli_incidents.print_help() elif args.func == magiclinks: cli_magiclinks.print_help() elif args.func == servers: cli_servers.print_help() elif args.func == servers_charts: cli_servers_charts.print_help() elif args.func == sites: cli_sites.print_help() elif args.func == usertokens: cli_usertokens.print_help() else: cli.print_help() else: cli.print_help() else: args.func(args) def main(): check_version() performCLI() if __name__ == '__main__': main()
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/monitoring.py
monitoring.py
import json from prettytable import PrettyTable from datetime import datetime from .api import apiGet, apiPost, apiDelete from .config import Config from .functions import printError, printWarn, formatDowntime, formatTimespan from .bcolors import bcolors class Sites(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.monitors = None self.table = PrettyTable(field_names=['ID', 'URL', 'Status', 'Uptime %', 'Time to first Byte', 'Location']) self.table.align['ID'] = 'l' self.table.align['URL'] = 'l' self.table.min_width['URL'] = 25 self.table.align['Status'] = 'l' self.table.align['Uptime %'] = 'r' self.table.align['Time to first Byte'] = 'c' self.table.align['Location'] = 'c' self.sum_uptime = 0 self.sum_ttfb = 0 self.num_monitors = 0 def fetchData(self): """Retrieve the list of all website monitors""" # if data is already downloaded, use cached data if self.monitors != None: return True response_json = apiGet('monitors', 200, self.config) if response_json: if 'monitors' in response_json: self.monitors = response_json['monitors'] return True else: printWarn('No monitors found') self.monitors = None return False else: self.monitors = None return False def getSiteId(self, url: str): """Return Site Id for the monitor with the specified url or name. Only the first matching entry (exact match) is returned or empty string if not found""" if url and self.fetchData(): # Iterate through list of monitors and find the specified one for monitor in self.monitors: if monitor['url'] == url or (monitor['name'] and monitor['name'] == url): return monitor['id'] return '' def getSiteUrl(self, id: str): """Return Site Url for the monitor with the specified id""" if id and self.fetchData(): # Iterate through list of monitors and find the specified one for monitor in self.monitors: if monitor['id'] == id: return monitor['url'] return '' def list(self, id: str = '', url: str = '', name: str = '', location: str = '', pattern: str = '', issuesOnly: bool = False, sort: str = '', reverse: bool = False, limit: int = 0): """Iterate through list of web monitors and print details""" if self.fetchData(): # if JSON was requested and no filters, then just print it without iterating through if (self.format == 'json' and not (id or url or name or location or pattern or issuesOnly or limit > 0)): print(json.dumps(self.monitors, indent=4)) return self.printHeader() self.sum_uptime = 0 self.sum_ttfb = 0 self.num_monitors = 0 for monitor in self.monitors: if (id or url or name or location or pattern): if (id and monitor['id'] == id) \ or (url and monitor['url'] == url) \ or (name and 'name' in monitor and monitor['name'] == name) \ or (location and location in monitor['monitor']['name']) \ or (pattern and pattern in monitor['url']): if (not issuesOnly) or self.hasIssue(monitor): self.print(monitor) else: if (not issuesOnly) or self.hasIssue(monitor): self.print(monitor) self.printFooter(sort=sort, reverse=reverse, limit=limit) def add(self, url: str, protocol: str = 'https', name: str = '', port: int = 443, keyword: str = '', matchType:str = '', nodeId: str = '', force: bool = False): """Add a monitor for the given URL""" if url and self.fetchData(): # urls do not include the protocol url = url.replace('https://', '').replace('http://', '') # use the url as name if not specified otherwise if not name: name = url # use https as protocol if not specified otherwise if not protocol: protocol = 'https' # check if monitored url already exists unless --force is specified if not force: for monitor in self.monitors: if monitor['url'] == url: print(url, 'already exists and will not be added') return # other parameters: # port: int (e.g. 443, 80) # redirects: int (e.g. 3 max redirects; 0 for no redirects) # timeout: int (e.g. 30 seconds) # interval: int # How often to perform the check in seconds # keyword: str # Alert when error on my page is found in the page HTML # match_type: str 'yes' or 'no' # If set to yes it will alert when keyword is found on page, if no alert when keyword not found # monitor: str # protocol: str [http, https, icmp, tcp] # Make request to API endpoint data = { 'url': url, 'name': name, 'port': port, 'protocol': protocol, 'keyword': keyword, 'match_type': matchType, 'monitor': nodeId, } apiPost('monitors', self.config, data=data, expectedStatusCode=200, successMessage='Added site monitor: ' + url, errorMessage='Failed to add site monitor ' + url + '') def remove(self, id: str = '', url: str = '', name: str = '', location: str = '', pattern: str = ''): """Remove the monitor for the given URL""" removed = 0 if (id or url or name or location or pattern) and self.fetchData(): for monitor in self.monitors: curr_id = monitor['id'] curr_url = monitor['url'] curr_name = monitor['name'] if 'name' in monitor else '' curr_location = monitor['monitor']['name'] if (id == curr_id) \ or (url and url == curr_url) \ or (name and name == curr_name) \ or (location and location in curr_location) \ or (pattern and pattern in curr_url): removed += 1 apiDelete('monitor/' + curr_id, self.config, expectedStatusCode=204, successMessage='Removed site monitor: ' + curr_url + ' [' + curr_id + ']', errorMessage='Failed to remove site monitor ' + curr_url + ' [' + curr_id + ']') if removed == 0: printWarn('No monitors with given pattern found: id=' + id, 'url=', url, 'name=' + name, 'location=' + location, 'pattern=' + pattern) def hasIssue(self, monitor): """Return True if the specified monitor has some issue by having a value outside of the expected threshold specified in config file""" if float(monitor['uptime_percentage']) <= float(self.config.threshold_uptime): return True if 'last_check' in monitor and 'ttfb' in monitor['last_check']: if float(monitor['last_check']['ttfb']) >= float(self.config.threshold_ttfb): return True return False def getUptime(self, siteId: str, startTimestamp: float, endTimestamp: float): """Retrieve uptime for the specified site within the specified uptime period""" # make sure all parameters are defined if not (siteId and startTimestamp > 0 and endTimestamp > 0): return None params = self.config.params() params['start'] = int(startTimestamp) params['end'] = int(endTimestamp) response_json = apiGet('monitor/' + siteId + '/uptime', 200, self.config, params=params) if response_json: if 'uptime_percentage' in response_json: return response_json else: printWarn('No uptime information available for site', siteId) return None else: return None def listUptimes(self, siteId: str, periods, dateTimeFormat: str = '%Y-%m-%d'): """Retrieve uptime for the specified site within the specified uptime periods""" table = PrettyTable(field_names=['Uptime in %', 'Period', 'Downtime', 'Events']) table.align['Uptime in %'] = 'r' table.align['Period'] = 'l' table.align['Downtime'] = 'l' table.align['Events'] = 'r' for period in periods: uptime_json = self.getUptime(siteId, period[0], period[1]) if uptime_json: startDate = datetime.fromtimestamp(float(uptime_json['start'])) endDate = datetime.fromtimestamp(float(uptime_json['end'])) uptime_percentage = float(uptime_json['uptime_percentage']) downtime_seconds = uptime_json['downtime_seconds'] events = uptime_json['events'] table.add_row(["{:.4f}%".format(uptime_percentage), formatTimespan(startDate, endDate, dateTimeFormat), formatDowntime(downtime_seconds), events]) print(table) def printHeader(self): """Print CSV header if CSV format requested""" if (self.format == 'csv'): print(self.config.delimiter.join(['ID', 'URL', 'Name', 'Code', 'Status', 'Status Message', 'Uptime %', 'Time to first Byte', 'Location'])) def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): avg_uptime = self.sum_uptime / self.num_monitors if self.sum_uptime > 0 and self.num_monitors > 0 else 0 avg_ttfb = self.sum_ttfb / self.num_monitors if self.sum_ttfb > 0 and self.num_monitors > 0 else 0 if avg_uptime <= float(self.config.threshold_uptime): uptime_percentage_text = f"{bcolors.FAIL}" + "{:.4f}".format(avg_uptime) + f"{bcolors.ENDC}" else: uptime_percentage_text = "{:.4f}".format(avg_uptime) if avg_ttfb >= float(self.config.threshold_ttfb): ttfb_text = f"{bcolors.FAIL}" + "{:.2f}".format(avg_ttfb) + f"{bcolors.ENDC}" else: ttfb_text = "{:.2f}".format(avg_ttfb) # add average row as table footer self.table.add_row(['', 'Average of ' + str(self.num_monitors) + ' monitors', '', uptime_percentage_text, ttfb_text, '']) # remove columns that should be excluded if self.config.hide_ids: self.table.del_column('ID') # Get string to be printed and create list of elements separated by \n list_of_table_lines = self.table.get_string().split('\n') # remember summary row summary_line = list_of_table_lines[-2] # remove summary row again to allow sorting and limiting self.table.del_row(len(self.table.rows)-1) if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: list_of_table_lines = self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit).split('\n') else: list_of_table_lines = self.table.get_string(sortby=sort, reversesort=reverse).split('\n') # Sorting by multiple columns could be done like this # list_of_table_lines = self.table.get_string(sortby=("Col Name 1", "Col Name 2")), reversesort=reverse).split('\n') # Print the table print('\n'.join(list_of_table_lines)) print(summary_line) print(list_of_table_lines[0]) # elif (self.format == 'csv'): # print(self.table.get_csv_string(delimiter=self.config.delimiter)) def print(self, monitor): """Print the data of the specified web monitor""" if (self.format == 'json'): print(json.dumps(monitor, indent=4)) return id = monitor['id'] url = monitor['url'] name = monitor['name'] if 'name' in monitor else '' code = monitor['code'] if 'code' in monitor else '' status = monitor['status'] if 'status' in monitor else '' status_message = monitor['status_message'] if 'status_message' in monitor else '' location = monitor['monitor']['name'] uptime_percentage = float(monitor['uptime_percentage']) if 'last_check' in monitor and 'ttfb' in monitor['last_check']: ttfb = float(monitor['last_check']['ttfb']) self.sum_uptime = self.sum_uptime + uptime_percentage self.sum_ttfb = self.sum_ttfb + ttfb self.num_monitors = self.num_monitors + 1 else: ttfb = -1 if (self.format == 'csv'): print(self.config.delimiter.join([id, url, name, str(code), status, status_message, str(uptime_percentage) + '%', str(ttfb), location])) else: if uptime_percentage <= float(self.config.threshold_uptime): uptime_percentage_text = f"{bcolors.FAIL}" + "{:.4f}".format(uptime_percentage) + f"{bcolors.ENDC}" else: uptime_percentage_text = "{:.4f}".format(uptime_percentage) if ttfb >= float(self.config.threshold_ttfb): ttfb_text = f"{bcolors.FAIL}" + "{:.2f}".format(ttfb) + f"{bcolors.ENDC}" elif ttfb != -1: ttfb_text = "{:.2f}".format(ttfb) else: ttfb_text = f"{bcolors.FAIL}n/a{bcolors.ENDC}" self.table.add_row([id, url, status_message, uptime_percentage_text, ttfb_text, location])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/sites.py
sites.py
import os import configparser from .functions import printError from .bcolors import bcolors class Config(object): def __init__(self, version: str): self.version = version self.filename = '360monitoring.ini' self.endpoint = 'https://api.monitoring360.io/v1/' self.api_key = '' self.usertoken = '' self.max_items = 5000 self.debug = False self.readonly = False self.hide_ids = False self.delimiter = ',' self.last_version_check = '' self.threshold_uptime = 99.0 self.threshold_ttfb = 1.0 self.threshold_free_diskspace = 20.0 self.threshold_cpu_usage = 80.0 self.threshold_mem_usage = 80.0 self.threshold_disk_usage = 80.0 self.loadFromFile() def headers(self): """Set headers for http requests""" if self.api_key: return { 'Authorization': 'Bearer ' + self.api_key, 'User-Agent': '360 Monitoring CLI ' + self.version, } else: printError('ERROR: No API key specified in ' + self.filename + ". Please run \"360monitoring config save --api-key YOUR_API_KEY\" to connect to your 360 Monitoring account.") return {} def params(self, tags:str = ''): """Set params for http requests""" params = { 'perpage': self.max_items, 'api_mode': 'cli_' + self.version } if tags: params['tags'] = tags return params def loadFromFile(self): """Read API endpoint and API key from config file""" if os.path.isfile(self.filename): parser = configparser.ConfigParser() parser.read(self.filename) if 'General' in parser.sections(): if 'last-version-check' in parser['General']: self.last_version_check = parser['General']['last-version-check'] if 'Connection' in parser.sections(): if 'endpoint' in parser['Connection']: self.endpoint = parser['Connection']['endpoint'] if 'api-key' in parser['Connection']: self.api_key = parser['Connection']['api-key'] if 'usertoken' in parser['Connection']: self.usertoken = parser['Connection']['usertoken'] if 'max-items' in parser['Connection']: self.max_items = parser['Connection']['max-items'] if 'hide-ids' in parser['Connection']: self.hide_ids = (parser['Connection']['hide-ids'] == 'True') if 'debug' in parser['Connection']: self.debug = (parser['Connection']['debug'] == 'True') if 'readonly' in parser['Connection']: self.readonly = (parser['Connection']['readonly'] == 'True') if 'Thresholds' in parser.sections(): if 'min-uptime-percent' in parser['Thresholds']: self.threshold_uptime = parser['Thresholds']['min-uptime-percent'] if 'max-time-to-first-byte' in parser['Thresholds']: self.threshold_ttfb = parser['Thresholds']['max-time-to-first-byte'] if 'min-free-diskspace-percent' in parser['Thresholds']: self.threshold_free_diskspace = parser['Thresholds']['min-free-diskspace-percent'] if 'max-cpu-usage-percent' in parser['Thresholds']: self.threshold_cpu_usage = parser['Thresholds']['max-cpu-usage-percent'] if 'max-mem-usage-percent' in parser['Thresholds']: self.threshold_mem_usage = parser['Thresholds']['max-mem-usage-percent'] if 'max-disk-usage-percent' in parser['Thresholds']: self.threshold_disk_usage = parser['Thresholds']['max-disk-usage-percent'] def saveToFile(self, printInfo : bool = True): """Save settings to config file""" parser = configparser.ConfigParser() parser['General'] = { 'last-version-check': self.last_version_check, } parser['Connection'] = { 'api-key': self.api_key, 'usertoken': self.usertoken, 'endpoint': self.endpoint, 'max-items': self.max_items, 'hide-ids': self.hide_ids, 'debug': self.debug, 'readonly': self.readonly, } parser['Thresholds'] = { 'min-uptime-percent': self.threshold_uptime, 'max-time-to-first-byte': self.threshold_ttfb, 'min-free-diskspace-percent': self.threshold_free_diskspace, 'max-cpu-usage-percent': self.threshold_cpu_usage, 'max-mem-usage-percent': self.threshold_mem_usage, 'max-disk-usage-percent': self.threshold_disk_usage, } with open(self.filename, 'w') as config_file: parser.write(config_file) if printInfo: print('Saved settings to', self.filename) def print(self): """Print current settings""" if os.path.isfile(self.filename): print('config file:'.ljust(30), self.filename) else: print('config file:'.ljust(30) + f"{bcolors.WARNING}" + self.filename + f" does not exist. Please run \"360monitoring config save --api-key YOUR_API_KEY\" to configure.{bcolors.ENDC}") print('CLI version:'.ljust(30), self.version) print() print('Connection') print('----------') print('endpoint:'.ljust(30), self.endpoint) if self.api_key: print('api-key:'.ljust(30), self.api_key) else: print('api-key:'.ljust(30) + f"{bcolors.FAIL}No API key specified in " + self.filename + f". Please run \"360monitoring config save --api-key YOUR_API_KEY\" to connect to your 360 Monitoring account.{bcolors.ENDC}") if self.usertoken: print('usertoken:'.ljust(30), self.usertoken) else: print('usertoken:'.ljust(30) + f"{bcolors.FAIL}No usertoken specified in " + self.filename + f". Please run \"360monitoring config save --usertoken YOUR_TOKEN\" to use it for creating magic links.{bcolors.ENDC}") print('max items:'.ljust(30), self.max_items) print('hide ids:'.ljust(30), self.hide_ids) print('debug:'.ljust(30), self.debug) print('readonly:'.ljust(30), self.readonly) print() print('Thresholds') print('----------') print('min-uptime-percent:'.ljust(30), self.threshold_uptime) print('max-time-to-first-byte:'.ljust(30), self.threshold_ttfb) print('min-free-diskspace-percent:'.ljust(30), self.threshold_free_diskspace) print('max-cpu-usage-percent:'.ljust(30), self.threshold_cpu_usage) print('max-mem-usage-percent:'.ljust(30), self.threshold_mem_usage) print('max-disk-usage-percent:'.ljust(30), self.threshold_disk_usage)
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/config.py
config.py
import json from prettytable import PrettyTable from datetime import datetime from .api import apiGet from .config import Config from .functions import printError, printWarn class ServerNotifications(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.notifications = None self.table = PrettyTable(field_names=['Start', 'End', 'Status', 'Summary']) self.table.align['Start'] = 'c' self.table.align['End'] = 'c' self.table.align['Status'] = 'c' self.table.align['Summary'] = 'l' def fetchData(self, serverId: str, startTimestamp: float, endTimestamp: float): """Retrieve a list of all alerts of a specified server in the specified time period""" # if data is already downloaded, use cached data if self.notifications != None: return True params = self.config.params() params['start'] = int(startTimestamp) params['end'] = int(endTimestamp) response_json = apiGet('server/' + serverId + '/notifications', 200, self.config, params) if response_json: if 'data' in response_json: self.notifications = response_json['data'] return True else: printWarn('No notifications found for server', serverId) self.notifications = None return False else: self.notifications = None return False def list(self, serverId: str, startTimestamp: float, endTimestamp: float, sort: str = '', reverse: bool = False, limit: int = 0): """Iterate through list of server notifications and print details""" if self.fetchData(serverId, startTimestamp, endTimestamp): # if JSON was requested and no filters, then just print it without iterating through if self.format == 'json': print(json.dumps(self.notifications, indent=4)) return # Iterate through list of servers and print data, etc. for notification in self.notifications: self.print(notification) self.printFooter(sort=sort, reverse=reverse, limit=limit) def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): # if self.config.hide_ids: # self.table.del_column('ID') if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: print(self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit)) else: print(self.table.get_string(sortby=sort, reversesort=reverse)) elif (self.format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter)) def print(self, notification): """Print the data of the specified contact""" if (self.format == 'json'): print(json.dumps(notification, indent=4)) return startTimestamp = datetime.fromtimestamp(float(notification['start'])) endTimestamp = datetime.fromtimestamp(float(notification['end'])) status = notification['status'] summary = notification['summary'] self.table.add_row([startTimestamp.strftime('%Y-%m-%d %H:%M:%S'), endTimestamp.strftime('%Y-%m-%d %H:%M:%S'), status, summary])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/servernotifications.py
servernotifications.py
import json from prettytable import PrettyTable from .api import apiGet, apiPost from .config import Config from .functions import printError, printWarn class UserTokens(object): def __init__(self, config: Config): self.config = config self.usertokens = None self.table = PrettyTable(field_names=['Token', 'Name', 'Tags']) self.table.align['Token'] = 'l' self.table.align['Name'] = 'l' self.table.align['Tags'] = 'l' def fetchData(self): """Retrieve the list of all usertokens""" # if data is already downloaded, use cached data if self.usertokens != None: return True response_json = apiGet('usertoken', 200, self.config) if response_json: if 'tokens' in response_json: self.usertokens = response_json['tokens'] return True else: printWarn('No usertokens found') self.usertokens = None return False else: self.usertokens = None return False def list(self, token: str = '', format: str = 'table'): """Iterate through list of usertokens and print details""" if self.fetchData(): if self.usertokens != None: # if JSON was requested and no filters, then just print it without iterating through if (format == 'json' and not token): print(json.dumps(self.usertokens, indent=4)) return for usertoken in self.usertokens: if token: if usertoken['token'] == token: self.print(usertoken) break else: self.print(usertoken) if (format == 'table'): print(self.table) elif (format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter)) def token(self): """Print the data of first usertoken""" if self.fetchData() and len(self.usertokens) > 0: return self.usertokens[0]['token'] def create(self, name: str = '', tags: str = ''): """Create a new usertoken""" data = { 'name': name, 'tags': tags } return apiPost('usertoken', self.config, data=data, expectedStatusCode=200, successMessage='Created usertoken', errorMessage='Failed to create usertoken') def print(self, usertoken, format: str = 'table'): """Print the data of the specified usertoken""" if (format == 'json'): print(json.dumps(usertoken, indent=4)) return token = usertoken['token'] name = usertoken['name'] if 'name' in usertoken and usertoken['name'] else '' tags = '' if 'tags' in usertoken and usertoken['tags']: for tag in usertoken['tags']: tags += ', ' + tag self.table.add_row([token, name, tags.lstrip(', ')])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/usertokens.py
usertokens.py
from prettytable import PrettyTable from .config import Config from .servers import Servers class WPToolkit(object): def __init__(self, config: Config): self.config = config self.table = PrettyTable(field_names=['ID', 'Server name', 'WP sites', 'Alive', 'Outdated', 'Outdated PHP', 'Broken']) self.table.align['ID'] = 'l' self.table.align['Server name'] = 'l' self.table.min_width['Server name'] = 24 self.table.align['WP sites'] = 'r' self.table.align['Alive'] = 'r' self.table.align['Outdated'] = 'r' self.table.align['Outdated PHP'] = 'r' self.table.align['Broken'] = 'r' self.num_servers_with_wpt = 0 self.sum_wp_sites_total = 0 self.sum_wp_sites_alive = 0 self.sum_wp_sites_outdated = 0 self.sum_wp_sites_outdated_php = 0 self.sum_wp_sites_broken = 0 def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" # add summary row as table footer self.table.add_row(['', 'Sum of ' + str(self.num_servers_with_wpt) + ' servers', self.sum_wp_sites_total, self.sum_wp_sites_alive, self.sum_wp_sites_outdated, self.sum_wp_sites_outdated_php, self.sum_wp_sites_broken]) if self.config.hide_ids: self.table.del_column('ID') # Get string to be printed and create list of elements separated by \n list_of_table_lines = self.table.get_string().split('\n') # remember summary row summary_line = list_of_table_lines[-2] # remove summary row again to allow sorting and limiting self.table.del_row(len(self.table.rows)-1) if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: list_of_table_lines = self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit).split('\n') else: list_of_table_lines = self.table.get_string(sortby=sort, reversesort=reverse).split('\n') # Sorting by multiple columns could be done like this # list_of_table_lines = self.table.get_string(sortby=("Col Name 1", "Col Name 2")), reversesort=reverse).split('\n') # Print the table print('\n'.join(list_of_table_lines)) print(summary_line) print(list_of_table_lines[0]) def print(self, format: str = 'table', issuesOnly: bool = False, sort: str = '', reverse: bool = False, limit: int = 0): """Iterate through all servers and aggregate metrics for those that have WP Toolkit installed""" servers = Servers(self.config) if servers.fetchData(): for server in servers.servers: id = server['id'] name = server['name'] last_data = server['last_data'] if last_data and 'wp-toolkit' in last_data: wpt_data = last_data['wp-toolkit'] if wpt_data: wp_sites_total = wpt_data['WordPress Websites'] wp_sites_alive = wpt_data['WordPress Websites - Alive'] wp_sites_outdated = wpt_data['WordPress Websites - Outdated'] wp_sites_outdated_php = wpt_data['WordPress Websites - Outdated PHP'] wp_sites_broken = wpt_data['WordPress Websites - Broken'] self.num_servers_with_wpt += 1 self.sum_wp_sites_total += wp_sites_total self.sum_wp_sites_alive += wp_sites_alive self.sum_wp_sites_outdated += wp_sites_outdated self.sum_wp_sites_outdated_php += wp_sites_outdated_php self.sum_wp_sites_broken += wp_sites_broken if wp_sites_outdated > 0 or wp_sites_outdated_php > 0 or wp_sites_broken > 0 or not issuesOnly: self.table.add_row([id, name, wp_sites_total, wp_sites_alive, wp_sites_outdated, wp_sites_outdated_php, wp_sites_broken]) if (format == 'table'): self.printFooter(sort=sort, reverse=reverse, limit=limit) elif (format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter))
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/wptoolkit.py
wptoolkit.py
import json from prettytable import PrettyTable from .api import apiGet from .config import Config from .functions import printError, printWarn class Nodes(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.nodes = None self.table = PrettyTable(field_names=['ID', 'Name']) self.table.align['ID'] = 'l' self.table.align['Name'] = 'l' def fetchData(self): """Retrieve the list of all nodes""" # if data is already downloaded, use cached data if self.nodes != None: return True response_json = apiGet('nodes', 200, self.config) if response_json: if 'nodes' in response_json: self.nodes = response_json['nodes'] return True else: printWarn('No nodes found') self.nodes = None return False else: self.nodes = None return False def list(self, id: str = '', name: str = '', sort: str = 'Name', reverse: bool = False, limit: int = 0): """Iterate through list of nodes and print details""" if self.fetchData(): # if JSON was requested and no filters, then just print it without iterating through if (self.format == 'json' and not (id or name or limit > 0)): print(json.dumps(self.nodes, indent=4)) return for node in self.nodes: if (id or name): if (id and 'id' in node and node['id'] == id) \ or (name and 'pretty_name' in node and name in node['pretty_name']): self.print(node) else: self.print(node) self.printFooter(sort=sort, reverse=reverse, limit=limit) def getNodeId(self, name: str): """Return Node Id for the location with the specified name. Only the first matching entry (exact match) is returned or empty string if not found""" if name and self.fetchData(): # Iterate through list of nodes and find the specified one for node in self.nodes: if name in node['pretty_name']: return node['id'] return '' def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): if self.config.hide_ids: self.table.del_column('ID') if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: print(self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit)) else: print(self.table.get_string(sortby=sort, reversesort=reverse)) elif (self.format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter)) def print(self, node): """Print the data of the specified node""" if (self.format == 'json'): print(json.dumps(node, indent=4)) return id = node['id'] name = node['pretty_name'] ''' { "pretty_name": "Nuremberg, DE", "ip": "116.203.118.7", "ipv6": "2a01:4f8:c0c:c52d::1", "lastactive": 1682624703, "password": "***********", "username": "***********", "geodata": { "latitude": 49.460983, "longitude": 11.061859 }, "id": "60e81944f401963e610a0623" } ''' self.table.add_row([id, name])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/nodes.py
nodes.py
import json from prettytable import PrettyTable from datetime import datetime from .api import apiGet from .config import Config from .functions import printError, printWarn class SiteNotifications(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.notifications = None self.table = PrettyTable(field_names=['Start', 'End', 'Status', 'Summary']) self.table.align['Start'] = 'c' self.table.align['End'] = 'c' self.table.align['Status'] = 'c' self.table.align['Summary'] = 'l' def fetchData(self, siteId: str, startTimestamp: float, endTimestamp: float): """Retrieve a list of all alerts of a specified site in the specified time period""" # if data is already downloaded, use cached data if self.notifications != None: return True params = self.config.params() params['start'] = int(startTimestamp) params['end'] = int(endTimestamp) response_json = apiGet('monitor/' + siteId + '/notifications', 200, self.config, params) if response_json: if 'data' in response_json: self.notifications = response_json['data'] return True else: printWarn('No notifications found for site', siteId) self.notifications = None return False else: self.notifications = None return False def list(self, siteId: str, startTimestamp: float, endTimestamp: float, sort: str = '', reverse: bool = False, limit: int = 0): """Iterate through list of site notifications and print details""" if self.fetchData(siteId, startTimestamp, endTimestamp): # if JSON was requested and no filters, then just print it without iterating through if self.format == 'json': print(json.dumps(self.notifications, indent=4)) return # Iterate through list of sites and print data, etc. for notification in self.notifications: self.print(notification) self.printFooter(sort=sort, reverse=reverse, limit=limit) def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): # if self.config.hide_ids: # self.table.del_column('ID') if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: print(self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit)) else: print(self.table.get_string(sortby=sort, reversesort=reverse)) elif (self.format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter)) def print(self, notification): """Print the data of the specified contact""" if (self.format == 'json'): print(json.dumps(notification, indent=4)) return startTimestamp = datetime.fromtimestamp(float(notification['start'])) endTimestamp = datetime.fromtimestamp(float(notification['end'])) status = notification['status'] summary = notification['summary'] self.table.add_row([startTimestamp.strftime('%Y-%m-%d %H:%M:%S'), endTimestamp.strftime('%Y-%m-%d %H:%M:%S'), status, summary])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/sitenotifications.py
sitenotifications.py
import json from datetime import datetime from prettytable import PrettyTable from .api import apiGet, apiPost, apiDelete from .config import Config from .functions import printError, printWarn class Incidents(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.incidents = None self.table = PrettyTable(field_names=['ID', 'Name', 'Body', 'Status', 'Timestamp']) self.table.align['ID'] = 'l' self.table.align['Name'] = 'l' self.table.align['Body'] = 'l' self.table.align['Status'] = 'c' self.table.align['Timestamp'] = 'c' def fetchData(self, page_id: str): """Retrieve the list of all incidents""" # if data is already downloaded, use cached data if self.incidents != None: return True response_json = apiGet('page/' + page_id + '/incidents', 200, self.config) if response_json: if 'incidents' in response_json: self.incidents = response_json['incidents'] return True else: printWarn('No incidents found for page', page_id) self.incidents = None return False else: self.incidents = None return False def list(self, page_id: str, id: str = '', name: str = ''): """Iterate through list of incidents and print details""" if self.fetchData(page_id): # if JSON was requested and no filters, then just print it without iterating through if (self.format == 'json'): print(json.dumps(self.incidents, indent=4)) return for incident in self.incidents: if id or name: if (id and 'id' in incident and incident['id'] == id) \ or (name and 'name' in incident and incident['name'] == name): self.print(incident) else: self.print(incident) self.printFooter() def add(self, page_id: str, name: str, body: str = ''): """Add a incident for the given name""" if page_id and name: if self.fetchData(page_id) and self.incidents: for incident in self.incidents: if incident['name'] == name and incident['body'] == body: print('Incident \'' + name + '\' already exists with this text and will not be added') return False # Make request to API endpoint data = { 'name': name, 'body': body } apiPost('page/' + page_id + '/incidents', self.config, data=data, expectedStatusCode=204, successMessage='Added incident: ' + name, errorMessage='Failed to add incident \"' + name + '\" to page \"' + page_id + '\"') def remove(self, page_id: str, id: str = '', name: str = ''): """Remove the incident for the given name""" if (id or name) and self.fetchData(page_id): for incident in self.incidents: curr_id = incident['id'] curr_name = incident['name'] curr_update_id = '' if (id and id == curr_id) \ or (name and name == curr_name): apiDelete('page/' + page_id + '/incident/' + curr_id + '/' + curr_update_id, self.config, expectedStatusCode=204, successMessage='Removed incident: ' + curr_name + ' [' + curr_id + ']', errorMessage='Failed to remove incident \"' + curr_name + '\" [' + curr_id + '] from page \"' + page_id + '\"') return printWarn('No incident with given pattern found on page \"' + page_id + '\": id=' + id, 'name=' + name) def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): if self.config.hide_ids: self.table.del_column('ID') if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: print(self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit)) else: print(self.table.get_string(sortby=sort, reversesort=reverse)) elif (self.format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter)) def print(self, incident): """Print the data of the specified incident""" if (self.format == 'json'): print(json.dumps(incident, indent=4)) return id = incident['id'] name = incident['name'] if 'name' in incident else '' body = incident['body'] if 'body' in incident else '' status = incident['status'] if 'status' in incident else '' timestamp = datetime.fromtimestamp(incident['timestamp']) if 'timestamp' in incident else '' self.table.add_row([id, name, body, status, timestamp])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/incidents.py
incidents.py
import json from prettytable import PrettyTable from .api import apiGet, apiPut from .config import Config from .functions import printError, printWarn from .bcolors import bcolors class Servers(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.servers = None self.table = PrettyTable(field_names=['ID', 'Server name', 'IP Address', 'Status', 'OS', 'CPU Usage %', 'Mem Usage %', 'Disk Usage %', 'Disk Info', 'Tags']) self.table.align['ID'] = 'l' self.table.align['Server name'] = 'l' self.table.min_width['Server name'] = 24 self.table.align['Tags'] = 'l' self.sum_cpu_usage = 0 self.sum_mem_usage = 0 self.sum_disk_usage = 0 self.num_servers = 0 def fetchData(self, tags: str = ''): """Retrieve a list of all monitored servers""" # if data is already downloaded, use cached data if self.servers != None: return True response_json = apiGet('servers', 200, self.config, self.config.params(tags)) if response_json: if 'servers' in response_json: self.servers = response_json['servers'] return True else: printWarn('No servers found for tags', tags) self.servers = None return False else: self.servers = None return False def update(self, serverId: str, tags): """Update a specific server and add specified tags to it""" data = { "tags": tags } apiPut('server/' + serverId, self.config, data=data, expectedStatusCode=200, successMessage='Updated tags of server ' + serverId + ' to ' + tags, errorMessage='Failed to update server ' + serverId) def list(self, issuesOnly: bool, sort: str, reverse: bool, limit: int, tags): """Iterate through list of server monitors and print details""" if self.fetchData(','.join(tags)): # if JSON was requested and no filters, then just print it without iterating through if (self.format == 'json' and not (issuesOnly or len(tags) > 0 or limit > 0)): print(json.dumps(self.servers, indent=4)) return self.printHeader() self.sum_cpu_usage = 0 self.sum_mem_usage = 0 self.sum_disk_usage = 0 self.num_servers = 0 # Iterate through list of servers and print data, etc. for server in self.servers: if len(tags) == 0: if (not issuesOnly) or self.hasIssue(server): self.print(server) elif 'tags' in server: match = True for tag in tags: if not tag in server['tags']: match = False break if match: if (not issuesOnly) or self.hasIssue(server): self.print(server) self.printFooter(sort=sort, reverse=reverse, limit=limit) def setTags(self, pattern: str, tags): """Set the tags for the server specified with pattern. Pattern can be either the server ID or its name""" if pattern and len(tags) > 0 and self.fetchData(): for server in self.servers: if pattern == server['id'] or pattern in server['name']: return self.update(server['id'], tags) printWarn('No server with given pattern found: ' + pattern) def getServerId(self, name: str): """Return Server Id for the server with the specified name. Only the first matching entry (exact match) is returned or empty string if not found""" if name and self.fetchData(): # Iterate through list of servers and find the specified one for server in self.servers: if server['name'] == name: return server['id'] return '' def getRecommendation(self, server): """Return recommendation text if the specified server has some issue by having a value outside of the expected threshold specified in config file""" last_data = server['last_data'] mem_usage_percent = server['summary']['mem_usage_percent'] if 'summary' in server else 0 memory_total = last_data['memory']['total'] if 'memory' in last_data else 0 if memory_total > 0 and mem_usage_percent >= float(self.config.threshold_mem_usage): memory_total_gb = memory_total / 1024 / 1024 memory_total_gb_recommended = round(memory_total_gb * 2) if (memory_total_gb_recommended % 2) != 0: memory_total_gb_recommended += 1 return 'Memory is too small for your workload. Please consider upgrading to a larger server with at least ' + str(memory_total_gb_recommended) + ' GB memory.' cpu_usage_percent = server['summary']['cpu_usage_percent'] if 'summary' in server else 0 cores = last_data['cores'] if 'cores' in last_data else 0 if cores > 0 and cpu_usage_percent >= float(self.config.threshold_cpu_usage): cores_recommended = round(cores * 2) if (cores % 2) != 0: cores += 1 return 'CPU is too small for your workload. Please consider upgrading to a larger server with at least ' + str(cores_recommended) + ' CPU cores.' disk_usage_percent = server['summary']['disk_usage_percent'] if 'summary' in server else 0 last_data = server['last_data'] if 'df' in last_data: # disk_usage_percent >= float(self.config.threshold_disk_usage) for disk in last_data['df']: mount = disk['mount'] free_disk_space = disk['free_bytes'] used_disk_space = disk['used_bytes'] total_disk_space = free_disk_space + used_disk_space free_disk_space_percent = free_disk_space / total_disk_space * 100 total_disk_space_gb = total_disk_space / 1024 / 1024 total_disk_space_gb_recommended = round(total_disk_space_gb * 2) if (total_disk_space_gb_recommended % 2) != 0: total_disk_space_gb_recommended += 1 if free_disk_space_percent <= float(self.config.threshold_free_diskspace): return 'Disk volume "' + mount + '" is almost exhausted. Please consider extending your storage volume or upgrading to a larger server with at least ' + str(total_disk_space_gb_recommended) + ' GB disk space for this volume.' return '' def hasIssue(self, server): """Return True if the specified server has some issue by having a value outside of the expected threshold specified in config file""" if self.getRecommendation(server): return True else: return False def printHeader(self): """Print CSV if CSV format requested""" if (self.format == 'csv'): print(self.config.delimiter.join(self.table.field_names)) def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): avg_cpu_usage = self.sum_cpu_usage / self.num_servers if self.sum_cpu_usage > 0 and self.num_servers > 0 else 0 avg_mem_usage = self.sum_mem_usage / self.num_servers if self.sum_mem_usage > 0 and self.num_servers > 0 else 0 avg_disk_usage = self.sum_disk_usage / self.num_servers if self.sum_disk_usage > 0 and self.num_servers > 0 else 0 if avg_cpu_usage >= float(self.config.threshold_cpu_usage): avg_cpu_usage_text = f"{bcolors.FAIL}" + "{:.1f}".format(avg_cpu_usage) + '%' + f"{bcolors.ENDC}" else: avg_cpu_usage_text = "{:.1f}".format(avg_cpu_usage) + '%' if avg_mem_usage >= float(self.config.threshold_mem_usage): avg_mem_usage_text = f"{bcolors.FAIL}" + "{:.1f}".format(avg_mem_usage) + '%' + f"{bcolors.ENDC}" else: avg_mem_usage_text = "{:.1f}".format(avg_mem_usage) + '%' if avg_disk_usage >= float(self.config.threshold_disk_usage): avg_disk_usage_text = f"{bcolors.FAIL}" + "{:.1f}".format(avg_disk_usage) + '%' + f"{bcolors.ENDC}" else: avg_disk_usage_text = "{:.1f}".format(avg_disk_usage) + '%' # add average row as table footer self.table.add_row(['', 'Average of ' + str(self.num_servers) + ' servers', '', '', '', avg_cpu_usage_text, avg_mem_usage_text, avg_disk_usage_text, '', '']) if self.config.hide_ids: self.table.del_column('ID') # Get string to be printed and create list of elements separated by \n list_of_table_lines = self.table.get_string().split('\n') # remember summary row summary_line = list_of_table_lines[-2] # remove summary row again to allow sorting and limiting self.table.del_row(len(self.table.rows)-1) if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: list_of_table_lines = self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit).split('\n') else: list_of_table_lines = self.table.get_string(sortby=sort, reversesort=reverse).split('\n') # Sorting by multiple columns could be done like this # list_of_table_lines = self.table.get_string(sortby=("Col Name 1", "Col Name 2")), reversesort=reverse).split('\n') # Print the table print('\n'.join(list_of_table_lines)) print(summary_line) print(list_of_table_lines[0]) def print(self, server): """Print the data of the specified server monitor""" if (self.format == 'json'): print(json.dumps(server, indent=4)) return id = server['id'] name = server['name'] os = server['os'] if 'os' in server else '' agent_version = server['agent_version'] if 'agent_version' in server else '' status = server['status'] if 'status' in server else '' last_data = server['last_data'] uptime_seconds = last_data['uptime']['seconds'] if 'uptime' in last_data else 0 cores = last_data['cores'] if 'cores' in last_data else 0 memory_used = last_data['memory']['used'] if 'memory' in last_data else 0 memory_free = last_data['memory']['free'] if 'memory' in last_data else 0 memory_available = last_data['memory']['available'] if 'memory' in last_data else 0 memory_total = last_data['memory']['total'] if 'memory' in last_data else 0 connecting_ip = server['connecting_ip'] if 'connecting_ip' in server else '' if 'ip_whois' in server and server['ip_whois']: ip_whois = server['ip_whois'] ip_address = ip_whois['ip'] if 'ip' in ip_whois else '' ip_country = ip_whois['country'] if 'country' in ip_whois else '' ip_hoster = ip_whois['org'] if 'org' in ip_whois else '' else: ip_address = '' ip_country = '' ip_hoster = '' cpu_usage_percent = server['summary']['cpu_usage_percent'] if 'summary' in server else 0 mem_usage_percent = server['summary']['mem_usage_percent'] if 'summary' in server else 0 disk_usage_percent = server['summary']['disk_usage_percent'] if 'summary' in server else 0 self.sum_cpu_usage = self.sum_cpu_usage + cpu_usage_percent self.sum_mem_usage = self.sum_mem_usage + mem_usage_percent self.sum_disk_usage = self.sum_disk_usage + disk_usage_percent self.num_servers = self.num_servers + 1 if cpu_usage_percent >= float(self.config.threshold_cpu_usage): cpu_usage_percent_text = f"{bcolors.FAIL}" + "{:.1f}".format(cpu_usage_percent) + '%' + f"{bcolors.ENDC}" else: cpu_usage_percent_text = "{:.1f}".format(cpu_usage_percent) + '%' if mem_usage_percent >= float(self.config.threshold_mem_usage): mem_usage_percent_text = f"{bcolors.FAIL}" + "{:.1f}".format(mem_usage_percent) + '%' + f"{bcolors.ENDC}" else: mem_usage_percent_text = "{:.1f}".format(mem_usage_percent) + '%' if disk_usage_percent >= float(self.config.threshold_disk_usage): disk_usage_percent_text = f"{bcolors.FAIL}" + "{:.1f}".format(disk_usage_percent) + '%' + f"{bcolors.ENDC}" else: disk_usage_percent_text = "{:.1f}".format(disk_usage_percent) + '%' tags = '' if 'tags' in server and server['tags']: for tag in server['tags']: if tags: tags += ', ' + tag else: tags = tag disk_info = '' if 'df' in last_data: for disk in last_data['df']: free_disk_space = disk['free_bytes'] used_disk_space = disk['used_bytes'] total_disk_space = free_disk_space + used_disk_space free_disk_space_percent = free_disk_space / total_disk_space * 100 mount = disk['mount'] # add separator if disk_info: disk_info += ', ' if free_disk_space_percent <= float(self.config.threshold_free_diskspace): disk_info += f"{bcolors.FAIL}" + "{:.0f}".format(free_disk_space_percent) + "% free on " + mount + f"{bcolors.ENDC}" else: disk_info += "{:.0f}".format(free_disk_space_percent) + "% free on " + mount if (self.format == 'csv'): print(self.config.delimiter.join([id, name, ip_address, status, os, str(cpu_usage_percent) + '%', str(mem_usage_percent) + '%', str(disk_usage_percent) + '%', disk_info, tags])) else: self.table.add_row([id, name, ip_address, status, os, cpu_usage_percent_text, mem_usage_percent_text, disk_usage_percent_text, disk_info, tags])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/servers.py
servers.py
import requests import json from .config import Config from .functions import printError def toParamString(params): s = '?' for k, v in params.items(): s += k + '=' + str(v) + '&' return s.rstrip('&') def apiGet(path: str, expectedStatusCode: int, config: Config, params: dict = None): """Do a GET request and return JSON from response if expected status code was returned""" # check if headers are correctly set for authorization if not config.headers(): return None if not params: params = config.params() if config.debug: print('GET', config.endpoint + path + toParamString(params)) # Make request to API endpoint response = requests.get(config.endpoint + path, params=params, headers=config.headers()) # Check status code of response if response.status_code == expectedStatusCode: # Return json from response return response.json() else: printError('An error occurred:', response.status_code) return None def apiPost(path: str, config: Config, params: dict = None, data: dict = None, expectedStatusCode: int = 200, successMessage: str = '', errorMessage: str = ''): """Do a POST request""" # check if headers are correctly set for authorization if not config.headers(): return False if not params: params = config.params() dataStr = json.dumps(data) if data else '' if config.debug: print('POST', config.endpoint + path + toParamString(params), dataStr) if config.readonly: return False # Make request to API endpoint response = requests.post(config.endpoint + path, data=dataStr, headers=config.headers()) # Check status code of response if response.status_code == expectedStatusCode: if successMessage: print(successMessage) return True else: if errorMessage: print(errorMessage, '(status ' + str(response.status_code) + ')') return False def apiPostJSON(path: str, config: Config, params: dict = None, data: dict = None): """Do a POST request""" # check if headers are correctly set for authorization if not config.headers(): return None if not params: params = config.params() dataStr = json.dumps(data) if data else '' if config.debug: print('POST', config.endpoint + path + toParamString(params), dataStr) if config.readonly: return None # Make request to API endpoint response = requests.post(config.endpoint + path, data=dataStr, headers=config.headers()) return response.json() def apiPut(path: str, config: Config, params: dict = None, data: dict = None, expectedStatusCode: int = 200, successMessage: str = '', errorMessage: str = ''): """Do a PUT request""" # check if headers are correctly set for authorization if not config.headers(): return False if not params: params = config.params() dataStr = json.dumps(data) if data else '' if config.debug: print('PUT', config.endpoint + path + toParamString(params), dataStr) if config.readonly: return False # Make request to API endpoint response = requests.put(config.endpoint + path, data=dataStr, headers=config.headers()) # Check status code of response if response.status_code == expectedStatusCode: if successMessage: print(successMessage) return True else: if errorMessage: print(errorMessage, '(status ' + str(response.status_code) + ')') return False def apiDelete(path: str, config: Config, params: dict = None, expectedStatusCode: int = 204, successMessage: str = '', errorMessage: str = ''): """Do a DELETE request""" # check if headers are correctly set for authorization if not config.headers(): return False if not params: params = config.params() if config.debug: print('DELETE', config.endpoint + path + toParamString(params)) if config.readonly: return False # Make request to API endpoint response = requests.delete(config.endpoint + path, headers=config.headers()) # Check status code of response if response.status_code == expectedStatusCode: if successMessage: print(successMessage) return True else: if errorMessage: print(errorMessage, '(status ' + str(response.status_code) + ')') return False
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/api.py
api.py
from prettytable import PrettyTable from .config import Config from .servers import Servers from .sites import Sites from .contacts import Contacts from .usertokens import UserTokens from .bcolors import bcolors class Statistics(object): def __init__(self, config: Config): self.config = config self.table = PrettyTable(field_names=['Value', 'Metric']) self.table.align['Value'] = 'r' self.table.align['Metric'] = 'l' def print(self, format: str = 'table'): """Iterate through all assets and print statistics""" servers = Servers(self.config) if servers.fetchData(): sum_cpu_usage = 0 sum_mem_usage = 0 sum_disk_usage = 0 num_servers = len(servers.servers) self.table.add_row([len(servers.servers), 'Servers']) for server in servers.servers: sum_cpu_usage = sum_cpu_usage + server['summary']['cpu_usage_percent'] if 'summary' in server else 0 sum_mem_usage = sum_mem_usage + server['summary']['mem_usage_percent'] if 'summary' in server else 0 sum_disk_usage = sum_disk_usage + server['summary']['disk_usage_percent'] if 'summary' in server else 0 avg_cpu_usage = sum_cpu_usage / num_servers if sum_cpu_usage > 0 and num_servers > 0 else 0 avg_mem_usage = sum_mem_usage / num_servers if sum_mem_usage > 0 and num_servers > 0 else 0 avg_disk_usage = sum_disk_usage / num_servers if sum_disk_usage > 0 and num_servers > 0 else 0 if avg_cpu_usage >= float(self.config.threshold_cpu_usage): avg_cpu_usage_text = f"{bcolors.FAIL}" + "{:.1f}".format(avg_cpu_usage) + f"{bcolors.ENDC}" else: avg_cpu_usage_text = "{:.1f}".format(avg_cpu_usage) if avg_mem_usage >= float(self.config.threshold_mem_usage): avg_mem_usage_text = f"{bcolors.FAIL}" + "{:.1f}".format(avg_mem_usage) + f"{bcolors.ENDC}" else: avg_mem_usage_text = "{:.1f}".format(avg_mem_usage) if avg_disk_usage >= float(self.config.threshold_disk_usage): avg_disk_usage_text = f"{bcolors.FAIL}" + "{:.1f}".format(avg_disk_usage) + f"{bcolors.ENDC}" else: avg_disk_usage_text = "{:.1f}".format(avg_disk_usage) self.table.add_row([avg_cpu_usage_text, '% avg cpu usage of all ' + str(num_servers) + ' servers']) self.table.add_row([avg_mem_usage_text, '% avg mem usage of all ' + str(num_servers) + ' servers']) self.table.add_row([avg_disk_usage_text, '% avg disk usage of all ' + str(num_servers) + ' servers']) sites = Sites(self.config) if sites.fetchData(): sum_uptime = 0 sum_ttfb = 0 num_monitors = len(sites.monitors) self.table.add_row([len(sites.monitors), 'Sites']) for monitor in sites.monitors: uptime_percentage = float(monitor['uptime_percentage']) if 'last_check' in monitor and 'ttfb' in monitor['last_check']: ttfb = float(monitor['last_check']['ttfb']) sum_uptime = sum_uptime + uptime_percentage sum_ttfb = sum_ttfb + ttfb avg_uptime = sum_uptime / num_monitors if sum_uptime > 0 and num_monitors > 0 else 0 avg_ttfb = sum_ttfb / num_monitors if sum_ttfb > 0 and num_monitors > 0 else 0 if avg_uptime <= float(self.config.threshold_uptime): uptime_percentage_text = f"{bcolors.FAIL}" + "{:.4f}".format(avg_uptime) + f"{bcolors.ENDC}" else: uptime_percentage_text = "{:.4f}".format(avg_uptime) if avg_ttfb >= float(self.config.threshold_ttfb): ttfb_text = f"{bcolors.FAIL}" + "{:.2f}".format(avg_ttfb) + f"{bcolors.ENDC}" else: ttfb_text = "{:.2f}".format(avg_ttfb) self.table.add_row([uptime_percentage_text, '% avg uptime of all ' + str(num_monitors) + ' sites']) self.table.add_row([ttfb_text, 'sec avg ttfb of all ' + str(num_monitors) + ' sites']) contacts = Contacts(self.config) if contacts.fetchData(): self.table.add_row([len(contacts.contacts), 'Contacts']) usertokens = UserTokens(self.config) if usertokens.fetchData(): self.table.add_row([len(usertokens.usertokens), 'User Tokens']) if (format == 'table'): print(self.table) elif (format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter))
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/statistics.py
statistics.py
import json from prettytable import PrettyTable from .api import apiGet, apiPost, apiDelete from .config import Config from .functions import printError, printWarn class Contacts(object): def __init__(self, config: Config, format: str = 'table'): self.config = config self.format = format self.contacts = None self.table = PrettyTable(field_names=['ID', 'Name', 'Email', 'Phone', 'Method']) self.table.align['ID'] = 'l' self.table.align['Name'] = 'l' self.table.align['Email'] = 'l' self.table.align['Phone'] = 'l' self.table.align['Method'] = 'c' def fetchData(self): """Retrieve the list of all contacts""" # if data is already downloaded, use cached data if self.contacts != None: return True response_json = apiGet('contacts', 200, self.config) if response_json: if 'contacts' in response_json: self.contacts = response_json['contacts'] return True else: printWarn('No contacts found') self.contacts = None return False else: self.contacts = None return False def list(self, id: str = '', name: str = '', email: str = '', phone: str = '', sort: str = '', reverse: bool = False, limit: int = 0): """Iterate through list of contacts and print details""" if self.fetchData(): # if JSON was requested and no filters, then just print it without iterating through if (self.format == 'json' and not (id or name or email or phone or limit > 0)): print(json.dumps(self.contacts, indent=4)) return for contact in self.contacts: if (id or name or email or phone): if (id and 'id' in contact and contact['id'] == id) \ or (name and 'name' in contact and contact['name'] == name) \ or (email and 'email' in contact and contact['email'] == email) \ or (phone and 'phonenumber' in contact and contact['phonenumber'] == phone): self.print(contact) else: self.print(contact) self.printFooter(sort=sort, reverse=reverse, limit=limit) def add(self, name: str, email: str = '', sms: str = ''): """Add a contact for the given name""" if name and self.fetchData(): for contact in self.contacts: if contact['name'] == name: print(name, 'already exists and will not be added') return # Make request to API endpoint data = { 'name': name, 'channels': { 'email': email, 'sms': sms } } apiPost('contacts', self.config, data=data, expectedStatusCode=200, successMessage='Added contact \"' + name + '\"', errorMessage='Failed to add contact \"' + name + '\"') def remove(self, id: str = '', name: str = '', email: str = '', phone: str = ''): """Remove the contact for the given name""" if (id or name or email or phone) and self.fetchData(): for contact in self.contacts: curr_id = contact['id'] curr_name = contact['name'] curr_email = contact['email'] if 'email' in contact else '' curr_phone = contact['phonenumber'] if 'phonenumber' in contact else '' if (id == curr_id) \ or (name and name == curr_name) \ or (email and email == curr_email) \ or (phone and phone == curr_phone): apiDelete('contact/' + curr_id, self.config, expectedStatusCode=204, successMessage='Removed contact \"' + curr_name + '\" [' + curr_id + ']', errorMessage='Failed to remove contact \"' + curr_name + '\" [' + curr_id + ']') return printWarn('No contact with given pattern found: id=' + id, 'name=' + name, 'email=' + email, 'phone=' + phone) def printFooter(self, sort: str = '', reverse: bool = False, limit: int = 0): """Print table if table format requested""" if (self.format == 'table'): if self.config.hide_ids: self.table.del_column('ID') if sort: # if sort contains the column index instead of the column name, get the column name instead if sort.isdecimal(): sort = self.table.get_csv_string().split(',')[int(sort) - 1] else: sort = None if limit > 0: print(self.table.get_string(sortby=sort, reversesort=reverse, start=0, end=limit)) else: print(self.table.get_string(sortby=sort, reversesort=reverse)) elif (self.format == 'csv'): print(self.table.get_csv_string(delimiter=self.config.delimiter)) def print(self, contact): """Print the data of the specified contact""" if (self.format == 'json'): print(json.dumps(contact, indent=4)) return id = contact['id'] name = contact['name'] email = contact['email'] if 'email' in contact else '' phone = contact['phonenumber'] if 'phonenumber' in contact else '' method = contact['method'] if 'method' in contact else '' self.table.add_row([id, name, email, phone, method])
360monitoringcli
/360monitoringcli-1.0.19-py3-none-any.whl/cli360monitoring/lib/contacts.py
contacts.py
import requests import json import pandas as pd import datetime from IPython.display import clear_output import time from sqlalchemy import create_engine from sqlalchemy.exc import IntegrityError from cryptography.fernet import Fernet import pymysql import random import math from sendgrid.helpers.mail import Mail from sendgrid import SendGridAPIClient """# Tata Tele API""" class tata: def call_records(tata_auth_token,from_date="",to_date="",page="",limit=100,agents="",department="",call_type="",callerid="",destination="",direction="",duration="",operator="",services=""): url = "https://api-cloudphone.tatateleservices.com/v1/call/records" params = { "from_date":from_date, "to_date":to_date, "page":page, "limit":limit, "agents":agents, "department":department, "call_type":call_type, "callerid":callerid, "destination":destination, "direction":direction, "duration":duration, "operator":operator, "services":services } payload={} headers = { 'Accept': 'application/json', 'Authorization': tata_auth_token } response = requests.request("GET", url, headers=headers, data=payload, params=params) res = json.loads(response.text) return res """# SAFFRONSTAYS ``` sql_query(query,cypher_key) sql_query_destructive(query,cypher_key) ss_calendar(listing_ids,check_in,check_out) ss_fb_catalogue() ``` """ def db_connection(cypher_key,database="main"): key = bytes(cypher_key,'utf-8') cipher_suite = Fernet(key) if database=="main": host_enc = b'gAAAAABgU5NFdPLwUewW-ljzzPKpURLo9mMKzOkClVvpWYotYRT6DsmgNlHYUKP8X3m_c12kAUqSrLw4KTlujTPly2F-R-CFrw==' user_enc = b'gAAAAABf-DB2YcOMC7JvsL-GihLJcImh6DvJpt1hNZFetiCzxMacK4agYHkyl3W1mnRkHNmEnecp4mMPZRfqO6bsLP1qgrpWbA==' pass_enc = b'gAAAAABf-DCFqT2kj-ExcdPn2IW0m0-M_3piK2-w1xNpUvH21XDsz3iqixvrT-NxKnpf1wirp0NcYoQEGt4TKpYHJzXcrXy6TA==' database_enc = b'gAAAAABfQPr48Sej-V7GarivuF4bsfBgP9rldzD500gl174HK4LZy70VfEob-kbaOBFa8rhuio_PbCFj4Nt3nJzVjKqC83d1NA==' elif database=="vista": host_enc = b'gAAAAABfQPr4eF5i5aU4vfC4RieOdLr9GjwQPWWmvTWT728cK-qUoPesPZmLKwE4vTkhh3oxCmREfrHN1omRwmxJJuo_CS4cMmRKG8_mLFIBQG1mg2Kx102PixJAdf1l74dhO6VI8ZCR' user_enc = b'gAAAAABfQPr4PssChqSwFRHAGwKGCrKRLvnjRqfBkrazUydFvX3RBNAr5zAvKxdGJtaemdjq3uRwk1kgY4tLpIO9CxXj_JdC0w==' pass_enc = b'gAAAAABfQPr4iwH0c5pxjI4XfV-uT-pBt9tKfQgFJEfjTcTIjwipeN4tI_bG-TtHoamosKEuFOldevYPi-3usIj1ZDSrb-zsXg==' database_enc = b'gAAAAABgU5oarKoMuMj5EYPHf59SSfalqJ1_vtsGjbk4Gepefkr5dhTnZg1KVSmt6Rln02B5SOJf-N9dzbA6Q47uJbZ-xNrJdQ==' elif database=="dev": host_enc = b'gAAAAABgU5RRIJqGSTQhaupb_rwblmtCTjl6Id6fa1JMsZQac6i9eaUtoBoglK92yuSCGiTaIadtjrwxmK5VMS2cM6Po-SWMpQ==' user_enc = b'gAAAAABgU5QmKmvNsS7TC2tz66e3S40CSiNF8418N6ANGFn6D_RhP8fd4iQRML3uk9WnDlDAtYHpGjstwgpKH8YJ347xZHQawA==' pass_enc = b'gAAAAABgU5Rf1piAvyT_p5LRd0YJheFT2Z9W75R4b2MUA1o1-O4Vn2Xw7R-1bWLx4EhYUrRZ6_ajI8DCgLVULZZdVSWxG6OvCw==' database_enc = b'gAAAAABgU5SLKYwupyp_nrcSzGYcwDkkKKxGjmvEpULZV2MmKGDgXCefa2WvINUBrCCmBeyt9GcpzBQQSE9QN8azsDSItdTa5Q==' else: raise ValueError("Invalid Database, pick either of the 3 - ('main','dev','vista')") myServer = cipher_suite.decrypt(host_enc).decode("utf-8") myUser = cipher_suite.decrypt(user_enc).decode("utf-8") myPwd = cipher_suite.decrypt(pass_enc).decode("utf-8") db = cipher_suite.decrypt(database_enc).decode("utf-8") myConnection = pymysql.connect(host=myServer,user=myUser,password=myPwd,db=db) return myConnection # SQL query on the SS database (ONLY SELECT) - returns a dataframe def sql_query(query,cypher_key): myConnection = db_connection(cypher_key,database="main") if query.split(' ')[0] != 'SELECT': print("Error. Please only use non destructive (SELECT) queries.") return "Please only use non destructive (SELECT) queries." response_df = pd.io.sql.read_sql(query, con=myConnection) myConnection.close() return response_df # to execute destructive queries def sql_query_destructive(query,cypher_key): con = db_connection(cypher_key,database="main") try: with con.cursor() as cur: cur.execute(query) con.commit() finally: con.close() class dev: def sql_query(query,cypher_key): myConnection = db_connection(cypher_key,database="dev") response_df = pd.io.sql.read_sql(query, con=myConnection) myConnection.close() return response_df def sql_query_destructive(query,cypher_key): con = db_connection(cypher_key,database="dev") try: with con.cursor() as cur: cur.execute(query) con.commit() finally: con.close() class aws: def sql_query(query,cypher_key): myConnection = db_connection(cypher_key,database="main") if query.split(' ')[0] != 'SELECT': print("Error. Please only use non destructive (SELECT) queries.") return "Please only use non destructive (SELECT) queries." response_df = pd.io.sql.read_sql(query, con=myConnection) myConnection.close() return response_df # to execute destructive queries def sql_query_destructive(query,cypher_key): con = db_connection(cypher_key,database="main") try: with con.cursor() as cur: cur.execute(query) con.commit() finally: con.close() # Get the status for all the dates for a list of homes def ss_calendar(listing_ids,check_in,check_out): parsed_listing_ids = str(listing_ids)[1:-1] parsed_listing_ids = parsed_listing_ids.replace("'","").replace(" ","") url = "https://www.saffronstays.com/calender_node.php" params={ "listingList": parsed_listing_ids, "checkIn":check_in, "checkOut":check_out } payload = {} headers= {} response = requests.get(url, headers=headers, data = payload,params=params) response = json.loads(response.text.encode('utf8')) return response # SS Facebook catalogue (a list of currently live listings) def ss_fb_catalogue(): url = "https://www.saffronstays.com/items_catalogue.php" response = requests.get(url) response_data = response.text.encode('utf8') csv_endpoint = str(response_data).split('`')[1] csv_download_url = "https://www.saffronstays.com/"+csv_endpoint ss_data = pd.read_csv(csv_download_url) return ss_data # list of emails and preheader names, update with yours def sendgrid_email(TEMPLATE_ID,EMAILS,api_key,PAYLOAD={}): """ Send a dynamic email to a list of email addresses :returns API response code :raises Exception e: raises an exception """ # create Mail object and populate message = Mail( from_email=('book@saffronstays.com','SaffronStays'), to_emails=EMAILS ) # pass custom values for our HTML placeholders message.dynamic_template_data = PAYLOAD message.template_id = TEMPLATE_ID # create our sendgrid client object, pass it our key, then send and return our response objects try: sg = SendGridAPIClient(api_key) response = sg.send(message) code, body, headers = response.status_code, response.body, response.headers print(f"Response code: {code}") print(f"Response headers: {headers}") print(f"Response body: {body}") print("Dynamic Messages Sent!") return str(response.status_code) except Exception as e: print("Error: {0}".format(e)) return "Error: {0}".format(e) """# Vista ``` # Vista API Wrappers # Refining the APIs # Dataframes # SQL ``` """ # Return list of all locations def vista_locations(): locations = ["lonavala, maharashtra", "goa, goa", "alibaug, maharashtra", "nainital, uttarakhand", "dehradun", "uttarakhand", "chail, himanchal-pradesh", "manali, himachal-pradesh", "shimla, himanchal%20pradesh", "ooty, tamil%20nadu", "coorg, karnataka", "dehradun, uttarakhand", "jaipur, rajasthan", "udaipur, rajasthan", "mahabaleshwar, maharashtra", "nashik, maharashtra", "gangtok, sikkim", "gurgaon, haryana", "vadodara, gujarat", "kashmir, jammu", ] return locations # Wrapper on the search API def vista_search_api(search_type='city',location="lonavala,%20maharashtra",checkin="",checkout="",guests=2,adults=2,childs=0,page_no=1): url = "https://searchapi.vistarooms.com/api/search/getresults" param={ } payload = { "city": location, "search_type": "city", "checkin": checkin, "checkout": checkout, "total_guests": guests, "adults": adults, "childs": childs, "page": page_no, "min_bedrooms": 1, "max_bedrooms": 30, "amenity": [], "facilities": [], "price_start": 1000, "price_end": 5000000, "sort_by_price": "" } headers = {} response = requests.post(url, params=param, headers=headers, data=payload) search_data = json.loads(response.text.encode('utf8')) return search_data # Wrapper on the listing API def vista_listing_api(slug='the-boulevard-villa',guests=2,checkin=datetime.date.today()+datetime.timedelta(1), checkout=datetime.date.today()+datetime.timedelta(2), guest=3,adult=3,child=0): url = "https://v3api.vistarooms.com/api/single-property" param={ 'slug': slug, 'checkin': checkin, 'checkout': checkout, 'guest': guest, 'adult': adult, 'child': child } payload = {} headers = { } response = requests.get(url, params=param, headers=headers, data = payload) property_deets = json.loads(response.text.encode('utf8')) return property_deets # Wrapper on the listing extra details API def vista_listing_other_details_api(id=107): url = "https://v3api.vistarooms.com/api/single-property-detail" param={ 'id': id, } payload = {} headers = { } response = requests.get(url, params=param, headers=headers, data = payload) property_other_deets = json.loads(response.text.encode('utf8')) return property_other_deets # Wrapper on the price calculator def vista_price_calculator_api(property_id='710', checkin=datetime.date.today()+datetime.timedelta(1), checkout = datetime.date.today()+datetime.timedelta(2), guest = 2, adult = 2, child = 0): if type(checkin)==str: checkin = datetime.datetime.strptime(checkin,'%Y-%m-%d') checkout = datetime.datetime.strptime(checkout,'%Y-%m-%d') url = "https://v3api.vistarooms.com/api/price-breakup" param={ 'property_id': property_id, 'checkin': checkin, 'checkout': checkout, 'guest': guest, 'adult': adult, 'child': child, } payload = {} headers = { } response = requests.get(url, params=param, headers=headers, data = payload) pricing_deets = json.loads(response.text.encode('utf8')) return pricing_deets # Wrapper on the avalability (Blocked dates) def vista_availability_api(property_id=119): url = "https://v3api.vistarooms.com/api/calendar/property/availability" params={ "property_id":property_id } payload = {} headers = { } response = requests.get(url, headers=headers, data = payload, params=params) calendar = json.loads(response.text.encode('utf8')) return calendar # Gives a json response for basic listing data for the list of locations def vista_search_locations_json(locations=["lonavala,%20maharashtra"],guests=2,get_all=False,wait_time=10): # Empty list to append (extend) all the data properties = [] if get_all: locations = vista_locations() # Outer loop - for each location for location in locations: try: page_no = 1 # Inner Loop - for each page in location ( acc to the Vista Search API ) while True: clear_output(wait=True) print(f"Page {page_no} for {location.split('%20')[0]} ") # Vista API call (search) search_data = vista_search_api(location=location,guests=guests,page_no=page_no) # Break when you reach the last page for a location if not 'data' in search_data.keys(): break if not search_data['data']['properties']: break properties.extend(search_data['data']['properties']) page_no += 1 time.sleep(wait_time) except: pass return properties # Retruns a DATAFRAME for the above functions & **DROPS DUPLICATES (always use this for analysis) def vista_search_locations(locations=["lonavala,%20maharashtra"],guests=2,get_all=False,wait_time=10): villas = vista_search_locations_json(locations=locations, guests=guests,get_all=get_all,wait_time=wait_time) villas = pd.DataFrame(villas) villas = villas.drop_duplicates('id') return villas # Returns a JSON with the listing details def vista_listing(slug='the-boulevard-villa',guests=2,checkin=datetime.date.today()+datetime.timedelta(1), checkout=datetime.date.today()+datetime.timedelta(2)): print("Fetching ",slug) # Vista API call (listing) property_deets = vista_listing_api(slug=slug,guests=guests,checkin=checkin, checkout=checkout) # Get lat and long (diff API call) lat_long = vista_listing_other_details_api(property_deets['data']['property_detail']['id'])['data']['location'] # Get pricing for various durations weekday_pricing = vista_price_calculator(property_deets['data']['property_detail']['id'],checkin=next_weekday(),checkout=next_weekday()+datetime.timedelta(1)) weekend_pricing = vista_price_calculator(property_deets['data']['property_detail']['id'],checkin=next_weekday(5),checkout=next_weekday(5)+datetime.timedelta(1)) entire_week_pricing = vista_price_calculator(property_deets['data']['property_detail']['id'],checkin=next_weekday(),checkout=next_weekday()+datetime.timedelta(7)) entire_month_pricing = vista_price_calculator(property_deets['data']['property_detail']['id'],checkin=next_weekday(),checkout=next_weekday()+datetime.timedelta(30)) # Add the extra fields in response (JSON) property_deets['data']['slug'] = slug property_deets['data']['lat'] = lat_long['latitude'] property_deets['data']['lon'] = lat_long['longitude'] property_deets['data']['checkin_date'] = checkin property_deets['data']['checkout_date'] = checkout property_deets['data']['weekday_pricing'] = weekday_pricing property_deets['data']['weekend_pricing'] = weekend_pricing property_deets['data']['entire_week_pricing'] = entire_week_pricing property_deets['data']['entire_month_pricing'] = entire_month_pricing property_deets['data']['price_per_room'] = property_deets['data']['price']['amount_to_be_paid']/property_deets['data']['property_detail']['number_of_rooms'] return property_deets['data'] # Calculates the price for a duration (if unavailable, will automatically look for the next available dates) % Recursive function def vista_price_calculator(property_id, checkin=datetime.date.today()+datetime.timedelta(1), checkout = datetime.date.today()+datetime.timedelta(2), guest = 2, adult = 2, child = 0, depth=0): date_diff = (checkout-checkin).days # Set the exit condition for the recursion depth ( to avoid an endless recursion -> slowing down the scripts ) if date_diff < 7: depth_lim = 15 next_hop = 7 elif date_diff >= 7 and date_diff < 29: depth_lim = 7 next_hop = 7 else: depth_lim = 5 next_hop = date_diff if depth==depth_lim: return f"Villa Probably Inactive, checked till {checkin}" if type(checkin)==str: checkin = datetime.datetime.strptime(checkin,'%Y-%m-%d') checkout = datetime.datetime.strptime(checkout,'%Y-%m-%d') # Vista API call (Calculation) pricing = vista_price_calculator_api(property_id=property_id, checkin=checkin, checkout=checkout, guest=guest, adult=adult, child=child) if 'error' in pricing.keys(): # Recursion condition (Call self with next dates in case the dates are not available) if pricing['error'] == 'Booking Not Available for these dates': next_checkin = checkin + datetime.timedelta(next_hop) next_chekout = checkout + datetime.timedelta(next_hop) next_pricing = vista_price_calculator(property_id,checkin=next_checkin ,checkout=next_chekout,depth=depth+1) return next_pricing # For other errors (Like invalid listing ID) else: return pricing['error'] return next_pricing else: return pricing['data']['price'] # Uses a list of slugs to generate a master DATAFRAME , this contains literally everything, ideal for any analysis on Vista def vista_master_dataframe(slugs=(['vista-greenwoods-five-villa','maison-calme-villa','vista-greenwoods-four-villa','mehta-mansion','villa-maira'])): total_slugs = len(slugs) temp_progress_counter = 0 villas_deets = [] for slug in slugs: try: villa_deets = vista_listing(slug=slug) villas_deets.append(villa_deets) villas_df = pd.DataFrame(villas_deets) temp_progress_counter += 1 clear_output(wait=True) print("Done ",int((temp_progress_counter/total_slugs)*100),"%") except: pass prop_detail_df = pd.DataFrame(list(villas_df['property_detail'])) agent_details_df = pd.DataFrame(list(villas_df['agent_details'])) price_df = pd.DataFrame(list(villas_df['price'])) literally_all_deets = pd.concat([prop_detail_df,villas_df,price_df,agent_details_df], axis=1) literally_all_deets = literally_all_deets.drop(['property_detail','mini_gallery', 'base_url', 'agent_details', 'house_rule_pdf', 'mini_gallery_text', 'seo','number_extra_guest', 'additionalcost', 'days', 'min_occupancy', 'max_occupancy', 'amount_to_be_paid','total_guest', 'extra_adult', 'extra_child', 'extra_adult_cost', 'extra_child_cost', 'per_person','price','checkin_date','checkout_date','total_price','agent_short_words'], axis = 1) literally_all_deets['amenities'] = [[amenity['name'] for amenity in amenities] for amenities in literally_all_deets['amenities']] literally_all_deets['weekday_pricing_value'] = [wkdpr if type(wkdpr)==str else wkdpr['amount_to_be_paid'] for wkdpr in literally_all_deets['weekday_pricing']] literally_all_deets['weekend_pricing_value'] = [wkdpr if type(wkdpr)==str else wkdpr['amount_to_be_paid'] for wkdpr in literally_all_deets['weekend_pricing']] literally_all_deets['entire_week_pricing_value'] = [wkdpr if type(wkdpr)==str else wkdpr['amount_to_be_paid'] for wkdpr in literally_all_deets['entire_week_pricing']] literally_all_deets['entire_month_pricing_value'] = [wkdpr if type(wkdpr)==str else wkdpr['amount_to_be_paid'] for wkdpr in literally_all_deets['entire_month_pricing']] return literally_all_deets # Takes 2 lists of listings (Old and New) and only responds with the Dataframe of the newly added listings def added_villas_dataframe(old_slugs,new_slugs): added_slugs = list(set(new_slugs).difference(set(old_slugs))) added_villas = [] if added_slugs: added_villas = vista_master_dataframe(added_slugs) return added_villas # Non Desctructive SQL QUERY - Try "SELECT * FROM VISTA_MASTER" def vista_sql_query(query,cypher_key): # Returns a daframe object of the query response myConnection = db_connection(cypher_key,database="vista") response_df = pd.io.sql.read_sql(query, con=myConnection) myConnection.close() return response_df # DESTRCUTIVE sql query def vista_sql_destructive(query,cypher_key): con = db_connection(cypher_key,database="vista") try: with con.cursor() as cur: cur.execute(query) con.commit() finally: con.close() def vista_weekly_update_script(cypher_key,search_api_wait=10): # Get the list of all the current villas lited vista_search_data = vista_search_locations(get_all=True,wait_time=search_api_wait) new_slugs = vista_search_data['slug'].values query = "SELECT slug FROM VISTA_MASTER" old_slugs = vista_sql_query(query,cypher_key) old_slugs = old_slugs['slug'].values # Get the list of recently added and removed slugs added_slugs = list(set(new_slugs).difference(set(old_slugs))) removed_slugs = list(set(old_slugs).difference(set(new_slugs))) # Add the new listings to the Database vista_newly_added_df = added_villas_dataframe(old_slugs,new_slugs) vista_current_columns = vista_sql_query("SELECT * FROM VISTA_MASTER LIMIT 2",cypher_key).columns dropcols = set(vista_newly_added_df).difference(set(vista_current_columns)) try: vista_newly_added_df.drop(dropcols,axis=1,inplace=True) except: pass if len(vista_newly_added_df) > 0: vista_newly_added_df['listing_status'] = "LISTED" vista_newly_added_df['status_on'] = datetime.datetime.today() vista_newly_added_df['created_on'] = datetime.datetime.today() # changind all the "Object" data types to str (to avoid some weird error in SQL) all_object_types = pd.DataFrame(vista_newly_added_df.dtypes) all_object_types = all_object_types[all_object_types[0]=='object'].index for column in all_object_types: vista_newly_added_df[column] = vista_newly_added_df[column].astype('str') #return vista_newly_added_df engine = db_connection(cypher_key,database="vista") for i in range(len(vista_newly_added_df)): try: vista_newly_added_df.iloc[i:i+1].to_sql(name='VISTA_MASTER',if_exists='append',con = engine,index=False) except IntegrityError: pass engine.dispose() # Update listing Statuses vista_update_listing_status(cypher_key) # A Summary of the updates final_success_response = { "No of Added Villas" : len(added_slugs), "No of Removed Villas" : len(removed_slugs), "Added Villas" : added_slugs, "Removed Villas" : removed_slugs } return final_success_response # Update listing status def vista_update_listing_status(cypher_key): get_ids_query ="SELECT id,listing_status FROM VISTA_MASTER" vista_data = vista_sql_query(get_ids_query,cypher_key) for id in vista_data[vista_data['listing_status']=='DELISTED']['id']: stat = vista_check_if_listed(id) print(id,stat) if stat: print("Updating database...") query = "UPDATE VISTA_MASTER SET listing_status='LISTED',status_on='"+str(datetime.datetime.today())+"'WHERE id='"+str(id)+"'" vista_sql_destructive(query,cypher_key) for id in vista_data[vista_data['listing_status']=='LISTED']['id']: stat = vista_check_if_listed(id) print(id,stat) if not stat: print("Updating database...") query = "UPDATE VISTA_MASTER SET listing_status='DELISTED',status_on='"+str(datetime.datetime.today())+"'WHERE id='"+str(id)+"'" vista_sql_destructive(query,cypher_key) # Breadth first seach algorithm to get the blocked dates def vista_blocked_dates(property_id,ci,co): # check if the listing is active lt_status = vista_check_status(property_id) if lt_status in ["INACTIVE","DELISTED"]: return { "id" : property_id, "blocked_dates" : lt_status } # rg = Range => checkout - checkin (in days) rg = (datetime.datetime.strptime(co, "%Y-%m-%d") - datetime.datetime.strptime(ci, "%Y-%m-%d")).days api_calls = 0 # This list contains all the date ranges to be checked - there will be additions and subtractions to this list DTE = [(ci,co,rg)] # we will add the blocekd dates here blocked = {} explored = [] while len(DTE) != 0: # To see how many API calls happened (fewer the better) api_calls += 1 # Pick one item (date range) from the DTE list -> to see if it is available dates = DTE.pop() print(f"Checking : {dates[0]} for {dates[2]} days") explored.append(dates) checkin = dates[0] checkout = dates[1] range = dates[2] # Call the vista API to see of this is available api_response = vista_price_calculator_api(property_id=property_id,checkin=checkin,checkout=checkout) # If no error -> it is available, start the next iteration of the loop if "error" not in api_response.keys(): print("Not Blocked") continue # if the range is unavailable do this else: print("Blocked") # if the range is 1, mark the date as blocked if range == 1: blocked[checkin] = api_response['data']['price']['amount_to_be_paid'] #blocked.append((checkin,api_response['data']['price']['amount_to_be_paid'])) # if the range is not 1, split the range in half and add both these ranges to the DTE list else: checkin_t = datetime.datetime.strptime(checkin, "%Y-%m-%d") checkout_t = datetime.datetime.strptime(checkout, "%Y-%m-%d") middle_date = checkin_t + datetime.timedelta(math.ceil(range/2)) first_half = ( str(checkin_t)[:10] , str(middle_date)[:10] , (middle_date - checkin_t).days ) second_half = ( str(middle_date)[:10] , str(checkout_t)[:10] , (checkout_t - middle_date).days) DTE.extend([first_half,second_half]) response_obj = { "id" : property_id, "blocked_dates" : blocked, "meta_data": { "total_blocked_dates" : len(blocked), "api_calls":api_calls, "checked from": ci, "checked till":co #"date_ranges_checked":explored } } return response_obj # To check if the villa is inactive (Listed but blocked for all dates) def vista_check_status(property_id="",slug=""): if vista_check_if_listed(property_id,slug): status = "LISTED" else: status = "DELISTED" return status if status == "LISTED": min_nights = 1 for i in [8,16,32,64,128]: price = vista_price_calculator_api(property_id , checkin=datetime.date.today()+datetime.timedelta(i), checkout = datetime.date.today()+datetime.timedelta(i + min_nights)) if "error" not in price.keys(): return "LISTED" if i == 128: return "INACTIVE" elif price['error'] == 'Booking Not Available for these dates': pass elif isinstance(price['error'].split(" ")[4],int): min_nights = price['error'].split(" ")[4] pass def vista_check_if_listed(property_id="",slug=""): if len(slug)>0: try: listing = vista_listing_api(slug) property_id = listing['data']['property_detail']['id'] except: return False price = vista_price_calculator_api(property_id , checkin=datetime.date.today()+datetime.timedelta(5), checkout = datetime.date.today()+datetime.timedelta(7)) if "error" not in price.keys(): return True elif isinstance(price['error'],str): return True elif 'property_id' in dict(price['error']).keys(): return False return False # Update listing status def vista_update_listing_status_old(cypher_key): get_ids_query ="SELECT id,listing_status FROM VISTA_MASTER" vista_data = vista_sql_query(get_ids_query,cypher_key) for id in vista_data[vista_data['listing_status']=='DELISTED']['id']: print(id) stat = vista_check_status(id) print(id,stat) if stat in ["LISTED","INACTIVE"]: print("Updating database...") query = "UPDATE VISTA_MASTER SET listing_status='"+stat+"',status_on='"+str(datetime.datetime.today())+"'WHERE id='"+str(id)+"'" vista_sql_destructive(query,cypher_key) for id in vista_data[vista_data['listing_status']=='LISTED']['id']: stat = vista_check_status(id) print(id,stat) if stat in ["DELISTED","INACTIVE"]: print("Updating database...") query = "UPDATE VISTA_MASTER SET listing_status='"+stat+"',status_on='"+str(datetime.datetime.today())+"'WHERE id='"+str(id)+"'" vista_sql_destructive(query,cypher_key) for id in vista_data[vista_data['listing_status']=='INACTIVE']['id']: stat = vista_check_status(id) print(id,stat) if stat in ["DELISTED","LISTED"]: print("Updating database...") query = "UPDATE VISTA_MASTER SET listing_status='"+stat+"',status_on='"+str(datetime.datetime.today())+"'WHERE id='"+str(id)+"'" vista_sql_destructive(query,cypher_key) def vista_update_listing_status(cypher_key): get_ids_query ="SELECT id,listing_status FROM VISTA_MASTER" vista_data = vista_sql_query(get_ids_query,cypher_key) for i,r in vista_data.iterrows(): try: old_status = r['listing_status'] cal = vista_availability_api(r['id']) if "error" in cal.keys(): current_status = "DELISTED" else: cal = pd.DataFrame(cal['data']) cal['date'] = cal['date'].astype('datetime64') if len(cal[cal['date']< datetime.datetime.today() + datetime.timedelta(90)])/88 > 1: current_status = "INACTIVE" else: current_status = "LISTED" if old_status != current_status: print(f"Updating database for {r['id']} - {current_status}...") query = f"UPDATE VISTA_MASTER SET listing_status='{current_status}',status_on='{str(datetime.datetime.today())}' WHERE id='{r['id']}'" #print(query) vista_sql_destructive(query,cypher_key) else: print(r['id'], "Unchanged") except: pass """# Lohono ``` # Lohono API wrappers # Refining the APIs # Master DataFrame ``` """ # List of all lohono locations def lohono_locations(): locations = ['india-alibaug','india-goa','india-lonavala','india-karjat'] return locations # lohono Search API wrapper def lohono_search_api(location_slug="india-goa",page=1): url = "https://www.lohono.com/api/property" params = { 'location_slug': location_slug, 'page': page } payload = {} headers = { 'authority': 'www.lohono.com', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'accept': 'application/json', 'user-agent': mock_user_agent(), 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': f'https://www.lohono.com/villas/india/{ location_slug.split("-")[-1] }', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8' } response = requests.get(url, headers=headers, data = payload, params=params) search_data = json.loads(response.text.encode('utf8')) return search_data # lohono listing API wrapper def lohono_listing_api(slug='prop-villa-magnolia-p5sp'): url = f"https://www.lohono.com/api/property/{slug}" payload = {} headers = { 'authority': 'www.lohono.com', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'accept': 'application/json', 'user-agent': mock_user_agent(), 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'https://www.lohono.com/villas/india/goa/prop-fonteira-vaddo-a-C6Cn', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8' } response = requests.get(url, headers=headers, data = payload) listing_data = json.loads(response.text.encode('utf8')) return listing_data['response'] # lohono Pricing API wrapper def lohono_pricing_api(slug,checkin,checkout,adult=2,child=0): url = f"https://www.lohono.com/api/property/{slug}/price" payload = "{\"property_slug\":\""+slug+"\",\"checkin_date\":\""+str(checkin)+"\",\"checkout_date\":\""+str(checkout)+"\",\"adult_count\":"+str(adult)+",\"child_count\":"+str(child)+",\"coupon_code\":\"\",\"price_package\":\"\",\"isEH\":false}" headers = { 'authority': 'www.lohono.com', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'accept': 'application/json', 'user-agent': mock_user_agent(), 'content-type': 'application/json', 'origin': 'https://www.lohono.com', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': f'https://www.lohono.com/villas/india/goa/{slug}?checkout_date={checkout}&adult_count={adult}&checkin_date={checkin}', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } response = requests.post(url, headers=headers, data = payload) pricing_data = json.loads(response.text.encode('utf8')) return pricing_data # Basic details from the search API def lohono_search(location_slugs=lohono_locations()): page = 1 all_properties = [] for location_slug in location_slugs: while True: print(f"page{ page } for {location_slug}") search_response = lohono_search_api(location_slug,page) all_properties.extend(search_response['response']['properties']) if search_response['paginate']['total_pages'] == page: break page += 1 return pd.DataFrame(all_properties) # All details for all the listings def lohono_master_dataframe(): search_data = lohono_search() slugs = search_data['property_slug'].values all_properties = [] for slug in slugs: print(f"getting {slug}") listing_raw = lohono_listing_api(slug) all_properties.append(listing_raw) all_properties = pd.DataFrame(all_properties) all_properties['amenities'] = [[amenity['name'] for amenity in amenities] for amenities in all_properties['amenities']] all_properties['price'] = search_data['rate'] all_properties['search_name'] = search_data['name'] return all_properties """# AirBnb""" airbnb_home_types = ['Entire home apt','Hotel room','Private room', 'Shared room'] airbnb_imp_amenities = [5,4,16,7,9,12] # AC, Wifi , Breakfast, Parking, Pool, Pets (Not in order) # Airbnb Search API def airbnb_search_api(place_id = "ChIJRYHfiwkB6DsRWIbipWBKa2k", city = "", state = "", min_price = 4000, max_price=50000, min_bedrooms=1, home_type=airbnb_home_types, items_per_grid = 50, amenities = [], items_offset = 0): home_type = [item.replace(" ","%20") for item in home_type] home_type = ["Entire%20home%2Fapt" if x=="Entire%20home%20apt" else x for x in home_type] home_type_filter = "%22%2C%22".join(home_type) amenities = [str(item) for item in amenities] amenities_filter = "%2C".join(amenities) url = f"https://www.airbnb.co.in/api/v3/ExploreSearch?locale=en-IN&operationName=ExploreSearch&currency=INR&variables=%7B%22request%22%3A%7B%22metadataOnly%22%3Afalse%2C%22version%22%3A%221.7.8%22%2C%22itemsPerGrid%22%3A{items_per_grid}%2C%22tabId%22%3A%22home_tab%22%2C%22refinementPaths%22%3A%5B%22%2Fhomes%22%5D%2C%22source%22%3A%22structured_search_input_header%22%2C%22searchType%22%3A%22filter_change%22%2C%22mapToggle%22%3Afalse%2C%22roomTypes%22%3A%5B%22{home_type_filter}%22%5D%2C%22priceMin%22%3A{min_price}%2C%22priceMax%22%3A{max_price}%2C%22placeId%22%3A%22{place_id}%22%2C%22itemsOffset%22%3A{items_offset}%2C%22minBedrooms%22%3A{min_bedrooms}%2C%22amenities%22%3A%5B{amenities_filter}%5D%2C%22query%22%3A%22{city}%2C%20{state}%22%2C%22cdnCacheSafe%22%3Afalse%2C%22simpleSearchTreatment%22%3A%22simple_search_only%22%2C%22treatmentFlags%22%3A%5B%22simple_search_1_1%22%2C%22oe_big_search%22%5D%2C%22screenSize%22%3A%22large%22%7D%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22274161d4ce0dbf360c201612651d5d8f080d23820ce74da388aed7f9e3b00c7f%22%7D%7D" #url = f"https://www.airbnb.co.in/api/v3/ExploreSearch?locale=en-IN&operationName=ExploreSearch&currency=INR&variables=%7B%22request%22%3A%7B%22metadataOnly%22%3Afalse%2C%22version%22%3A%221.7.8%22%2C%22itemsPerGrid%22%3A20%2C%22roomTypes%22%3A%5B%22Entire%20home%2Fapt%22%5D%2C%22minBedrooms%22%3A0%2C%22source%22%3A%22structured_search_input_header%22%2C%22searchType%22%3A%22pagination%22%2C%22tabId%22%3A%22home_tab%22%2C%22mapToggle%22%3Afalse%2C%22refinementPaths%22%3A%5B%22%2Fhomes%22%5D%2C%22ib%22%3Atrue%2C%22amenities%22%3A%5B4%2C5%2C7%2C9%2C12%2C16%5D%2C%22federatedSearchSessionId%22%3A%22e597713a-7e46-4d10-88e7-3a2a9f15dc8d%22%2C%22placeId%22%3A%22ChIJM6uk0Jz75zsRT1nlkg6PwiQ%22%2C%22itemsOffset%22%3A20%2C%22sectionOffset%22%3A2%2C%22query%22%3A%22Karjat%2C%20Maharashtra%22%2C%22cdnCacheSafe%22%3Afalse%2C%22simpleSearchTreatment%22%3A%22simple_search_only%22%2C%22treatmentFlags%22%3A%5B%22simple_search_1_1%22%2C%22oe_big_search%22%5D%2C%22screenSize%22%3A%22large%22%7D%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22274161d4ce0dbf360c201612651d5d8f080d23820ce74da388aed7f9e3b00c7f%22%7D%7D" payload = {} headers = { 'authority': 'www.airbnb.co.in', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'device-memory': '4', 'x-airbnb-graphql-platform-client': 'apollo-niobe', #'x-csrf-token': 'V4$.airbnb.co.in$lHdA3kStJv0$yEvcPM_C6eeUUHkQuYEdGFWrZreA5ui1e4A-pMzDFI=', 'x-airbnb-api-key': 'd306zoyjsyarp7ifhu67rjxn52tv0t20', 'x-csrf-without-token': '4', 'user-agent': mock_user_agent(), 'viewport-width': '1600', 'content-type': 'application/json', 'accept': '*/*', 'dpr': '1', 'ect': '4g', 'x-airbnb-graphql-platform': 'web', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', # 'referer': f'https://www.airbnb.co.in/s/{city}--{state}/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&adults=2&source=structured_search_input_header&search_type=filter_change&map_toggle=false&room_types%5B%5D=Entire%20home%2Fapt&price_min=4221&place_id={place_id}', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', } response = requests.get(url, headers=headers, data = payload) #response = json.loads(response.text.encode('utf8')) return response # Airbnb Calendar API def airbnb_calendar_api(listing_id,start_month=9,start_year=2020,bev='1600684519_NDg5ZGY1ZDQ4YjNk',month_count=4): url = f"https://www.airbnb.co.in/api/v3/PdpAvailabilityCalendar?operationName=PdpAvailabilityCalendar&locale=en-IN&currency=INR&variables=%7B%22request%22%3A%7B%22count%22%3A{month_count}%2C%22listingId%22%3A%22{listing_id}%22%2C%22month%22%3A{start_month}%2C%22year%22%3A{start_year}%7D%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22b94ab2c7e743e30b3d0bc92981a55fff22a05b20bcc9bcc25ca075cc95b42aac%22%7D%7D" payload = {} headers = { 'authority': 'www.airbnb.co.in', #'pragma': 'no-cache', #'cache-control': 'no-cache', #'device-memory': '8', 'x-airbnb-graphql-platform-client': 'minimalist-niobe', #'x-csrf-token': 'V4$.airbnb.co.in$lHdA3kStJv0$yEvcPMB_C6eeUUHkQuYEdGFWrZreA5ui1e4A-pMzDFI=', 'x-airbnb-api-key': 'd306zoyjsyarp7ifhu67rjxn52tv0t20', #'x-csrf-without-token': '1', 'user-agent': mock_user_agent(), 'viewport-width': '1600', 'content-type': 'application/json', 'accept': '*/*', 'dpr': '1', 'ect': '4g', 'x-airbnb-graphql-platform': 'web', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': f'https://www.airbnb.co.in/rooms/{listing_id}?adults=2&source_impression_id=p3_1598719581_vge1qn5YJ%2FXWgUKg&check_in=2020-10-01&guests=1', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', 'cookie': f'bev={bev};' } response = requests.request("GET", url, headers=headers, data = payload) response = json.loads(response.text.encode('utf8')) return response #Airbnb search DataFrame def airbnb_search(place_ids = ["ChIJRYHfiwkB6DsRWIbipWBKa2k"], max_iters = 5, min_price=4000,max_price=200000, home_type=[],amenities=[], min_bedrooms=1 ): all_items = [] for place_id in place_ids: counter = 1 offset = 0 while counter<=max_iters: print(f"Round {counter} for {place_id}") counter+=1 response = airbnb_search_api(place_id = place_id, min_price = min_price ,max_price=max_price, min_bedrooms=min_bedrooms,home_type=home_type,amenities=amenities, items_offset = offset) offset += 50 if not response['data']['dora']['exploreV3']['sections']: break else: for sections in response['data']['dora']['exploreV3']['sections']: if 'listing' in sections['items'][0].keys(): all_items.extend(sections['items']) items_df = pd.DataFrame([item['listing'] for item in all_items]) prices_df = pd.DataFrame([item['pricingQuote'] for item in all_items]) items_df[['canInstantBook','weeklyPriceFactor','monthlyPriceFactor','priceDropDisclaimer','priceString','rateType']] = prices_df[['canInstantBook','weeklyPriceFactor','monthlyPriceFactor','priceDropDisclaimer','priceString','rateType']] return_obj = items_df[['id','name','roomAndPropertyType','reviews','avgRating','starRating','reviewsCount','amenityIds','previewAmenityNames','bathrooms','bedrooms','city','lat','lng','personCapacity','publicAddress','pictureUrl','pictureUrls','isHostHighlyRated','isNewListing','isSuperhost','canInstantBook','weeklyPriceFactor','monthlyPriceFactor','priceDropDisclaimer','priceString','rateType']] return_obj = return_obj.drop_duplicates('id') return return_obj # Airbnb Calendar DataFrame def airbnb_calendar(listing_id,start_month=datetime.datetime.today().month,start_year=datetime.datetime.today().year): api_response = airbnb_calendar_api(listing_id,start_month,start_year) all_months = [month['days'] for month in api_response['data']['merlin']['pdpAvailabilityCalendar']['calendarMonths']] all_days=[] for month in all_months: all_days.extend(month) all_days = pd.DataFrame(all_days) all_days['price'] = [item['localPriceFormatted'][1:].replace(",","") for item in all_days['price'].values] all_days['calendarDate'] = pd.to_datetime(all_days['calendarDate']) all_days['listing_id'] = listing_id all_days = all_days.astype({'price':'int32'}) return all_days # Get Occupancy data for a listing id def airbnb_occupancy(listing_id): clndr = airbnb_calendar(listing_id=listing_id,start_month=datetime.datetime.today().month,start_year=datetime.datetime.today().year) clndr = clndr.set_index('calendarDate') clndr_monthly = clndr.groupby(pd.Grouper(freq='M')).mean() clndr_monthly['month-year'] = [str(item.month_name())+" "+str(item.year) for item in clndr_monthly.index] clndr_monthly = clndr_monthly.set_index('month-year') clndr_monthly['occupancy'] = 1-clndr_monthly['available'] occupancy = clndr_monthly['occupancy'].to_json() available = clndr[clndr['available']==True].index blocked = clndr[clndr['available']==False].index available = [str(item.date()) for item in available] blocked = [str(item.date()) for item in blocked] return_obj = { "listing_id": listing_id, "monthly_occupancy" : occupancy, "blocked_dates" : blocked, "available_dates": available } return return_obj """# Helper Functions ``` next_weekday() mock_user_agent() mock_proxy() earth_distance(lat1,lon1,lat2,lon2) ``` """ # Get the next weekday ( 0=monday , 1 = tuesday ... ) def next_weekday(weekday=0, d=datetime.date.today()): days_ahead = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 return d + datetime.timedelta(days_ahead) # default - next monday # gives a random user-agent to use in the API call def mock_user_agent(): users = ["Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41", "Opera/9.80 (Macintosh; Intel Mac OS X; U; en) Presto/2.2.15 Version/10.00", "Opera/9.60 (Windows NT 6.0; U; en) Presto/2.1.1", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1", "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"] return users[random.randint(0,7)] # Gives a 'proxies' object for a 'requests' call def mock_proxy(): proxies_list = ["45.72.30.159:80", "45.130.255.156:80", "193.8.127.117:80", "45.130.255.147:80", "193.8.215.243:80", "45.130.125.157:80", "45.130.255.140:80", "45.130.255.198:80", "185.164.56.221:80", "45.136.231.226:80"] proxy = proxies_list[random.randint(0,9)] proxies = { "http": proxy, "https": proxy } return proxies # Arial distance between 2 pairs of coordinates def earth_distance(lat1,lon1,lat2,lon2): # Radius of the earth R = 6373.0 lat1 = math.radians(lat1) lon1 = math.radians(lon1) lat2 = math.radians(lat2) lon2 = math.radians(lon2) dlon = lon2 - lon1 dlat = lat2 - lat1 #Haversine formula a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) distance = R * c return distance def to_fancy_date(date): tmstmp = pd.to_datetime(date) day = tmstmp.day if 4 <= day <= 20 or 24 <= day <= 30: suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] return f"{tmstmp.day}{suffix} {tmstmp.month_name()} {tmstmp.year}" """# TEST""" def final_test(): ss_latest() vista_latest() vista_locations() vista_search_locations_json(locations=["nainital, uttarakhand"],guests=2,get_all=False) vista_search_locations(locations=["nainital, uttarakhand"],guests=2,get_all=False) vista_listing(slug='the-boulevard-villa',guests=2,checkin=datetime.date.today()+datetime.timedelta(1), checkout=datetime.date.today()+datetime.timedelta(2)) vista_listing_other_details_api(slug='the-boulevard-villa') vista_price_calculator(property_id='310', checkin=datetime.date.today()+datetime.timedelta(1), checkout = datetime.date.today()+datetime.timedelta(2), guest = 2, adult = 2, child = 0) next_weekday(weekday=0, d=datetime.date.today()) vista_master_dataframe(slugs=(['vista-greenwoods-five-villa','maison-calme-villa','vista-greenwoods-four-villa','mehta-mansion','villa-maira'])) vista_map_all() ss_map_all() ss_vs_vista() return "All Good :)"
3636c788d0392f7e84453434eea18c59
/3636c788d0392f7e84453434eea18c59-4.3.1.tar.gz/3636c788d0392f7e84453434eea18c59-4.3.1/sstools/__init__.py
__init__.py
# System from typing import Optional, List, Union, Tuple from datetime import datetime import json, os, shutil # Pip from ksimpleapi import Api from simple_multiprocessing import MultiProcess, Task # Local from .models import Sport, Game, GameAssets from ._cache_utils import _CacheUtils # ---------------------------------------------------------------------------------------------------------------------------------------- # # ----------------------------------------------------------- class: 365Scores ----------------------------------------------------------- # class Scores(Api): # -------------------------------------------------------- Public methods -------------------------------------------------------- # def get_games( self, sports: Optional[Union[List[Union[Sport, int]], Union[Sport, int]]] = None, competition_ids: Optional[Union[List[int], int]] = None, start_date: Optional[Union[int, datetime, str]] = None, # 03/01/2021 end_date: Optional[Union[int, str]] = None, # 03/01/2021 only_major_games: bool = False, only_live_games: bool = False, included_status_groups: List[int] = [1, 2, 3, 4], include_cancelled: bool = False, include_postponed: bool = False ) -> Optional[List[Game]]: if sports and type(sports) != list: sports = [sports] try: res = self._get( 'https://webws.365scores.com/web/games/allscores', params={ 'appTypeId': 5, 'langId': 1, 'startDate': self.__normalized_date(start_date), 'endDate': self.__normalized_date(end_date), 'onlyMajorGames': 'true' if only_major_games else None, 'onlyLiveGames': 'true' if only_live_games else None, 'sports': ','.join([sport.value if type(sport) == Sport else sport for sport in sports]) if sports else None, 'competitionIds': ','.join(competition_ids) if competition_ids else None } ).json() games = [] for game_json in res['games']: try: sport_id = game_json['sportId'] competition_id = game_json['competitionId'] competition_dict = [competition_dict for competition_dict in res['competitions'] if competition_dict['id'] == competition_id][0] home_competitor_country_id = game_json['homeCompetitor']['countryId'] away_competitor_country_id = game_json['awayCompetitor']['countryId'] game = Game( game_json, sport_dict=[sport_dict for sport_dict in res['sports'] if sport_dict['id'] == sport_id][0], competition_dict=competition_dict, competition_country_dict=[country_dict for country_dict in res['countries'] if country_dict['id'] == competition_dict['countryId']][0], home_competitor_country_dict=[country_dict for country_dict in res['countries'] if country_dict['id'] == home_competitor_country_id][0], away_competitor_country_dict=[country_dict for country_dict in res['countries'] if country_dict['id'] == away_competitor_country_id][0] ) if ( (not included_status_groups or game.status_group in included_status_groups) and (include_cancelled or not game.cancelled) and (include_postponed or not game.postponed) and (not only_live_games or game.live) ): games.append(game) except Exception as e: if self.debug: print(e, json.dumps(game_json, indent=4)) return games except Exception as e: if self.debug: print(e) return None def download_assets( self, game: Game, competition_image_path: Optional[str] = None, home_competitor_image_path: Optional[str] = None, away_competitor_image_path: Optional[str] = None, image_folder_path: Optional[str] = None, round_images: bool = True, request_timeout: float = 5, use_cache: bool = True ) -> GameAssets: if image_folder_path: os.makedirs(image_folder_path, exist_ok=True) def get_image( image_url: str, image_path: Optional[str] = None, image_folder_path: Optional[str] = None, round_image: bool = True, request_timeout: float = 5, use_cache: bool = True ) -> Tuple[str, bool]: downloaded_image_path = _CacheUtils.temp_download_image_path_for_url(image_url, image_path, image_folder_path, use_cache) final_download_image_path = _CacheUtils.final_download_image_path_for_url(image_url, image_path, image_folder_path) if not os.path.exists(downloaded_image_path) and not self._download(image_url, downloaded_image_path, timeout=request_timeout): return final_download_image_path, False if not downloaded_image_path == final_download_image_path: shutil.copy2(downloaded_image_path, final_download_image_path) return final_download_image_path, True _kwargs = { 'image_folder_path': image_folder_path, 'round_image': round_images, 'request_timeout': request_timeout, 'use_cache': use_cache } competition_image_url = game.competition.get_image_url(round=round_images) home_competitor_image_url = game.home_competitor.get_image_url(round=round_images) away_competitor_image_url = game.away_competitor.get_image_url(round=round_images) (competition_image_path, _), (home_competitor_image_path, _), (away_competitor_image_path, _) = MultiProcess([ Task(get_image, competition_image_url, competition_image_path, **_kwargs), Task(get_image, home_competitor_image_url, home_competitor_image_path, **_kwargs), Task(get_image, away_competitor_image_url, away_competitor_image_path, **_kwargs) ]).solve() return GameAssets( competition_image_url, competition_image_path, home_competitor_image_url, home_competitor_image_path, away_competitor_image_url, away_competitor_image_path ) # ------------------------------------------------------- Private methods -------------------------------------------------------- # def __normalized_date( self, date: Optional[Union[int, datetime, str]] ) -> Optional[str]: if not date: return None if type(date) == int: date = datetime.fromtimestamp(date) if type(date) == datetime: date = '{}/{}/{}'.format(str(date.day).zfill(2), str(date.month).zfill(2), date.year()) return date # ---------------------------------------------------------------------------------------------------------------------------------------- #
365scores
/365scores-1.0.7-py3-none-any.whl/scores/scores.py
scores.py
# System from typing import Optional import os # Pip from kcu import kpath # ---------------------------------------------------------------------------------------------------------------------------------------- # # ---------------------------------------------------------- class: _CacheUtils ---------------------------------------------------------- # class _CacheUtils: # -------------------------------------------------------- Public methods -------------------------------------------------------- # @classmethod def images_cache_path(cls) -> str: return kpath.new_tempdir( path_src=cls.cache_path(), appending_subpath='images', append_random_subfolder_path=False, create_folder_if_not_exists=True ) @staticmethod def cache_path() -> str: return kpath.new_tempdir( appending_subpath='py_365scores_cache', append_random_subfolder_path=False, create_folder_if_not_exists=True ) @classmethod def final_download_image_path_for_url( cls, image_url: str, image_path: Optional[str] = None, image_folder_path: Optional[str] = None ) -> str: if image_path: return image_path return os.path.join(image_folder_path or cls.images_cache_path(), cls.image_name_for_url(image_url)) @classmethod def temp_download_image_path_for_url( cls, image_url: str, image_path: Optional[str] = None, image_folder_path: Optional[str] = None, use_cache: bool = True ) -> str: if image_path: return image_path return os.path.join( image_folder_path if not use_cache and image_folder_path else cls.images_cache_path(), cls.image_name_for_url(image_url) ) @classmethod def image_name_for_url( cls, image_url: str ) -> str: return '{}.png'.format(cls.image_id_for_url(image_url)) @staticmethod def image_id_for_url(image_url: str) -> str: # https://imagecache.365scores.com/image/upload/d_Countries:Round:153.png/Competitors/67096 base = image_url.split('d_Countries:')[-1].replace('.png', '').lower() # round:153/competitors/67096 # 153/competitors/67096 is_round = 'round' in base if is_round: base = base.replace('round:', '') # 153/competitors/67096 country_id, type, id = base.split('/') return '{}-country_id_{}-id_{}{}'.format(type, country_id, id, '-round' if is_round else '') # ---------------------------------------------------------------------------------------------------------------------------------------- #
365scores
/365scores-1.0.7-py3-none-any.whl/scores/_cache_utils.py
_cache_utils.py
# System import datetime # Local from .base import Sport, Country, BaseIdable from .game_competitor import GameCompetitor from .competition import Competition # ---------------------------------------------------------------------------------------------------------------------------------------- # # ------------------------------------------------------------- class: Game -------------------------------------------------------------- # class Game(BaseIdable): # ------------------------------------------------------------- Init ------------------------------------------------------------- # def __init__( self, d: dict, sport_dict: dict, competition_dict: dict, competition_country_dict: dict, home_competitor_country_dict: dict, away_competitor_country_dict: dict ): super().__init__(d) sport = Sport(sport_dict) self.competition = Competition(competition_dict, sport_or_sport_dict=sport, country_or_country_dict=competition_country_dict) self.home_competitor = GameCompetitor(d['homeCompetitor'], sport_or_sport_dict=sport, country_or_country_dict=home_competitor_country_dict) self.away_competitor = GameCompetitor(d['awayCompetitor'], sport_or_sport_dict=sport, country_or_country_dict=away_competitor_country_dict) self.season_num = self._d_val(d, 'seasonNum') self.stage_num = self._d_val(d, 'stageNum') self.group_num = self._d_val(d, 'groupNum') self.round_num = self._d_val(d, 'roundNum') self.competition_display_name = self._d_val(d, 'competitionDisplayName') self.status_group = d['statusGroup'] self.status_text = d['statusText'] self.short_status_text = d['shortStatusText'] self.start_time_str = d['startTime'] self.start_time_date = datetime.datetime.strptime(self.start_time_str.split('+')[0], '%Y-%m-%dT%H:%M:%S') self.start_time_ts = self.start_time_date.timestamp() self.just_ended = d['justEnded'] self.live = self.status_group == 3 self.postponed = self.status_group == 4 and self.status_text.lower() == 'postponed' self.cancelled = self.status_group == 4 and not self.postponed and self.status_text.lower() == 'cancelled' self.scheduled = self.status_group == 2 and not self.postponed and not self.cancelled and self.status_text.lower() == 'scheduled' self.game_time = d['gameTime'] self.game_time_display = self._d_val(d, 'gameTimeDisplay', '') self.game_time_and_status_display_type = d['gameTimeAndStatusDisplayType'] self.has_tv_networks = d['hasTVNetworks'] self.has_lineups = self._d_val(d, 'hasLineups', False) self.has_field_positions = self._d_val(d, 'hasFieldPositions', False) self.has_missing_players = self._d_val(d, 'hasMissingPlayers', False) self.score = (self.home_competitor.score, self.away_competitor.score) self.aggregated_score = (self.home_competitor.aggregated_score, self.away_competitor.aggregated_score) self.has_score = self.score != (-1, -1) self.has_aggregated_score = self.aggregated_score != (-1, -1) # ------------------------------------------------------- Public properties ------------------------------------------------------ # @property def sport(self) -> Sport: return self.competition.sport @property def country(self) -> Country: return self.competition.country # ---------------------------------------------------------------------------------------------------------------------------------------- #
365scores
/365scores-1.0.7-py3-none-any.whl/scores/models/game.py
game.py
# System from typing import Union from abc import abstractmethod # Local from .core import BaseObject, SportType from .sport import Sport from .country import Country # ---------------------------------------------------------------------------------------------------------------------------------------- # # ------------------------------------------------------ class: BaseCompetingObject ------------------------------------------------------ # class BaseCompetingObject(BaseObject): # ------------------------------------------------------------- Init ------------------------------------------------------------- # def __init__( self, d: dict, sport_or_sport_dict: Union[Sport, dict], country_or_country_dict: Union[Country, dict] ): super().__init__(d) self.sport = sport_or_sport_dict if isinstance(sport_or_sport_dict, Sport) else Sport(sport_or_sport_dict) self.country = country_or_country_dict if isinstance(country_or_country_dict, Country) else Country(country_or_country_dict) self.popularity_rank = d['popularityRank'] self.image_url = self.get_image_url(round=False) self.image_url_round = self.get_image_url(round=True) self.long_name = self._d_val(d, 'longName') self.short_name = self._d_val(d, 'shortName') # ------------------------------------------------------- Abstract methods ------------------------------------------------------- # @abstractmethod def _image_url_key(self) -> str: pass # ------------------------------------------------------- Public properties ------------------------------------------------------ # @property def sport_id(self) -> int: return self.sport.id @property def sport_type(self) -> SportType: return SportType(self.sport_id) @property def country_id(self) -> int: return self.country.id # -------------------------------------------------------- Public methods -------------------------------------------------------- # def get_name(self) -> str: return self.long_name or self.name def get_image_url( self, round: bool = False ) -> str: return 'https://imagecache.365scores.com/image/upload/d_Countries{}:{}.png/{}/{}'.format( ':Round' if round else '', self.country_id, self._image_url_key(), self.id ) # ---------------------------------------------------------------------------------------------------------------------------------------- #
365scores
/365scores-1.0.7-py3-none-any.whl/scores/models/base/base_competing_object.py
base_competing_object.py
import os import sys import inflection from app.commons.generate.generate_code_service import GenerateFileService args = sys.argv if __name__ == "__main__": """ 数据库注释格式约定:第一行:名称+特殊字符(空格等)+其他注释信息 第二行:约定关键字 数据库注释关键字 编辑类型关键字:("input", "text", "radio", "checkbox", "select", "date", "datetime") 条件查询关键字:("==", "!=", "llike", "rlike", "like", "between") 条件查询排序关键字:("asc", "desc") 字段查询关键字:("get_by", "gets_by") 下拉类型:全大写字符串 """ # table_name = "tests" table_name = args[1] table_name = table_name[table_name.find("=") + 1:] gen_file = args[2] gen_file = gen_file[gen_file.find("=") + 1:] gfs = GenerateFileService(table_name=table_name) dao_str = gfs.get_dao_string() service_str = gfs.get_service_string() handler_str = gfs.get_handler_string() list_page_str = gfs.get_list_page_string() add_edit_page_str = gfs.get_add_edit_page_string() detail_page_str = gfs.get_detail_page_string() dao_file_path = os.path.join(os.path.dirname(__file__), u"templates") current_path = os.path.dirname(__file__) app_path = current_path[:current_path.find("commons/")] sing_table_name = inflection.singularize(table_name) if gen_file == "dao" or not gen_file or gen_file == "all": dao_file_name = sing_table_name + "_dao.py" dao_file_path = os.path.join(app_path, u"daos/" + dao_file_name) f = open(dao_file_path, 'w') f.write(dao_str) print dao_file_path if gen_file == "service" or not gen_file or gen_file == "all": service_file_name = sing_table_name + "_service.py" service_file_path = os.path.join(app_path, u"services/" + service_file_name) f = open(service_file_path, 'w') f.write(service_str) print service_file_path if gen_file == "handler" or not gen_file or gen_file == "all": handler_file_name = sing_table_name + ".py" handler_file_path = os.path.join(app_path, u"handlers/" + handler_file_name) f = open(handler_file_path, 'w') f.write(handler_str) print handler_file_path if not os.path.exists(os.path.join(app_path, u"views/" + sing_table_name)): os.mkdir(os.path.join(app_path, u"views/" + sing_table_name)) if gen_file == "list" or not gen_file or gen_file == "all": list_page_file_name = table_name + ".html" list_page_file_path = os.path.join(app_path, u"views/" + sing_table_name + "/" + list_page_file_name) f = open(list_page_file_path, 'w') f.write(list_page_str) print list_page_file_path if gen_file == "add" or not gen_file or gen_file == "all": add_edit_page_file_name = sing_table_name + ".html" add_edit_page_file_path = os.path.join(app_path, u"views/" + sing_table_name + "/" + add_edit_page_file_name) f = open(add_edit_page_file_path, 'w') f.write(add_edit_page_str) print add_edit_page_file_path if gen_file == "detail" or not gen_file or gen_file == "all": detail_page_file_name = sing_table_name + "_detail.html" detail_page_file_path = os.path.join(app_path, u"views/" + sing_table_name + "/" + detail_page_file_name) f = open(detail_page_file_path, 'w') f.write(detail_page_str) print detail_page_file_path print gfs.get_route_string()
36ban_commons
/36ban_commons-0.0.1.tar.gz/36ban_commons-0.0.1/generate/application.py
application.py
import MySQLdb import getpass import os import platform import re import time import inflection from tornado.template import Template, Loader import yaml from configs.settings import Settings __author__ = 'wangshubin' class MyLoader(Loader): """ 不对空格进行过滤,保留文件的原始格式 原Loader对html,js进行了空格过滤,破坏了原始的文件格式 """ def _create_template(self, name): path = os.path.join(self.root, name) with open(path, "rb") as f: my_template = Template(f.read(), name=name, loader=self, compress_whitespace=False) return my_template class MyTemplate(object): @staticmethod def get_template_string(template_path, template_file_name, namespace): loader = MyLoader(template_path) t = loader.load(template_file_name) return t.generate(**namespace) class DBMessage(object): """ 获取数据库相关信息类 """ runmod = "development" database_config = None def __init__(self, config_name=None): self.conn = self.get_conn(config_name) def get_conn(self, config_name=None): """获取数据库连接,当前使用的是MySql数据库,如果更换数据库,新建子类,重写该方法即可 :param config_name: :return: """ if config_name is None: config_name = "default" if not self.database_config: file_stream = file(os.path.join(Settings.SITE_ROOT_PATH, 'configs/databases.yaml'), 'r') yml = yaml.load(file_stream) databases_config = yml.get(self.runmod) config = databases_config[config_name] url = config["url"] # sqlA的连接字符串,要截取mysqlDB所要的信息 self.database_config = dict() self.database_config["user"] = url[16:url.rindex(":")] self.database_config["passwd"] = url[url.rindex(":") + 1:url.rindex("@")] self.database_config["host"] = url[url.rindex("@") + 1:url.rindex("/")] self.database_config["database"] = url[url.rindex("/") + 1:url.rindex("?")] self.database_config["charset"] = url[url.rindex("charset=") + 8:] else: pass # 建立和数据库系统的连接 conn = MySQLdb.connect(host=self.database_config["host"], user=self.database_config["user"], passwd=self.database_config["passwd"], charset=self.database_config["charset"]) conn.select_db("information_schema") return conn def get_schema_names(self): """获取所有数据库名 获取数据库连接,当前使用的是MySql数据库,如果更换数据库,新建子类,重写该方法即可 :return: """ cursor = self.conn.cursor() # 执行SQL 获取所有字段信息 cursor.execute("SELECT DISTINCT table_schema FROM columns ") row = cursor.fetchall() schema_names = list() ignore_names = ("information_schema", "mysql") for (table_schema,) in row: if table_schema not in ignore_names: schema_names.append(table_schema) return tuple(schema_names) def get_table_names(self, table_schema): """获取数据库中所有表名 获取数据库连接,当前使用的是MySql数据库,如果更换数据库,新建子类,重写该方法即可 :param table_schema: :return: """ cursor = self.conn.cursor() # 执行SQL 获取所有字段信息 cursor.execute("SELECT DISTINCT table_name FROM columns WHERE table_schema='" + table_schema + "'") row = cursor.fetchall() table_names = list() for (table_name,) in row: table_names.append(table_name) return tuple(table_names) def get_columns(self, table_name): """根据表名,获取数据库字段信息 获取数据库连接,当前使用的是MySql数据库,如果更换数据库,新建子类,重写该方法即可 :return: 所有的字段信息 """ cursor = self.conn.cursor() # 执行SQL 获取所有字段信息 cursor.execute(""" SELECT column_name, column_default, is_nullable, data_type, column_type, column_comment FROM columns WHERE table_schema='""" + self.database_config["database"] + """' AND table_name = '""" + table_name + """' """) row = cursor.fetchall() method_keys = self.get_where_types() order_by_keys = ("asc", "desc") edit_keys = self.get_edit_types() columns = list() for (column_name, column_default, is_nullable, data_type, column_type, column_comment) in row: column_length = self.get_column_length(column_type) sql_a_type = self.get_sql_a_type(data_type) column_title = self.get_first_word(column_comment) col_msg = dict() col_msg["column_name"] = column_name # 字段 col_msg["column_title"] = column_title # 字段对应的中文 默认为column_comment中截取;用于生成页面 col_msg["column_comment"] = "" # 数据库中的备注,用于生成title .py文件中的注释等 col_msg["data_type"] = data_type # sql类型 col_msg["column_default"] = column_default # 默认值 col_msg["is_nullable"] = is_nullable # 是否为空 col_msg["column_length"] = column_length # 字段长度 col_msg["sql_a_type"] = sql_a_type # 对应的sqlA类型 col_msg["condition_search"] = False # 是否参与条件查询 及 参与条件查询类型 where条件 col_msg["order_by"] = False # 是否参与排序 及 排序方式 col_msg["edit_type"] = self.get_sql_edit_type(data_type) # 编辑类型 默认数据库类型 或 input col_msg["option_type"] = None # 下拉类型 大写字符串 col_msg["gets_by"] = False # 按字段查询所有 col_msg["get_by"] = False # 按字段查询第一个 # file_path="" # service handler view 子文件夹 这个应该在表注释中 好像没有表注释 通过命令参数形式给出吧 if column_comment: comments = column_comment.split("\n") col_msg["column_comment"] = comments[0] # 数据库中的备注,用于生成title .py文件中的注释等 if len(comments) > 1: # 存在第二行的配置 config_str = comments[1] configs = config_str.split(" ") for conf in configs: if conf in method_keys: col_msg["condition_search"] = conf if conf in order_by_keys: col_msg["order_by"] = conf if conf in edit_keys: col_msg["edit_type"] = conf if conf.isupper(): col_msg["option_type"] = conf if conf == "get_by": col_msg["get_by"] = True if conf == "gets_by": col_msg["gets_by"] = True columns.append(col_msg) return columns def get_namespace(self, table_name, ext_namespace=None): """获取到文件魔板所需的变量 :return: """ columns = self.get_columns(table_name) singular_table_name = inflection.singularize(table_name) model_name = self.get_model_name(table_name) sys_user_name = self.get_sys_user_name() created_at = time.strftime('%Y-%m-%d %H:%M:%S') sql_a_types = self.get_all_sql_a_type(columns) mixins = self.get_all_mixin(columns) condition_search_columns = list() get_by_columns = list() gets_by_columns = list() order_by_columns = list() for col in columns: if col["condition_search"]: condition_search_columns.append(col) if col["get_by"]: get_by_columns.append(col) if col["gets_by"]: gets_by_columns.append(col) if col["order_by"]: order_by_columns.append(col) namespace = dict(model_name=model_name, # sqlA 映射对象名, 用于生成类名等 table_name=table_name, # 表名(复数形式) 可以用户列表的变量命名 singular_table_name=singular_table_name, # 表名的单数形式 可用于单数实例的命名 sys_user_name=sys_user_name, # 系统用户名,一般用于生成文件头部的注释 created_at=created_at, # 当前系统时间,一般用于文件头部的注释 sql_a_types=sql_a_types, # 对应的sqlA类型(不仅限于sqlA,如果以后使用其他框架,修改get_all_sql_a_type方法即可) mixins=mixins, # 相关mixin IdMixin等。。。 columns=columns, # 数据库字段信息,自定义编辑信息等一些关于字段的信息 condition_search_columns=condition_search_columns, # 存产于条件查询的列信息 便于模版处理 order_by_columns=order_by_columns, # 存产于条件查询的排序信息 便于模版处理 gets_by_columns=gets_by_columns, # 存产于字段查询的列信息 便于模版处理 get_by_columns=get_by_columns # 存产于字段查询的列信息 便于模版处理 ) # 定制参数 if ext_namespace: namespace.update(ext_namespace) return namespace @staticmethod def get_dirs(dir_type): dirs = dict( dao=os.path.join(Settings.SITE_ROOT_PATH, 'app/daos'), service=os.path.join(Settings.SITE_ROOT_PATH, 'app/services'), handler=os.path.join(Settings.SITE_ROOT_PATH, 'app/handlers'), view=os.path.join(Settings.SITE_ROOT_PATH, 'app/views') ) dir_str_long = dirs[dir_type] dir_str_shot = "" return dir_str_long def get_config_schema_name(self): return self.database_config["database"] @staticmethod def get_edit_types(): """所有编辑类型关键字 :return: """ return ("input", "text", "radio", "checkbox", "select", "date", "datetime", "time") @staticmethod def get_sql_edit_type(data_type): """数据库类型默认编辑类型 :return: """ types_map = dict( datetime="datetime", smallinteger="input", numeric="input", unicodetext="text", varchar="input", char="input", pickletype="input", bigint="input", unicode="input", binary="input", enum="input", date="date", int="input", interval="input", time="time", text="text", float="input", largebinary="input", tinyint="radio") if data_type in types_map: return types_map[data_type] else: return "input" @staticmethod def get_where_types(): return ("==", "!=", "llike", "rlike", "like", "between") @staticmethod def get_first_word(word_str): """获取第一个特殊符号(非数字 字母 中文)前所有字符,待匹配字符为unicode 用于数据库注释中获取字段中文名 :param word_str: :return: """ r = re.compile(ur'[\w]*[\u4E00-\u9FA5]*[\w]*') # 这个要加上ur s_match = r.findall(word_str) if s_match and len(s_match) > 0: return s_match[0] return "" @staticmethod def get_column_length(column_type): """获取数据库字段长度 :param column_type: 数据库字段类型(长度) :return: 字段长度 """ pattern = re.compile("\w*\((\d*)\)w*") res = pattern.search(column_type) if res is None: return None else: return res.groups()[0] @staticmethod def get_sql_a_type(sql_type): """根据数据库字段类型获取对应的SQLA数据类型 这个类型对应还有待完善 :param sql_type:数据库字段类型 :return:SQLA数据类型字符串 """ types_map = dict( datetime="DateTime", smallinteger="SmallInteger", numeric="Numeric", unicodetext="UnicodeText", varchar="String", char="String", pickletype="PickleType", bigint="BigInteger", unicode="Unicode", binary="Binary", enum="Enum", date="Date", int="Integer", interval="Interval", time="Time", text="Text", float="Float", largebinary="LargeBinary", tinyint="Boolean") if sql_type in types_map: return types_map[sql_type] else: return None @staticmethod def get_model_name(table_name): """将‘user_categories’ 转换成‘UserCategory’,用作数据库表名转换成对应的实体名 :param table_name: 需要传入的表名 :return: """ model_name = inflection.singularize(inflection.camelize(table_name)) return model_name @staticmethod def get_all_sql_a_type(columns): """获取指定columns中所有的sqlA类型 :param columns: :return: """ sql_a_types = set() for col in columns: # 过滤掉不存在类型,以及默认字段类型 if col["sql_a_type"] and col["column_name"] not in ("id", "created_at", "updated_at", "is_deleted"): sql_a_types.add(col["sql_a_type"]) return sql_a_types @staticmethod def get_all_mixin(columns): """获取指定columns中所有的 mixin :param columns: :return: """ mixins = dict() for col in columns: col_name = col["column_name"] if col_name == "id": mixins.setdefault("id", "IdMixin") if col_name == "created_at": mixins.setdefault("created_at", "CreatedAtMixin") if col_name == "updated_at": mixins.setdefault("updated_at", "UpdatedAtMixin") if col_name == "is_deleted": mixins.setdefault("is_deleted", "IsDeletedMixin") return mixins @staticmethod def get_sys_user_name(): """获取当前系统用户名 :return: """ return getpass.getuser() class GenerateFileService(object): """ 生成文件通用服务 准备模版参数,调用模版生成字符串,读写文件等功能 """ def __init__(self, table_name, columns=None): self.table_name = table_name self.dbm = DBMessage() self.namespace = self.dbm.get_namespace(self.table_name) if columns is not None: self.namespace.update(dict(columns=columns)) self.template_path = os.path.join(os.path.dirname(__file__), u"templates") self.templates = dict(dao="dao_template.txt", service="service_template.txt", handler="handler_template.txt", list_page="list_page_template.txt", add_edit_page="add_edit_page_template.txt", detail_page="detail_page_template.txt", route="route_template.txt" ) def get_dao_string(self): template_file_name = self.templates["dao"] return MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) def get_service_string(self): template_file_name = self.templates["service"] return MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) def get_handler_string(self): template_file_name = self.templates["handler"] return MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) def get_route_string(self): template_file_name = self.templates["route"] return MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) def get_list_page_string(self): template_file_name = self.templates["list_page"] list_page_str = MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) list_page_str = list_page_str.replace("}&}", "}}") return list_page_str def get_add_edit_page_string(self): template_file_name = self.templates["add_edit_page"] add_edit_page_str = MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) add_edit_page_str = add_edit_page_str.replace("}&}", "}}") return add_edit_page_str def get_detail_page_string(self): template_file_name = self.templates["detail_page"] detail_page_str = MyTemplate.get_template_string(self.template_path, template_file_name, self.namespace) detail_page_str = detail_page_str.replace("}&}", "}}") return detail_page_str if __name__ == "__main__": gfs = GenerateFileService(table_name="tests") print gfs.get_dao_string() # print gfs.get_service_string() # print gfs.get_handler_string() # print gfs.get_route_string() # print gfs.get_list_page_string() # print gfs.get_add_edit_page_string() # print gfs.get_detail_page_string()
36ban_commons
/36ban_commons-0.0.1.tar.gz/36ban_commons-0.0.1/generate/generate_code_service.py
generate_code_service.py
# Registration tools __Before everything else, the current status of the whole thing here is that it only works on UNIX systems (eg Linux & MacOs) that have reasonnable chips (eg not M1 chips for example).__ ## Purpose and "history" This repository is about two scripts to do spatial and temporal registration of 3D microscopy images. It was initially developed to help friends with their ever moving embryos living under a microscope. I found that actually quite a few people were interested so I made a version of it that is somewhat easier to use. In theory, the main difficulty to make the whole thing work is to install the different libraries. ## Credits The whole thing is just a wrapping of the amazing blockmatching algorithm developed by [S. Ourselin et al.] and currently maintained Grégoire Malandin et al.@[Team Morphem - inria] (if I am not mistaking). ## Installation [conda] and [pip] are required to install `registration-tools` We recommand to install the registration tools in a specific environement (like [conda]). For example the following way: conda create -n registration python=3.10 You can then activate the environement the following way: conda activate registration For here onward we assume that you are running the commands from the `registration` [conda] environement. Then, to install the whole thing, it is necessary to first install blockmatching. To do so you can run the following command: conda install vt -c morpheme -c trcabel Then, you can install the 3D-registration library either directly via pip: pip install 3D-registration Or, if you want the latest version, by specifying the git repository: pip install git+https://github.com/GuignardLab/registration-tools.git ### Troubleshooting - Windows: If you are trying to run the script on Windows you might need to install `pthreadvse2.dll`. It can be found there: https://www.pconlife.com/viewfileinfo/pthreadvse2-dll/ . Make sure to download the version that matches your operating system (32 or 64 bits, most likely 64). - MacOs: As there are no M1 binaries available yet, please use rosetta or install an intel version of conda. ## Usage Most of the description on how to use the two scripts is described in the [manual] (Note that the installation part is quite outdated, the remaining is ok). That being said, once installed, one can run either of the scripts from anywhere in a terminal by typing: time-registration or spatial-registration The location of the json files or folder containing the json files will be prompted and when provided the registration will start. It is also possible to run the registration from a script/notebook the following way: ```python from registrationtools import TimeRegistration tr = TimeRegistration('path/to/param.json') tr.run_trsf() ``` or ```python from registrationtools import TimeRegistration tr = TimeRegistration('path/to/folder/with/jsonfiles/') tr.run_trsf() ``` or ```python from registrationtools import TimeRegistration tr = TimeRegistration() tr.run_trsf() ``` and a path will be asked to be inputed. ### Example json files Few example json files are provided to help the potential users. You can find informations about what they do in the [manual]. [S. Ourselin et al.]: http://www-sop.inria.fr/asclepios/Publications/Gregoire.Malandain/ourselin-miccai-2000.pdf [Team Morphem - inria]: https://team.inria.fr/morpheme/ [conda]: https://conda.io/projects/conda/en/latest/user-guide/install/index.html [pip]: https://pypi.org/project/pip/ [manual]: https://github.com/GuignardLab/registration-tools/blob/master/User-manual/user-manual.pdf
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/README.md
README.md
from os.path import ( exists, splitext, isdir, split as psplit, expanduser as expusr, ) import os, fnmatch import warnings from struct import pack, unpack, calcsize from pickle import dumps, loads import numpy as np from .spatial_image import SpatialImage from .inrimage import read_inrimage, write_inrimage try: from .tif import read_tif, write_tif except Exception as e: warnings.warn("pylibtiff library is not installed") try: from .h5 import read_h5, write_h5 except Exception as e: warnings.warn("h5py library is not installed") try: from .klb import read_klb, write_klb except Exception as e: warnings.warn("KLB library is not installed") from .folder import read_folder def imread(filename, parallel=True, SP_im=True): """Reads an image file completely into memory. It uses the file extension to determine how to read the file. It first tries some specific readers for volume images (Inrimages, TIFFs, LSMs, NPY) or falls back on PIL readers for common formats if installed. In all cases the returned image is 3D (2D is upgraded to single slice 3D). If it has colour or is a vector field it is even 4D. :Parameters: - `filename` (str) :Returns Type: |SpatialImage| """ filename = expusr(filename) if not exists(filename): raise IOError("The requested file do not exist: %s" % filename) root, ext = splitext(filename) ext = ext.lower() if ext == ".gz": root, ext = splitext(root) ext = ext.lower() if ext == ".inr": return read_inrimage(filename) elif ext in [".tif", ".tiff"]: return read_tif(filename) elif ext in [".h5", ".hdf5"]: return read_h5(filename) elif ext == ".klb": return read_klb(filename, SP_im) elif isdir(filename): return read_folder(filename, parallel) def imsave(filename, img): """Save a |SpatialImage| to filename. .. note: `img` **must** be a |SpatialImage|. The filewriter is choosen according to the file extension. However all file extensions will not match the data held by img, in dimensionnality or encoding, and might raise `IOError`s. For real volume data, Inrimage and NPY are currently supported. For |SpatialImage|s that are actually 2D, PNG, BMP, JPG among others are supported if PIL is installed. :Parameters: - `filename` (str) - `img` (|SpatialImage|) """ filename = expusr(filename) root, ext = splitext(filename) # assert isinstance(img, SpatialImage) or ext == '.klb' # -- images are always at least 3D! If the size of dimension 3 (indexed 2) is 1, then it is actually # a 2D image. If it is 4D it has vectorial or RGB[A] data. -- head, tail = psplit(filename) head = head or "." if not exists(head): raise IOError("The directory do not exist: %s" % head) # is2D = img.shape[2] == 1 ext = ext.lower() if ext == ".gz": root, ext = splitext(root) ext = ext.lower() if ext == ".inr": write_inrimage(filename, img) elif ext in [".tiff", ".tif"]: write_tif(filename, img) elif ext == ".klb": write_klb(filename, img) elif ext in [".h5", ".hdf5"]: write_h5(filename, img)
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/IO/IO.py
IO.py
__license__ = "Cecill-C" __revision__ = " $Id$ " import numpy as np from .spatial_image import SpatialImage __all__ = [] import decimal import numpy as np from tifffile import TiffFile, imread, imwrite import os, os.path, sys, time __all__ += ["read_tif", "write_tif", "mantissa"] def read_tif(filename, channel=0): """Read a tif image :Parameters: - `filename` (str) - name of the file to read """ def format_digit(v): try: v = eval(v) except Exception as e: pass return v with TiffFile(filename) as tif: if "ImageDescription" in tif.pages[0].tags: description = ( tif.pages[0].tags["ImageDescription"].value.split("\n") ) separator = set.intersection(*[set(k) for k in description]).pop() info_dict = { v.split(separator)[0]: format_digit(v.split(separator)[1]) for v in description } else: info_dict = {} if "XResolution" in tif.pages[0].tags: vx = tif.pages[0].tags["XResolution"].value if vx[0] != 0: vx = vx[1] / vx[0] if isinstance(vx, list): vx = vx[1] / vx[0] else: vx = 1.0 else: vx = 1.0 if "YResolution" in tif.pages[0].tags: vy = tif.pages[0].tags["YResolution"].value if vy[0] != 0: vy = vy[1] / vy[0] if isinstance(vy, list): vy = vy[1] / vy[0] else: vy = 1.0 else: vy = 1.0 if "ZResolution" in tif.pages[0].tags: vz = tif.pages[0].tags["ZResolution"].value if vz[0] != 0: if isinstance(vz, list): vz = vz[1] / vz[0] else: vz = 1.0 elif "spacing" in info_dict: vz = info_dict["spacing"] else: vz = 1.0 im = tif.asarray() if len(im.shape) == 3: im = np.transpose(im, (2, 1, 0)) elif len(im.shape) == 2: im = np.transpose(im, (1, 0)) if 3 <= len(im.shape): im = SpatialImage(im, (vx, vy, vz)) else: print(im.shape, vx, vy) im = SpatialImage(im, (vx, vy)) im.resolution = (vx, vy, vz) return im def mantissa(value): """Convert value to [number, divisor] where divisor is power of 10""" # -- surely not the nicest thing around -- d = decimal.Decimal(str(value)) # -- lovely... sign, digits, exp = d.as_tuple() n_digits = len(digits) dividend = int( sum(v * (10 ** (n_digits - 1 - i)) for i, v in enumerate(digits)) * (1 if sign == 0 else -1) ) divisor = int(10**-exp) return dividend, divisor def write_tif(filename, obj): if len(obj.shape) > 3: raise IOError( "Vectorial images are currently unsupported by tif writer" ) is3D = len(obj.shape) == 3 if hasattr(obj, "resolution"): res = obj.resolution elif hasattr(obj, "voxelsize"): res = obj.resolution else: res = (1, 1, 1) if is3D else (1, 1) vx = 1.0 / res[0] vy = 1.0 / res[1] if is3D: spacing = res[2] metadata = {"spacing": spacing, "axes": "ZYX"} else: metadata = {} extra_info = { "XResolution": res[0], "YResolution": res[1], "spacing": spacing if is3D else None, # : no way to save the spacing (no specific tag) } print(extra_info) if obj.dtype.char in "BHhf": return imwrite( filename, obj.T, imagej=True, resolution=(vx, vy), metadata=metadata, ) else: return imwrite(filename, obj.T)
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/IO/tif.py
tif.py
__license__ = "Cecill-C" __revision__ = " $Id: $ " import numpy as np from scipy import ndimage import copy as cp # -- deprecation messages -- # import warnings, exceptions # msg = "SpatialImage.resolution is deprecated, use SpatialImage.voxelsize" # rezexc = exceptions.PendingDeprecationWarning(msg) class SpatialImage(np.ndarray): """ Associate meta data to np.ndarray """ def __new__( cls, input_array, voxelsize=None, vdim=None, info=None, dtype=None, **kwargs ): """Instantiate a new |SpatialImage| if voxelsize is None, vdim will be used to infer space size and affect a voxelsize of 1 in each direction of space .. warning :: `resolution` keyword is deprecated. Use `voxelsize` instead. :Parameters: - `cls` - internal python - `input_array` (array) - data to put in the image - `voxelsize` (tuple of float) - spatial extension in each direction of space - `vdim` (int) - size of data if vector data are used - `info` (dict of str|any) - metainfo """ # if the input_array is 2D we can reshape it to 3D. # ~ if input_array.ndim == 2: # Jonathan # ~ input_array = input_array.reshape( input_array.shape+(1,) ) # Jonathan # initialize datas. For some obscure reason, we want the data # to be F-Contiguous in the NUMPY sense. I mean, if this is not # respected, we will have problems when communicating with # C-Code... yeah, that makes so much sense (fortran-contiguous # to be c-readable...). dtype = dtype if dtype is not None else input_array.dtype if input_array.flags.f_contiguous: obj = np.asarray(input_array, dtype=dtype).view(cls) else: obj = np.asarray(input_array, dtype=dtype, order="F").view(cls) voxelsize = kwargs.get("resolution", voxelsize) # to manage transition if voxelsize is None: # ~ voxelsize = (1.,) * 3 voxelsize = (1.0,) * input_array.ndim # Jonathan else: # ~ if len(voxelsize) != 3 : if (input_array.ndim != 4) and ( len(voxelsize) != input_array.ndim ): # Jonathan _ Compatibility with "champs_*.inr.gz" generated by Baloo & SuperBaloo raise ValueError("data dimension and voxelsize mismatch") obj.voxelsize = tuple(voxelsize) obj.vdim = vdim if vdim else 1 # set metadata if info is None: obj.info = {} else: obj.info = dict(info) # return return obj def _get_resolution(self): # warnings.warn(rezexc) return self.voxelsize def _set_resolution(self, val): # warnings.warn(rezexc) self.voxelsize = val resolution = property(_get_resolution, _set_resolution) @property def real_shape(self): # ~ return np.multiply(self.shape[:3], self.voxelsize) return np.multiply(self.shape, self.voxelsize) # Jonathan def invert_z_axis(self): """ invert allong 'Z' axis """ self = self[:, :, ::-1] def __array_finalize__(self, obj): if obj is None: return # assert resolution res = getattr(obj, "voxelsize", None) if res is None: # assert vdim == 1 res = (1.0,) * len(obj.shape) self.voxelsize = tuple(res) # metadata self.info = dict(getattr(obj, "info", {})) def clone(self, data): """Clone the current image metadata on the given data. .. warning:: vdim is defined according to self.voxelsize and data.shape :Parameters: - `data` - (array) :Returns Type: |SpatialImage| """ if len(data.shape) == len(self.voxelsize): vdim = 1 elif len(data.shape) - len(self.voxelsize) == 1: vdim = data.shape[-1] else: raise UserWarning("unable to handle such data dimension") return SpatialImage(data, self.voxelsize, vdim, self.info) @classmethod def valid_array(cls, array_like): return ( isinstance(array_like, (np.ndarray, cls)) and array_like.flags.f_contiguous ) def empty_image_like(spatial_image): array = np.zeros(spatial_image.shape, dtype=spatial_image.dtype) return SpatialImage(array, spatial_image.voxelsize, vdim=1) def null_vector_field_like(spatial_image): array = np.zeros(list(spatial_image.shape) + [3], dtype=np.float32) return SpatialImage(array, spatial_image.voxelsize, vdim=3) def random_vector_field_like(spatial_image, smooth=0, max_=1): # ~ if spatial_image.vdim == 1: # ~ shape = spatial_image.shape+(3,) # ~ else: # ~ shape = spatial_image.shape shape = spatial_image.shape # Jonathan array = np.random.uniform(-max_, max_, shape) if smooth: array = ndimage.gaussian_filter(array, smooth) return SpatialImage(array, spatial_image.voxelsize, dtype=np.float32) def checkerboard( nx=9, ny=8, nz=5, size=10, vs=(1.0, 1.0, 1.0), dtype=np.uint8 ): """Creates a 3D checkerboard image with `nx` squares in width, `ny` squares in height and `nz` squares in depth. The length of the edge in real units of each square is `size`.""" sxv, syv, szv = np.array([size] * 3) / np.array(vs) array = np.zeros((sxv * nx, syv * ny, szv * nz), dtype=dtype, order="F") typeinfo = np.iinfo(dtype) # -- wooo surely not the most beautiful implementation out here -- for k in range(nz): kval = typeinfo.max if (k % 2 == 0) else typeinfo.min jval = kval for j in range(ny): ival = jval for i in range(nx): array[ i * sxv : i * sxv + sxv, j * syv : j * syv + syv, k * szv : k * szv + szv, ] = ival ival = typeinfo.max if (ival == typeinfo.min) else typeinfo.min jval = typeinfo.max if (jval == typeinfo.min) else typeinfo.min kval = typeinfo.max if (kval == typeinfo.min) else typeinfo.min return SpatialImage(array, vs, dtype=dtype) def is2D(image): """ Test if the `image` (array) is in 2D or 3D. Return True if 2D, False if not. """ if len(image.shape) == 2 or image.shape[2] == 1: return True else: return False
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/IO/spatial_image.py
spatial_image.py
__license__ = "Cecill-C" __revision__ = " $Id$ " import os from os import path import numpy as np from struct import calcsize, pack, unpack import gzip from io import BytesIO from .spatial_image import SpatialImage __all__ = ["read_inriheader", "read_inrimage", "write_inrimage"] specific_header_keys = ( "XDIM", "YDIM", "ZDIM", "VDIM", "TYPE", "PIXSIZE", "SCALE", "CPU", "VX", "VY", "VZ", "TX", "TY", "TZ", "#GEOMETRY", ) def open_inrifile(filename): """Open an inrimage file Manage the gz attribute """ if path.splitext(filename)[1] in (".gz", ".zip"): with gzip.open(filename, "rb") as fzip: f = BytesIO(fzip.read()) fzip.close() else: f = open(filename, "rb") return f def _read_header(f): """Extract header from a stream and return it as a python dict """ # read header string header = "" while header[-4:] != "##}\n": header += f.read(256).decode("latin-1") # read infos in header prop = {} hstart = header.find("{\n") + 1 hend = header.find("##}") infos = [gr for gr in header[hstart:hend].split("\n") if len(gr) > 0] # format infos for prop_def in infos: key, val = prop_def.split("=") prop[key] = val # return return prop def read_inriheader(filename): """Read only the header of an inrimage :Parameters: - `filename` (str) - name of the file to read """ f = open_inrifile(filename) prop = _read_header(f) f.close() return prop def read_inrimage(filename): """Read an inrimage, either zipped or not according to extension :Parameters: - `filename` (str) - name of the file to read """ f = open_inrifile(filename) # read header prop = _read_header(f) prop["filename"] = filename # Jonathan : 14.05.2012 # extract usefull infos to read image zdim = int(prop.pop("ZDIM")) ydim = int(prop.pop("YDIM")) xdim = int(prop.pop("XDIM")) vdim = int(prop.pop("VDIM", 1)) # if vdim != 1 : # msg = "don't know how to handle vectorial pixel values" # raise NotImplementedError(msg) # find data type pixsize = int(prop.pop("PIXSIZE", "0").split(" ")[0]) dtype = prop.pop("TYPE") if dtype == "unsigned fixed": if pixsize == 0: ntyp = np.dtype(np.int) else: try: ntyp = eval("np.dtype(np.uint%d)" % pixsize) except AttributeError: raise UserWarning("undefined pix size: %d" % pixsize) elif dtype == "float": if pixsize == 0: ntyp = np.dtype(np.float) else: try: ntyp = eval("np.dtype(np.float%d)" % pixsize) except AttributeError: raise UserWarning("undefined pix size: %d" % pixsize) else: msg = "unable to read that type of datas : %s" % dtype raise UserWarning(msg) # read datas size = ntyp.itemsize * xdim * ydim * zdim * vdim mat = np.frombuffer(f.read(size), ntyp) if vdim != 1: mat = mat.reshape((vdim, xdim, ydim, zdim), order="F") mat = mat.transpose(1, 2, 3, 0) else: mat = mat.reshape((xdim, ydim, zdim), order="F") # mat = mat.transpose(2,1,0) # create SpatialImage res = tuple(float(prop.pop(k)) for k in ("VX", "VY", "VZ")) for k in ("TX", "TY", "TZ"): prop.pop(k, None) img = SpatialImage(mat, res, vdim, prop) # return f.close() return img def write_inrimage_to_stream(stream, img): assert img.ndim in (3, 4) # metadata info = dict(getattr(img, "info", {})) if "filename" in info: info["filename"] = path.basename(info["filename"]) else: info["filename"] = path.basename("img.inr") # image dimensions if img.ndim < 4: info["XDIM"], info["YDIM"], info["ZDIM"] = ( "%d" % val for val in img.shape ) info["VDIM"] = "1" else: info["XDIM"], info["YDIM"], info["ZDIM"], info["VDIM"] = ( "%d" % val for val in img.shape ) # image resolution res = getattr(img, "resolution", (1, 1, 1)) info["VX"], info["VY"], info["VZ"] = ("%f" % val for val in res) # data type if img.dtype == np.uint8: info["TYPE"] = "unsigned fixed" info["PIXSIZE"] = "8 bits" elif img.dtype == np.uint16: info["TYPE"] = "unsigned fixed" info["PIXSIZE"] = "16 bits" elif img.dtype == np.uint32: info["TYPE"] = "unsigned fixed" info["PIXSIZE"] = "32 bits" elif img.dtype == np.uint64: info["TYPE"] = "unsigned fixed" info["PIXSIZE"] = "64 bits" elif img.dtype == np.float32: info["TYPE"] = "float" info["PIXSIZE"] = "32 bits" elif img.dtype == np.float64: info["TYPE"] = "float" info["PIXSIZE"] = "64 bits" # elif img.dtype == np.float128 : # info["TYPE"] = "float" # info["PIXSIZE"] = "128 bits" else: msg = "unable to write that type of datas : %s" % str(img.dtype) raise UserWarning(msg) # mandatory else an error occurs when reading image info["#GEOMETRY"] = "CARTESIAN" info["CPU"] = "decm" # write header header = "#INRIMAGE-4#{\n" for ( k ) in ( specific_header_keys ): # HACK pas bo to ensure order of specific headers try: header += "%s=%s\n" % (k, info[k]) except KeyError: pass for k in set(info) - set(specific_header_keys): header += "%s=%s\n" % (k, info[k]) # fill header to be a multiple of 256 header_size = len(header) + 4 if (header_size % 256) > 0: header += "\n" * (256 - header_size % 256) header += "##}\n" contiguous_rule = "C" if img.flags["C_CONTIGUOUS"] else "F" stream.write(header) if img.ndim == 3: stream.write(img.tostring(contiguous_rule)) elif img.ndim == 4: mat = img.transpose(3, 0, 1, 2) stream.write(mat.tostring(contiguous_rule)) else: raise Exception("Unhandled image dimension %d." % img.ndim) def write_inrimage(filename, img): """Write an inrimage zipped or not according to the extension .. warning:: if img is not a |SpatialImage|, default values will be used for the resolution of the image :Parameters: - `img` (|SpatialImage|) - image to write - `filename` (str) - name of the file to read """ # open stream zipped = path.splitext(filename)[1] in (".gz", ".zip") if zipped: f = gzip.GzipFile(filename, "wb") # f = StringIO() else: f = open(filename, "wb") try: write_inrimage_to_stream(f, img) except: # -- remove probably corrupt file-- f.close() if path.exists(filename) and path.isfile(filename): os.remove(filename) raise else: f.close()
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/IO/inrimage.py
inrimage.py
from pathlib import Path from time import time import os from subprocess import call import scipy as sp from scipy import interpolate import json import numpy as np from IO import imread, imsave, SpatialImage from typing import List, Tuple from statsmodels.nonparametric.smoothers_lowess import lowess import sys import xml.etree.ElementTree as ET from xml.dom import minidom from transforms3d.affines import decompose from transforms3d.euler import mat2euler if sys.version_info[0] < 3: from future.builtins import input try: from pyklb import readheader pyklb_found = True except Exception as e: pyklb_found = False print("pyklb library not found, klb files will not be generated") class trsf_parameters(object): """ Read parameters for the registration function from a preformated json file """ def check_parameters_consistancy(self) -> bool: """ Function that should check parameter consistancy """ correct = True if not "path_to_data" in self.__dict__: print('\n\t"path_to_data" is required') correct = False if not "file_name" in self.__dict__: print('\n\t"file_name" is required') correct = False if not "trsf_folder" in self.__dict__: print('\n\t"trsf_folder" is required') correct = False if not "voxel_size" in self.__dict__: print('\n\t"voxel_size" is required') correct = False if not "ref_TP" in self.__dict__: print('\n\t"ref_TP" is required') correct = False if not "projection_path" in self.__dict__: print('\n\t"projection_path" is required') correct = False if self.apply_trsf and not "output_format" in self.__dict__: print('\n\t"output_format" is required') correct = False if self.trsf_type != "translation" and ( self.lowess or self.trsf_interpolation ): print("\n\tLowess or transformation interplolation") print("\tonly work with translation") correct = False if self.lowess and not "window_size" in self.param_dict: print('\n\tLowess smoothing "window_size" is missing') print("\tdefault value of 5 will be used\n") if self.trsf_interpolation and not "step_size" in self.param_dict: print('\n\tTransformation interpolation "step_size" is missing') print("\tdefault value of 100 will be used\n") if self.trsf_type == "vectorfield" and self.ref_path is None: print("\tNon-linear transformation asked with propagation.") print("\tWhile working it is highly not recommended") print( "\tPlease consider not doing a registration from propagation" ) print("\tTHIS WILL LITERALLY TAKE AGES!! IF IT WORKS AT ALL ...") if ( not isinstance(self.spline, int) or self.spline < 1 or 5 < self.spline ): out = ("{:d}" if isinstance(self.spline, int) else "{:s}").format( self.spline ) print("The degree of smoothing for the spline interpolation") print("Should be an Integer between 1 and 5, you gave " + out) return correct def __str__(self) -> str: max_key = ( max([len(k) for k in self.__dict__.keys() if k != "param_dict"]) + 1 ) max_tot = ( max( [ len(str(v)) for k, v in self.__dict__.items() if k != "param_dict" ] ) + 2 + max_key ) output = "The registration will run with the following arguments:\n" output += "\n" + " File format ".center(max_tot, "-") + "\n" output += "path_to_data".ljust(max_key, " ") + ": {}\n".format( self.path_to_data ) output += "file_name".ljust(max_key, " ") + ": {}\n".format( self.file_name ) output += "trsf_folder".ljust(max_key, " ") + ": {}\n".format( self.trsf_folder ) output += "output_format".ljust(max_key, " ") + ": {}\n".format( self.output_format ) output += "check_TP".ljust(max_key, " ") + ": {:d}\n".format( self.check_TP ) output += "\n" + " Time series properties ".center(max_tot, "-") + "\n" output += "voxel_size".ljust( max_key, " " ) + ": {:f}x{:f}x{:f}\n".format(*self.voxel_size) output += "first".ljust(max_key, " ") + ": {:d}\n".format(self.first) output += "last".ljust(max_key, " ") + ": {:d}\n".format(self.last) output += "\n" + " Registration ".center(max_tot, "-") + "\n" output += "compute_trsf".ljust(max_key, " ") + ": {:d}\n".format( self.compute_trsf ) if self.compute_trsf: output += "ref_TP".ljust(max_key, " ") + ": {:d}\n".format( self.ref_TP ) if self.ref_path is not None: output += "ref_path".ljust(max_key, " ") + ": {}\n".format( self.ref_path ) output += "trsf_type".ljust(max_key, " ") + ": {}\n".format( self.trsf_type ) if self.trsf_type == "vectorfield": output += "sigma".ljust(max_key, " ") + ": {:.2f}\n".format( self.sigma ) output += "padding".ljust(max_key, " ") + ": {:d}\n".format( self.padding ) output += "lowess".ljust(max_key, " ") + ": {:d}\n".format( self.lowess ) if self.lowess: output += "window_size".ljust( max_key, " " ) + ": {:d}\n".format(self.window_size) output += "trsf_interpolation".ljust( max_key, " " ) + ": {:d}\n".format(self.trsf_interpolation) if self.trsf_interpolation: output += "step_size".ljust(max_key, " ") + ": {:d}\n".format( self.step_size ) output += "recompute".ljust(max_key, " ") + ": {:d}\n".format( self.recompute ) output += "apply_trsf".ljust(max_key, " ") + ": {:d}\n".format( self.apply_trsf ) if self.apply_trsf: if self.projection_path is not None: output += "projection_path".ljust( max_key, " " ) + ": {}\n".format(self.projection_path) output += "image_interpolation".ljust( max_key, " " ) + ": {}\n".format(self.image_interpolation) return output def add_path_prefix(self, prefix: str): """ Add a prefix to all the relevant paths (this is mainly for the unitary tests) Args: prefix (str): The prefix to add in front of the path """ self.projection_path = ( os.path.join(prefix, self.projection_path) + os.path.sep ) self.path_to_data = ( os.path.join(prefix, self.path_to_data) + os.path.sep ) self.trsf_folder = os.path.join(prefix, self.trsf_folder) + os.path.sep self.output_format = ( os.path.join(prefix, self.output_format) + os.path.sep ) def __init__(self, file_name: str): if not isinstance(file_name, dict): with open(file_name) as f: param_dict = json.load(f) f.close() else: param_dict = {} for k, v in file_name.items(): if isinstance(v, Path): param_dict[k] = str(v) else: param_dict[k] = v # Default parameters self.check_TP = None self.not_to_do = [] self.compute_trsf = True self.ref_path = None self.padding = 1 self.lowess = False self.window_size = 5 self.step_size = 100 self.recompute = True self.apply_trsf = True self.sigma = 2.0 self.keep_vectorfield = False self.trsf_type = "rigid" self.image_interpolation = "linear" self.path_to_bin = "" self.spline = 1 self.trsf_interpolation = False self.sequential = True self.time_tag = "TM" self.do_bdv = 0 self.bdv_voxel_size = None self.bdv_unit = "microns" self.projection_path = None self.pre_2D = False self.low_th = None self.plot_trsf = False self.param_dict = param_dict if "registration_depth" in param_dict: self.__dict__["registration_depth_start"] = 6 self.__dict__["registration_depth_end"] = param_dict[ "registration_depth" ] elif not "registration_depth_start" in param_dict: self.__dict__["registration_depth_start"] = 6 self.__dict__["registration_depth_end"] = 3 self.__dict__.update(param_dict) self.voxel_size = tuple(self.voxel_size) if not hasattr(self, "voxel_size_out"): self.voxel_size_out = self.voxel_size else: self.voxel_size_out = tuple(self.voxel_size_out) self.origin_file_name = file_name if ( 0 < len(self.projection_path) and self.projection_path[-1] != os.path.sep ): self.projection_path = self.projection_path + os.path.sep self.path_to_data = os.path.join(self.path_to_data, "") self.trsf_folder = os.path.join(self.trsf_folder, "") self.path_to_bin = os.path.join(self.path_to_bin, "") if 0 < len(self.path_to_bin) and not os.path.exists(self.path_to_bin): print("Binary path could not be found, will try with global call") self.path_to_bin = "" class TimeRegistration: @staticmethod def read_trsf(path: str) -> np.ndarray: """ Read a transformation from a text file Args: path (str): path to a transformation Returns (np.ndarray): 4x4 ndarray matrix """ f = open(path) if f.read()[0] == "(": f.close() f = open(path) lines = f.readlines()[2:-1] f.close() return np.array([[float(v) for v in l.split()] for l in lines]) f.close() return np.loadtxt(path) def __produce_trsf(self, params: Tuple[trsf_parameters, int, int, bool]): """ Given a parameter object a reference time and two time points compute the transformation that registers together two consecutive in time images. Args: params (tuple): a tuple with the parameter object, two consecutive time points to register and a boolean to detemine wether to apply the trsf or not """ (p, t1, t2, make) = params if not p.sequential: p_im_flo = p.A0.format(t=t2) p_im_ref = p.ref_path t_ref = p.ref_TP t_flo = t2 if t1 == p.to_register[0]: self.__produce_trsf((p, t2, t1, make)) else: if t1 < p.ref_TP: t_ref = t2 t_flo = t1 else: t_ref = t1 t_flo = t2 p_im_ref = p.A0.format(t=t_ref) p_im_flo = p.A0.format(t=t_flo) if not make: print("trsf tp %d-%d not done" % (t1, t2)) np.savetxt( os.path.join(p.trsf_folder, "t%06d-%06d.txt" % (t_flo, t_ref)), np.identity(4), ) elif t_flo != t_ref and ( p.recompute or not os.path.exists( os.path.join(p.trsf_folder, "t%06d-%06d.txt" % (t_flo, t_ref)) ) ): if p.low_th is not None and 0 < p.low_th: th = " -ref-lt {lt:f} -flo-lt {lt:f} -no-norma ".format( lt=p.low_th ) else: th = "" if p.trsf_type != "vectorfield": if p.pre_2D == 1: call( self.path_to_bin + "blockmatching -ref " + p_im_ref + " -flo " + p_im_flo + " -reference-voxel %f %f %f" % p.voxel_size + " -floating-voxel %f %f %f" % p.voxel_size + " -trsf-type rigid2D -py-hl %d -py-ll %d" % ( p.registration_depth_start, p.registration_depth_end, ) + " -res-trsf " + os.path.join( p.trsf_folder, "t%06d-%06d-tmp.txt" % (t_flo, t_ref), ) + th, shell=True, ) pre_trsf = ( " -init-trsf " + os.path.join( p.trsf_folder, "t%06d-%06d-tmp.txt" % (t_flo, t_ref), ) + " -composition-with-initial " ) else: pre_trsf = "" call( self.path_to_bin + "blockmatching -ref " + p_im_ref + " -flo " + p_im_flo + pre_trsf + " -reference-voxel %f %f %f" % p.voxel_size + " -floating-voxel %f %f %f" % p.voxel_size + " -trsf-type %s -py-hl %d -py-ll %d" % ( p.trsf_type, p.registration_depth_start, p.registration_depth_end, ) + " -res-trsf " + os.path.join( p.trsf_folder, "t%06d-%06d.txt" % (t_flo, t_ref) ) + th, shell=True, ) else: if p.apply_trsf: res = " -res " + p.A0_out.format(t=t_flo) else: res = "" if p.keep_vectorfield and pyklb_found: res_trsf = ( " -composition-with-initial -res-trsf " + os.path.join( p.trsf_folder, "t%06d-%06d.klb" % (t_flo, t_ref) ) ) else: res_trsf = "" if p.keep_vectorfield: print( "The vectorfield cannot be stored without pyklb being installed" ) call( self.path_to_bin + "blockmatching -ref " + p_im_ref + " -flo " + p_im_flo + " -reference-voxel %f %f %f" % p.voxel_size + " -floating-voxel %f %f %f" % p.voxel_size + " -trsf-type affine -py-hl %d -py-ll %d" % (p.registration_depth_start, p.registration_depth_end) + " -res-trsf " + os.path.join( p.trsf_folder, "t%06d-%06d.txt" % (t_flo, t_ref) ) + th, shell=True, ) call( self.path_to_bin + "blockmatching -ref " + p_im_ref + " -flo " + p_im_flo + " -init-trsf " + os.path.join( p.trsf_folder, "t%06d-%06d.txt" % (t_flo, t_ref) ) + res + " -reference-voxel %f %f %f" % p.voxel_size + " -floating-voxel %f %f %f" % p.voxel_size + " -trsf-type %s -py-hl %d -py-ll %d" % ( p.trsf_type, p.registration_depth_start, p.registration_depth_end, ) + res_trsf + ( " -elastic-sigma {s:.1f} {s:.1f} {s:.1f} " + " -fluid-sigma {s:.1f} {s:.1f} {s:.1f}" ).format(s=p.sigma) + th, shell=True, ) def run_produce_trsf(self, p: trsf_parameters): """ Parallel processing of the transformations from t to t-1/t+1 to t (depending on t<r) The transformation is computed using blockmatching algorithm Args: p (trsf_paraneters): a trsf_parameter object """ mapping = [ (p, t1, t2, not (t1 in p.not_to_do or t2 in p.not_to_do)) for t1, t2 in zip(p.to_register[:-1], p.to_register[1:]) ] tic = time() tmp = [] for mi in mapping: tmp += [self.__produce_trsf(mi)] tac = time() whole_time = tac - tic secs = whole_time % 60 whole_time = whole_time // 60 mins = whole_time % 60 hours = whole_time // 60 print("%dh:%dmin:%ds" % (hours, mins, secs)) def compose_trsf( self, flo_t: int, ref_t: int, trsf_p: str, tp_list: List[int] ) -> str: """ Recusrively build the transformation that allows to register time `flo_t` onto the frame of time `ref_t` assuming that it exists the necessary intermediary transformations Args: flo_t (int): time of the floating image ref_t (int): time of the reference image trsf_p (str): path to folder containing the transformations tp_list (list): list of time points that have been processed Returns: out_trsf (str): path to the result composed transformation """ out_trsf = trsf_p + "t%06d-%06d.txt" % (flo_t, ref_t) if not os.path.exists(out_trsf): flo_int = tp_list[tp_list.index(flo_t) + np.sign(ref_t - flo_t)] # the call is recursive, to build `T_{flo\leftarrow ref}` # we need `T_{flo+1\leftarrow ref}` and `T_{flo\leftarrow ref-1}` trsf_1 = self.compose_trsf(flo_int, ref_t, trsf_p, tp_list) trsf_2 = self.compose_trsf(flo_t, flo_int, trsf_p, tp_list) call( self.path_to_bin + "composeTrsf " + out_trsf + " -trsfs " + trsf_2 + " " + trsf_1, shell=True, ) return out_trsf @staticmethod def __lowess_smooth( X: np.ndarray, T: np.ndarray, frac: float ) -> np.ndarray: """ Smooth a curve using the lowess algorithm. See: Cleveland, W.S. (1979) “Robust Locally Weighted Regression and Smoothing Scatterplots”. Journal of the American Statistical Association 74 (368): 829-836. Args: X (np.ndarray): 1D array for the point positions T (np.ndarray): 1D array for the times corresponding to the `X` positions frac (float): Between 0 and 1. The fraction of the data used when estimating each value within X Returns: (np.ndarray): the smoothed X values """ return lowess(X, T, frac=frac, is_sorted=True, return_sorted=False) @staticmethod def interpolation( p: trsf_parameters, X: np.ndarray, T: np.ndarray ) -> np.ndarray: """ Interpolate positional values between missing timepoints using spline interplolation Args: p (trsf_parameters): parameters for the function X (np.ndarray): 1D array for the point positions T (np.ndarray): 1D array for the times corresponding to the `X` position Returns: (np.ndarray): The interoplated function """ return sp.interpolate.InterpolatedUnivariateSpline(T, X, k=p.spline) @classmethod def read_param_file(clf, p_param: str = None) -> List[trsf_parameters]: """ Asks for, reads and formats the parameter file Args: p_params (str | None): path to the json parameter files. It can either be a json or a folder containing json files. If it is None (default), a path is asked to the user. Returns: (list): list of `trsf_parameters` objects """ if not isinstance(p_param, dict): if p_param is None: if len(sys.argv) < 2 or sys.argv[1] == "-f": p_param = input( "\nPlease inform the path to the json config file:\n" ) else: p_param = sys.argv[1] stable = False or isinstance(p_param, Path) while not stable: tmp = p_param.strip('"').strip("'").strip(" ") stable = tmp == p_param p_param = tmp if os.path.isdir(p_param): f_names = [ os.path.join(p_param, f) for f in os.listdir(p_param) if ".json" in f and not "~" in f ] else: f_names = [p_param] else: f_names = [p_param] params = [] for file_name in f_names: if isinstance(file_name, str): print("") print("Extraction of the parameters from file %s" % file_name) p = trsf_parameters(file_name) if not p.check_parameters_consistancy(): print("\n%s Failed the consistancy check, it will be skipped") else: params += [p] print("") return params @staticmethod def prepare_paths(p: trsf_parameters): """ Prepare the paths in a format that is usable by the algorithm Args: p (trsf_parameters): parameter object """ image_formats = [ ".tiff", ".tif", ".inr", ".gz", ".klb", ".h5", ".hdf5", ] ### Check the file names and folders: p.im_ext = p.file_name.split(".")[-1] # Image type p.A0 = os.path.join(p.path_to_data, p.file_name) # Image path # Output format if p.output_format is not None: # If the output format is a file alone if os.path.split(p.output_format)[0] == "": p.A0_out = os.path.join(p.path_to_data, p.output_format) # If the output format is a folder alone elif not os.path.splitext(p.output_format)[-1] in image_formats: p.A0_out = os.path.join(p.output_format, p.file_name) else: p.A0_out = p.output_format else: p.A0_out = os.path.join( p.path_to_data, p.file_name.replace(p.im_ext, p.suffix + "." + p.im_ext), ) # Time points to work with p.time_points = np.array( [i for i in np.arange(p.first, p.last + 1) if not i in p.not_to_do] ) if p.check_TP: missing_time_points = [] for t in p.time_points: if not os.path.exists(p.A0.format(t=t)): missing_time_points += [t] if len(missing_time_points) != 0: print("The following time points are missing:") print("\t" + missing_time_points) print("Aborting the process") exit() if not p.sequential: p.ref_path = p.A0.format(t=p.ref_TP) if p.apply_trsf: for t in sorted(p.time_points): folder_tmp = os.path.split(p.A0_out.format(t=t))[0] if not os.path.exists(folder_tmp): os.makedirs(folder_tmp) max_t = max(p.time_points) if p.trsf_interpolation: p.to_register = sorted(p.time_points)[:: p.step_size] if not max_t in p.to_register: p.to_register += [max_t] else: p.to_register = p.time_points if not hasattr(p, "bdv_im") or p.bdv_im is None: p.bdv_im = p.A0 if not hasattr(p, "out_bdv") or p.out_bdv is None: p.out_bdv = os.path.join(p.trsf_folder, "bdv.xml") if p.bdv_voxel_size is None: p.bdv_voxel_size = p.voxel_size def lowess_filter(self, p: trsf_parameters, trsf_fmt: str) -> str: """ Apply a lowess filter on a set of ordered transformations (only works for translations). It does it from already computed transformations and write new transformations on disk. Args: p (trsf_parameters): parameter object trsf_fmt (srt): the string format for the initial transformations Returns: (str): output transformation string """ X_T = [] Y_T = [] Z_T = [] T = [] for t in p.to_register: trsf_p = p.trsf_folder + trsf_fmt.format(flo=t, ref=p.ref_TP) trsf = self.read_trsf(trsf_p) T += [t] X_T += [trsf[0, -1]] Y_T += [trsf[1, -1]] Z_T += [trsf[2, -1]] frac = float(p.window_size) / len(T) X_smoothed = self.__lowess_smooth(p, X_T, T, frac=frac) Y_smoothed = self.__lowess_smooth(p, Y_T, T, frac=frac) Z_smoothed = self.__lowess_smooth(p, Z_T, T, frac=frac) new_trsf_fmt = "t{flo:06d}-{ref:06d}-filtered.txt" for i, t in enumerate(T): mat = np.identity(4) mat[0, -1] = X_smoothed[i] mat[1, -1] = Y_smoothed[i] mat[2, -1] = Z_smoothed[i] np.savetxt( p.trsf_folder + new_trsf_fmt.format(flo=t, ref=p.ref_TP), mat ) return new_trsf_fmt def interpolate( self, p: trsf_parameters, trsf_fmt: str, new_trsf_fmt: str = None ) -> str: """ Interpolate a set of ordered transformations (only works for translations). It does it from already computed transformations and write new transformations on disk. Args: p (trsf_parameters): parameter object trsf_fmt (srt): the string format for the initial transformations new_trsf_fmt (str | None): path to the interpolated transformations. If None, the format will be "t{flo:06d}-{ref:06d}-interpolated.txt" Returns: (str): output transformation format """ if new_trsf_fmt is None: new_trsf_fmt = "t{flo:06d}-{ref:06d}-interpolated.txt" X_T = [] Y_T = [] Z_T = [] T = [] for t in p.to_register: trsf_p = os.path.join( p.trsf_folder, trsf_fmt.format(flo=t, ref=p.ref_TP) ) trsf = self.read_trsf(trsf_p) T += [t] X_T += [trsf[0, -1]] Y_T += [trsf[1, -1]] Z_T += [trsf[2, -1]] X_interp = self.interpolation(p, X_T, T) Y_interp = self.interpolation(p, Y_T, T) Z_interp = self.interpolation(p, Z_T, T) for t in p.time_points: mat = np.identity(4) mat[0, -1] = X_interp(t) mat[1, -1] = Y_interp(t) mat[2, -1] = Z_interp(t) np.savetxt( os.path.join( p.trsf_folder, new_trsf_fmt.format(flo=t, ref=p.ref_TP), mat, ) ) trsf_fmt = new_trsf_fmt return trsf_fmt @staticmethod def pad_trsfs(p: trsf_parameters, trsf_fmt: str): """ Pad transformations Args: p (trsf_parameters): parameter object trsf_fmt (srt): the string format for the initial transformations """ if not p.sequential and p.ref_path.split(".")[-1] == "klb": im_shape = readheader(p.ref_path)["imagesize_tczyx"][-1:-4:-1] elif not p.sequential: im_shape = imread(p.ref_path).shape elif p.A0.split(".")[-1] == "klb": im_shape = readheader(p.A0.format(t=p.ref_TP))["imagesize_tczyx"][ -1:-4:-1 ] else: im_shape = imread(p.A0.format(t=p.ref_TP)).shape im = SpatialImage(np.ones(im_shape), dtype=np.uint8) im.voxelsize = p.voxel_size if pyklb_found: template = os.path.join(p.trsf_folder, "tmp.klb") res_t = "template.klb" else: template = os.path.join(p.trsf_folder, "tmp.tif") res_t = "template.tif" imsave(template, im) identity = np.identity(4) trsf_fmt_no_flo = trsf_fmt.replace("{flo:06d}", "%06d") new_trsf_fmt = "t{flo:06d}-{ref:06d}-padded.txt" new_trsf_fmt_no_flo = new_trsf_fmt.replace("{flo:06d}", "%06d") for t in p.not_to_do: np.savetxt( os.path.join( p.trsf_folder, trsf_fmt.format(flo=t, ref=p.ref_TP), identity, ) ) call( p.path_to_bin + "changeMultipleTrsfs -trsf-format " + os.path.join(p.trsf_folder, trsf_fmt_no_flo.format(ref=p.ref_TP)) + " -index-reference %d -first %d -last %d " % (p.ref_TP, min(p.time_points), max(p.time_points)) + " -template " + template + " -res " + os.path.join( p.trsf_folder, new_trsf_fmt_no_flo.format(ref=p.ref_TP) ) + " -res-t " + os.path.join(p.trsf_folder, res_t) + " -trsf-type %s -vs %f %f %f" % ((p.trsf_type,) + p.voxel_size), shell=True, ) def compute_trsfs(self, p: trsf_parameters): """ Compute all the transformations from a given set of parameters Args: p (trsf_parameters): Parameter object """ # Create the output folder for the transfomrations if not os.path.exists(p.trsf_folder): os.makedirs(p.trsf_folder) trsf_fmt = "t{flo:06d}-{ref:06d}.txt" try: self.run_produce_trsf(p) if p.sequential: if min(p.to_register) != p.ref_TP: self.compose_trsf( min(p.to_register), p.ref_TP, p.trsf_folder, list(p.to_register), ) if max(p.to_register) != p.ref_TP: self.compose_trsf( max(p.to_register), p.ref_TP, p.trsf_folder, list(p.to_register), ) np.savetxt( os.path.join("{:s}", trsf_fmt).format( p.trsf_folder, flo=p.ref_TP, ref=p.ref_TP ), np.identity(4), ) except Exception as e: print(p.trsf_folder) print(e) if p.lowess: trsf_fmt = self.lowess_filter(p, trsf_fmt) if p.trsf_interpolation: trsf_fmt = interpolate(p, trsf_fmt) if p.padding: self.pad_trsfs(p, trsf_fmt) @staticmethod def apply_trsf(p: trsf_parameters): """ Apply transformations to a movie from a set of computed transformations Args: p (trsf_parameters): Parameter object """ trsf_fmt = "t{flo:06d}-{ref:06d}.txt" if p.lowess: trsf_fmt = "t{flo:06d}-{ref:06d}-filtered.txt" if p.trsf_interpolation: trsf_fmt = "t{flo:06d}-{ref:06d}-interpolated.txt" if p.padding: trsf_fmt = "t{flo:06d}-{ref:06d}-padded.txt" if pyklb_found: template = os.path.join(p.trsf_folder, "template.klb") X, Y, Z = readheader(template)["imagesize_tczyx"][-1:-4:-1] else: template = os.path.join(p.trsf_folder, "template.tif") X, Y, Z = imread(template).shape elif p.A0.split(".")[-1] == "klb": X, Y, Z = readheader(p.A0.format(t=p.ref_TP))["imagesize_tczyx"][ -1:-4:-1 ] template = p.A0.format(t=p.ref_TP) else: X, Y, Z = imread(p.A0.format(t=p.ref_TP)).shape template = p.A0.format(t=p.ref_TP) if p.voxel_size != p.voxel_size_out: before, after = os.path.splitext(template) old_template = template template = "".join((before, ".final_template", after)) call( p.path_to_bin + f"applyTrsf {old_template} {template} " + "-vs %f %f %f" % p.voxel_size_out, shell=True, ) X, Y, Z = imread(template).shape xy_proj = np.zeros((X, Y, len(p.time_points)), dtype=np.uint16) xz_proj = np.zeros((X, Z, len(p.time_points)), dtype=np.uint16) yz_proj = np.zeros((Y, Z, len(p.time_points)), dtype=np.uint16) for i, t in enumerate(sorted(p.time_points)): folder_tmp = os.path.split(p.A0_out.format(t=t))[0] if not os.path.exists(folder_tmp): os.makedirs(folder_tmp) call( p.path_to_bin + "applyTrsf %s %s -trsf " % (p.A0.format(t=t), p.A0_out.format(t=t)) + os.path.join( p.trsf_folder, trsf_fmt.format(flo=t, ref=p.ref_TP) ) + " -template " + template + " -floating-voxel %f %f %f " % p.voxel_size + " -reference-voxel %f %f %f " % p.voxel_size_out + " -interpolation %s" % p.image_interpolation, shell=True, ) try: im = imread(p.A0_out.format(t=t)) except Exception as e: # print("applyTrsf failed at t=",str(t),", retrying now") call( p.path_to_bin + "applyTrsf %s %s -trsf " % (p.A0.format(t=t), p.A0_out.format(t=t)) + os.path.join( p.trsf_folder, trsf_fmt.format(flo=t, ref=p.ref_TP) ) + " -template " + template + " -floating-voxel %f %f %f " % p.voxel_size + " -reference-voxel %f %f %f " % p.voxel_size_out + " -interpolation %s" % p.image_interpolation, shell=True, ) im = imread(p.A0_out.format(t=t)) if p.projection_path is not None: xy_proj[..., i] = SpatialImage(np.max(im, axis=2)) xz_proj[..., i] = SpatialImage(np.max(im, axis=1)) yz_proj[..., i] = SpatialImage(np.max(im, axis=0)) if p.projection_path is not None: if not os.path.exists(p.projection_path): os.makedirs(p.projection_path) p_to_data = p.projection_path num_s = p.file_name.find("{") num_e = p.file_name.find("}") + 1 f_name = p.file_name.replace(p.file_name[num_s:num_e], "") if not os.path.exists(p_to_data.format(t=-1)): os.makedirs(p_to_data.format(t=-1)) imsave( os.path.join( p_to_data, f_name.replace(p.im_ext, "xyProjection.tif") ), SpatialImage(xy_proj), ) imsave( os.path.join( p_to_data, f_name.replace(p.im_ext, "xzProjection.tif") ), SpatialImage(xz_proj), ) imsave( os.path.join( p_to_data, f_name.replace(p.im_ext, "yzProjection.tif") ), SpatialImage(yz_proj), ) @staticmethod def inv_trsf(trsf: np.ndarray) -> np.ndarray: """ Inverse a transformation Args: trsf (np.ndarray): 4x4 transformation matrix Returns (np.ndarray): the inverse of the input transformation """ return np.linalg.lstsq(trsf, np.identity(4))[0] @staticmethod def prettify(elem: ET.Element) -> str: """ Return a pretty-printed XML string for the Element. Args: elem (xml.etree.ElementTree.Element): xml element Returns: (str): a nice version of our xml file """ rough_string = ET.tostring(elem, "utf-8") reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") @staticmethod def do_viewSetup( ViewSetup: ET.SubElement, p: trsf_parameters, im_size: Tuple[int, int, int], i: int, ): """ Setup xml elements for BigDataViewer Args: ViewSetup (ET.SubElement): ... p (trsf_parameters): Parameter object im_size (tuple): tuple of 3 integers with the dimension of the image i (int): angle id """ id_ = ET.SubElement(ViewSetup, "id") id_.text = "%d" % i name = ET.SubElement(ViewSetup, "name") name.text = "%d" % i size = ET.SubElement(ViewSetup, "size") size.text = "%d %d %d" % tuple(im_size) voxelSize = ET.SubElement(ViewSetup, "voxelSize") unit = ET.SubElement(voxelSize, "unit") unit.text = p.bdv_unit size = ET.SubElement(voxelSize, "size") size.text = "%f %f %f" % tuple(p.bdv_voxel_size) attributes = ET.SubElement(ViewSetup, "attributes") illumination = ET.SubElement(attributes, "illumination") illumination.text = "0" channel = ET.SubElement(attributes, "channel") channel.text = "0" tile = ET.SubElement(attributes, "tile") tile.text = "0" angle = ET.SubElement(attributes, "angle") angle.text = "%d" % i def do_ViewRegistration( self, ViewRegistrations: ET.SubElement, p: trsf_parameters, t: int, a: int, ): """ Write the view registration for BigDataViewer Args: ViewSetup (ET.SubElement): ... p (trsf_parameters): Parameter object t (int): time point to treat a (int): angle to treat (useless for time regisrtation) """ ViewRegistration = ET.SubElement(ViewRegistrations, "ViewRegistration") ViewRegistration.set("timepoint", "%d" % t) ViewRegistration.set("setup", "0") ViewTransform = ET.SubElement(ViewRegistration, "ViewTransform") ViewTransform.set("type", "affine") affine = ET.SubElement(ViewTransform, "affine") f = os.path.join(p.trsf_folder, "t%06d-%06d.txt" % (t, p.ref_TP)) trsf = self.read_trsf(f) trsf = self.inv_trsf(trsf) formated_trsf = tuple(trsf[:-1, :].flatten()) affine.text = ("%f " * 12) % formated_trsf ViewTransform = ET.SubElement(ViewRegistration, "ViewTransform") ViewTransform.set("type", "affine") affine = ET.SubElement(ViewTransform, "affine") affine.text = ( "%f 0.0 0.0 0.0 0.0 %f 0.0 0.0 0.0 0.0 %f 0.0" % p.voxel_size ) def build_bdv(self, p: trsf_parameters): """ Build the BigDataViewer xml Args: p (trsf_parameters): Parameter object """ if not p.im_ext in ["klb"]: # ['tif', 'klb', 'tiff']: print("Image format not adapted for BigDataViewer") return SpimData = ET.Element("SpimData") SpimData.set("version", "0.2") SpimData.set("encoding", "UTF-8") base_path = ET.SubElement(SpimData, "BasePath") base_path.set("type", "relative") base_path.text = "." SequenceDescription = ET.SubElement(SpimData, "SequenceDescription") ImageLoader = ET.SubElement(SequenceDescription, "ImageLoader") ImageLoader.set("format", p.im_ext) Resolver = ET.SubElement(ImageLoader, "Resolver") Resolver.set( "type", "org.janelia.simview.klb.bdv.KlbPartitionResolver" ) ViewSetupTemplate = ET.SubElement(Resolver, "ViewSetupTemplate") template = ET.SubElement(ViewSetupTemplate, "template") template.text = p.bdv_im.format(t=p.to_register[0]) timeTag = ET.SubElement(ViewSetupTemplate, "timeTag") timeTag.text = p.time_tag ViewSetups = ET.SubElement(SequenceDescription, "ViewSetups") ViewSetup = ET.SubElement(ViewSetups, "ViewSetup") if p.im_ext == "klb": im_size = tuple( readheader(p.A0.format(t=p.ref_TP))["imagesize_tczyx"][ -1:-4:-1 ] ) else: im_size = tuple(imread(p.A0.format(t=p.ref_TP)).shape) self.do_viewSetup(ViewSetup, p, im_size, 0) Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "illumination") Illumination = ET.SubElement(Attributes, "Illumination") id_ = ET.SubElement(Illumination, "id") id_.text = "0" name = ET.SubElement(Illumination, "name") name.text = "0" Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "channel") Channel = ET.SubElement(Attributes, "Channel") id_ = ET.SubElement(Channel, "id") id_.text = "0" name = ET.SubElement(Channel, "name") name.text = "0" Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "tile") Tile = ET.SubElement(Attributes, "Tile") id_ = ET.SubElement(Tile, "id") id_.text = "0" name = ET.SubElement(Tile, "name") name.text = "0" Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "angle") Angle = ET.SubElement(Attributes, "Angle") id_ = ET.SubElement(Angle, "id") id_.text = "0" name = ET.SubElement(Angle, "name") name.text = "0" TimePoints = ET.SubElement(SequenceDescription, "Timepoints") TimePoints.set("type", "range") first = ET.SubElement(TimePoints, "first") first.text = "%d" % min(p.to_register) last = ET.SubElement(TimePoints, "last") last.text = "%d" % max(p.to_register) ViewRegistrations = ET.SubElement(SpimData, "ViewRegistrations") b = min(p.to_register) e = max(p.to_register) for t in range(b, e + 1): self.do_ViewRegistration(ViewRegistrations, p, t) with open(p.out_bdv, "w") as f: f.write(self.prettify(SpimData)) f.close() def plot_transformations(self, p: trsf_parameters): trsf_fmt = "t{flo:06d}-{ref:06d}.txt" if p.lowess: trsf_fmt = "t{flo:06d}-{ref:06d}-filtered.txt" if p.trsf_interpolation: trsf_fmt = "t{flo:06d}-{ref:06d}-interpolated.txt" if p.padding: trsf_fmt = "t{flo:06d}-{ref:06d}-padded.txt" import matplotlib.pyplot as plt tX, tY, tZ = [], [], [] rX, rY, rZ = [], [], [] for t in sorted(p.time_points): trsf = self.read_trsf( os.path.join( p.trsf_folder, trsf_fmt.format(flo=t, ref=p.ref_TP) ) ) (tx, ty, tz), M, *_ = decompose(trsf) rx, ry, rz = mat2euler(M) tX.append(tx) tY.append(ty) tZ.append(tz) rX.append(np.rad2deg(rx)) rY.append(np.rad2deg(ry)) rZ.append(np.rad2deg(rz)) fig, ax = plt.subplots(3, 1, figsize=(8, 5), sharex=True, sharey=True) ax[0].plot(p.time_points, tX, "o-") ax[1].plot(p.time_points, tY, "o-") ax[2].plot(p.time_points, tZ, "o-") for axis, axi in zip(["X", "Y", "Z"], ax): axi.set_ylabel(f"{axis} Translation [µm]") ax[2].set_xlabel("Time") fig.suptitle("Translations") fig.tight_layout() fig, ax = plt.subplots(3, 1, figsize=(8, 5), sharex=True, sharey=True) ax[0].plot(p.time_points, rX, "o-") ax[1].plot(p.time_points, rY, "o-") ax[2].plot(p.time_points, rZ, "o-") for axis, axi in zip(["X", "Y", "Z"], ax): axi.set_ylabel(f"{axis} Rotation\nin degree") ax[2].set_xlabel("Time") fig.suptitle("Rotations") fig.tight_layout() plt.show() def run_trsf(self): """ Start the Spatial registration after having informed the parameter files """ for p in self.params: try: print("Starting experiment") print(p) self.prepare_paths(p) if p.compute_trsf: self.compute_trsfs(p) if p.plot_trsf: self.plot_transformations(p) if p.apply_trsf and p.trsf_type != "vectorfield": self.apply_trsf(p) if p.do_bdv: self.build_bdv(p) except Exception as e: print("Failure of %s" % p.origin_file_name) print(e) def __init__(self, params=None): if params is None: self.params = self.read_param_file() elif ( isinstance(params, str) or isinstance(params, Path) or isinstance(params, dict) ): self.params = TimeRegistration.read_param_file(params) else: self.params = params if self.params is not None and 0 < len(self.params): self.path_to_bin = self.params[0].path_to_bin def time_registration(): reg = TimeRegistration() reg.run_trsf()
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/registrationtools/time_registration.py
time_registration.py
import tifffile import os import registrationtools import json import numpy as np from glob import glob from ensure import check ##need to pip install ! from pathlib import Path def get_paths() : #Ask the user for the folder containing his data, find the movies is they are in tiff format and put them in a list after confirmation path_correct=False while path_correct==False : path_folder = input('Path to the folder of the movie(s) (in tiff format only) : \n ') paths_movies = sorted(glob(rf'{path_folder}/*.tif')) if len(paths_movies) > 0 : print('You have',len(paths_movies),'movie(s), which is (are) : ') for path_movie in paths_movies : print('',Path(path_movie).stem) #the empty str at the begining is to align the answers one space after the questions, for readability path_correct = int(input('Correct ? (1 for yes, 0 for no) \n ')) else : print('There is no tiff file in the folder. \n') return (paths_movies) def dimensions(list_paths:list) : # Take the path to the data and returns its size in the dimensions CTZXY. Raise error if the other movies do not have the same C ot T dimensions. movie = tifffile.imread(list_paths[0]) name_movie = Path(list_paths[0]).stem dim_correct = False while dim_correct == False : print('\nThe dimensions of ',name_movie, 'are ',movie.shape,'. \n') dimensions=input('What is the order of the dimensions (for example TZCYX or XYZT) ? T stands for Time, C for channels if your image has multiple channels, Z for depth (or number or plans) and XY is your field of view. \n ') sorted_axes = sorted(dimensions) if ''.join(sorted_axes) == "CTXYZ": number_channels = movie.shape[dimensions.find('C')] dim_correct=True elif ''.join(sorted_axes) == "TXYZ": number_channels = 1 dim_correct=True elif len(sorted_axes) != len(movie.shape) : print('Error : Number of dimensions is incorrect. \n') dim_correct = False else: print(' \n The letters you choose has to be among these letters : X,Y,Z,C,T, with XYZT mandatory, and no other letters are allowed. \nEvery letter can be included only once. \n') number_timepoints = movie.shape[dimensions.find('T')] if 'C' in dimensions : number_channels = movie.shape[dimensions.find('C')] else : number_channels = 1 if dim_correct == True : depth = movie.shape[dimensions.find('Z')] size_X = movie.shape[dimensions.find('X')] size_Y = movie.shape[dimensions.find('Y')] print('\nSo',name_movie, 'has',number_channels,'channels, ',number_timepoints,'timepoints, the depth in z is',depth,'pixels and the XY plane measures ',size_X,'x',size_Y,'pixels.') dim_correct = int(input('Correct ? (1 for yes, 0 for no) \n ')) #checking if the movies have the same dimensions in C and T, otherwise the registration cannot be computed. if 'C' in dimensions : #have to check beforehand if multichannels, otherwise, dimensions.find('C') will return -1 and mov.shape[dimensions.find('C')] will probably return the dimension of the X axis for path in list_paths : mov = tifffile.imread(path) check(mov.shape[dimensions.find('T')]).equals(number_timepoints).or_raise(Exception, 'These movies do not all have the same number of timepoints. \n') check(mov.shape[dimensions.find('C')]).equals(number_channels).or_raise(Exception, 'These movies do not all have the same number of channels. \n') #if XYZ are not the same thats ok ? return(number_channels,number_timepoints,depth,size_X,size_Y) def get_channels_name(number_channels:int) : #Ask for the name of the channels, return a list of str containing all the channels channels=[] if number_channels == 1: ch = str(input('Name of the channel : \n ')) channels.append(ch) else : #if multichannels for n in range(number_channels) : ch = str(input('Name of channel n°'+str(n+1) +' : \n ')) channels.append(ch) return(channels) def reference_channel(channels:list) : #Ask for the reference channel among the channels given (with safety check) if len(channels) == 1 : ch_ref=channels[0] else : channel_correct=False print('\nAmong the channels'+ str(channels)+', you need a reference channel to compute the registration. A good option is generally a marker that is expressed ubiquitously\n') while channel_correct==False : ch_ref = input('Name of the reference channel : \n ') if ch_ref not in channels : print('The reference channel is not in', channels,'(do not put any other character than the name itself)') channel_correct=False else : channel_correct=True channels_float=channels.copy() channels_float.remove(ch_ref) return(channels_float,ch_ref) def sort_by_channels_and_timepoints(list_paths:str,channels:str,number_timepoints:int): #Take a list of movies and cut them into a timesequence of 3D stacks, one timesequence per channel. Works for one channel or multiple channels. for path in list_paths : for n in range(len(channels)) : name_movie = Path(path).stem directory = name_movie+'_'+channels[n] cut_timesequence(path_to_movie = path, directory=directory, ind_current_channel=n, number_timepoints = number_timepoints, number_channels = len(channels)) def cut_timesequence (path_to_movie:str, directory:str, ind_current_channel:int, number_timepoints:int,number_channels:int): #take a movie and cut it into a timesequence in the given directory. Creates the folder structure for the registration. movie = tifffile.imread(path_to_movie) position_t = np.argwhere(np.array(movie.shape)==number_timepoints)[0][0] movie=np.moveaxis(movie,source=position_t,destination=0) #i did not test this path_to_data=os.path.dirname(path_to_movie) path_dir = rf'{path_to_data}\{directory}' check(os.path.isdir(path_dir)).is_(False).or_raise(Exception,"Please delete the folder "+directory+" and run again.") os.mkdir(os.path.join(path_to_data,directory)) os.mkdir(os.path.join(path_to_data+'/'+directory,"trsf")) os.mkdir(os.path.join(path_to_data+'/'+directory,"output")) os.mkdir(os.path.join(path_to_data+'/'+directory,"proj_output")) os.mkdir(os.path.join(path_to_data+'/'+directory,"stackseq")) if number_channels >1 : position_c = np.argwhere(np.array(movie.shape)==number_channels)[0][0] movie=np.moveaxis(movie,source=position_c,destination=2) #we artificially change to the format TZCXY (reference in Fiji). Its just to cut into timesequence. does not modify the data for t in range(number_timepoints) : stack = movie[t,:,ind_current_channel,:,:] tifffile.imwrite(path_to_data+'/'+directory+"/stackseq/movie_t"+str(format(t,'03d')+'.tif'),stack) else : for t in range(number_timepoints) : stack = movie[t,:,:,:] tifffile.imwrite(path_to_data+'/'+directory+"/stackseq/movie_t"+str(format(t,'03d')+'.tif'),stack) def get_voxel_sizes() : #ask the user for the voxel size of his input and what voxel size does he want in output. Returns 2 tuples for this values. print('\nTo register properly, you need to specify the voxel size of your input image. This can be found in Fiji, Image>Show Info. ') print('Voxel size of your original image (XYZ successively) :\n ') x= float(input('X :')) y= float(input('Y :')) z= float(input('Z :')) voxel_size_input = [x,y,z] print('Initial voxel size =',voxel_size_input) change_voxel_size = int(input(' \nYou can choose to have another voxel size on the registered image , for example to have an isotropic output image (voxel size [1,1,1]), Or you can also choose to keep the same voxel size. \nDo you want to change the voxel size of your movies ? (1 for yes, 0 for no) : \n ')) if change_voxel_size==1 : print('\nVoxel size of your image after transformation (XYZ): \n ') x= float(input('X :')) y= float(input('Y :')) z= float(input('Z :')) voxel_size_output = [x,y,z] elif change_voxel_size==0 : voxel_size_output = voxel_size_input print('\nVoxel size after transformation =',voxel_size_output) return(voxel_size_input,voxel_size_output) def get_trsf_type() : #Ask for what transformation the user want and return a string list_trsf_types = ['rigid2D','rigid3D','translation2D','translation3D'] #needs to be completed print('\nYou can choose to apply different transformation types depending on your data : ',list_trsf_types) trsf_correct = False while trsf_correct == False : trsf_type = str(input('\nWhich one do you want to use ? (please enter the name of the transformation only, no other character) \n ')) if trsf_type in list_trsf_types : trsf_correct = True else : print(('You can only choose a transformation that is in this list :',list_trsf_types)) return(trsf_type) def data_preparation() : #Gather all the functions asking the user for the parameters. Returns the useful ones for registration (not XYZ size and channels list) list_paths = get_paths() number_channels,number_timepoints,depth,size_X,size_Y = dimensions(list_paths) channels=get_channels_name(number_channels) channels_float,ch_ref = reference_channel(channels) sort_by_channels_and_timepoints(list_paths = list_paths, channels = channels, number_timepoints = number_timepoints) voxel_size_input, voxel_size_output = get_voxel_sizes() trsf_type = get_trsf_type() return(list_paths, number_timepoints, channels_float,ch_ref, voxel_size_input, voxel_size_output, trsf_type) def run_registration (list_paths:list,channels_float:list, ch_ref:str, voxel_size_input:tuple, voxel_size_output:tuple, trsf_type:str) : #Does the actual registration : Take the reference channel first to compute and apply the trsf, then loop on the float channels and only apply it for path in list_paths : json_string=[] folder=os.path.dirname(path) name_movie = Path(path).stem movie = tifffile.imread(path) directory = name_movie+'_'+ch_ref data_ref = { "path_to_data": rf'{folder}/{directory}/stackseq/', "file_name": "movie_t{t:03d}.tif", "trsf_folder": rf'{folder}/{directory}/trsf/', "output_format": rf'{folder}/{directory}/output/', "projection_path":rf'{folder}/{directory}/proj_output/', "check_TP": 0, "voxel_size": voxel_size_input, "voxel_size_out" : voxel_size_output, "first": 0, "last": movie.shape[0]-1, "not_to_do": [], "compute_trsf": 1, "ref_TP": int(movie.shape[0]/2), "trsf_type": trsf_type, "padding": 1, "recompute": 1, "apply_trsf":1, "out_bdv": "", "plot_trsf":0 } json_string.append(json.dumps(data_ref)) tr = registrationtools.TimeRegistration(data_ref) tr.run_trsf() #registration rest of the channels for c in channels_float : directory = name_movie+'_'+c data_float = { "path_to_data": rf'{folder}/{directory}/stackseq/', "file_name": "movie_t{t:03d}.tif", "trsf_folder": rf'{folder}/{name_movie}_{ch_ref}/trsf/', "output_format": rf'{folder}/{directory}/output/', "projection_path":rf'{folder}/{directory}/proj_output/', "check_TP": 0, "voxel_size": voxel_size_input, "voxel_size_out" : voxel_size_output, "first": 0, "last": movie.shape[0]-1, "not_to_do": [], "compute_trsf": 0, "ref_TP": int(movie.shape[0]/2), "trsf_type": trsf_type, "padding": 1, "recompute": 1, "apply_trsf":1, "out_bdv": "", "plot_trsf":0 } json_string.append(json.dumps(data_float)) tr = registrationtools.TimeRegistration(data_float) tr.run_trsf() return(json_string) def save_sequences_as_stacks(list_paths:list,channels:list,number_timepoints:int) : #save the timesequence as a hyperstack for path in list_paths : path_to_data=os.path.dirname(path) name_movie = Path(path).stem movie = tifffile.imread(path) stack0 =tifffile.imread(rf"{path_to_data}/{name_movie}_{channels[0]}/output/movie_t000.tif") #we use the first image (3D) to know the dimensions registered_movie = np.zeros((number_timepoints,stack0.shape[0],len(channels),stack0.shape[1],stack0.shape[2]),dtype=np.float32) #one movie per channel, of format (t,z,y,x).Datatype uint16 or float32 is necessary to export as hyperstack for ind_c,c in enumerate(channels) : directory = name_movie+'_'+c for t in range(movie.shape[0]) : stack =tifffile.imread(rf"{path_to_data}/{directory}/output/movie_t{format(t,'03d')}.tif") #we take each stack in a given timepoint registered_movie[t,:,ind_c,:,:]=stack #and put it in a new hyperstack tifffile.imwrite(path_to_data+rf"/{name_movie}_registered.tif",registered_movie.astype(np.float32),imagej=True) #write a hyperstack in the main folder print('saved registered', name_movie, 'of size', registered_movie.shape) def save_jsonfile(list_paths,json_string): path_to_data = os.dirname(list_paths[0]) keep_same_dir = int(input(str('Do you want to save your json files in the same master directory, in '+path_to_data+'\jsonfiles ? (1 for yes, 0 for no)'))) if keep_same_dir ==1 : path_to_json = rf'{path_to_data}\jsonfiles' os.mkdir(os.path.join(path_to_data,'jsonfiles')) else : path_to_json = input('In which folder do you want to write your jsonfile ?').replace("\\", "/") #if single backslashes, fine. If double backslashes (when copy/paste the Windows path), compatibility problems, thats why we replace by single slashes.') print('saving',len(json_string),'json files :') for ind_json,json in enumerate(json_string) : with open(path_to_json+'\param'+str(ind_json)+'.json','w') as outfile : #maybe not the best name outfile.write(json) print(path_to_json) print('Done saving')
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/registrationtools/utils.py
utils.py
import numpy as np import os import sys import json from subprocess import call import xml.etree.ElementTree as ET from xml.dom import minidom from shutil import copyfile from pathlib import Path from typing import Union, List, Tuple from IO import imread, imsave, SpatialImage class trsf_parameters(object): """ Read parameters for the registration function from a preformated json file """ def check_parameters_consistancy(self) -> bool: """ Function that should check parameter consistancy @TODO: write something that actually do check """ correct = True if not ( hasattr(self, "out_pattern") or hasattr(self, "output_format") ): print("The output pattern cannot be an empty string") correct = False return correct def __str__(self) -> str: max_key = ( max([len(k) for k in self.__dict__.keys() if k != "param_dict"]) + 1 ) output = "The registration will run with the following arguments:\n" output += "\n" + " File format \n" output += "path_to_data".ljust(max_key, " ") + ": {:s}\n".format( self.path_to_data ) output += "ref_im".ljust(max_key, " ") + ": {:s}\n".format(self.ref_im) output += "flo_ims".ljust(max_key, " ") + ": " tmp_just_len = len("flo_ims".ljust(max_key, " ") + ": ") already = tmp_just_len + 1 for flo in self.flo_ims: output += (" " * (tmp_just_len - already)) + "{:s}\n".format(flo) already = 0 output += "init_trsfs".ljust(max_key, " ") + ": " tmp_just_len = len("init_trsfs".ljust(max_key, " ") + ": ") already = tmp_just_len + 1 for init_trsfs in self.init_trsfs: if init_trsfs is not None and 0 < len(init_trsfs): output += (" " * (tmp_just_len - already)) + "{}\n".format( init_trsfs ) already = 0 output += "trsf_types".ljust(max_key, " ") + ": " tmp_just_len = len("trsf_types".ljust(max_key, " ") + ": ") already = tmp_just_len + 1 for trsf_type in self.trsf_types: output += (" " * (tmp_just_len - already)) + "{:s}\n".format( trsf_type ) already = 0 output += "ref_voxel".ljust( max_key, " " ) + ": {:f} x {:f} x {:f}\n".format(*self.ref_voxel) output += "flo_voxels".ljust(max_key, " ") + ": " tmp_just_len = len("flo_voxels".ljust(max_key, " ") + ": ") already = tmp_just_len + 1 for flo_voxel in self.flo_voxels: output += ( " " * (tmp_just_len - already) ) + "{:f} x {:f} x {:f}\n".format(*flo_voxel) already = 0 output += "out_voxel".ljust( max_key, " " ) + ": {:f} x {:f} x {:f}\n".format(*self.out_voxel) output += "out_pattern".ljust(max_key, " ") + ": {:s}\n".format( self.out_pattern ) return output def add_path_prefix(self, prefix: str): """ Add a prefix to all the relevant paths (this is mainly for the unitary tests) Args: prefix (str): The prefix to add in front of the path """ self.path_to_data = str(Path(prefix) / self.path_to_data) self.trsf_paths = [ str(Path(prefix) / trsf) for trsf in self.trsf_paths ] def __init__(self, file_name: str): if not isinstance(file_name, dict): with open(file_name) as f: param_dict = json.load(f) f.close() else: param_dict = {} for k, v in file_name.items(): if isinstance(v, Path): param_dict[k] = str(v) else: param_dict[k] = v # Default parameters self.param_dict = param_dict self.init_trsfs = [[], [], []] self.path_to_bin = "" self.registration_depth_start = 6 self.registration_depth_end = 3 self.init_trsf_real_unit = True self.image_interpolation = "linear" self.apply_trsf = True self.compute_trsf = True self.test_init = False self.begin = None self.end = None self.trsf_types = [] self.time_tag = None self.bdv_unit = "microns" self.bdv_voxel_size = None self.do_bdv = 0 self.flo_im_sizes = None self.copy_ref = False self.bbox_out = False if "registration_depth" in param_dict: self.__dict__["registration_depth_start"] = 6 self.__dict__["registration_depth_end"] = param_dict[ "registration_depth" ] elif not "registration_depth_start" in param_dict: self.__dict__["registration_depth_start"] = 6 self.__dict__["registration_depth_end"] = 3 self.__dict__.update(param_dict) self.ref_voxel = tuple(self.ref_voxel) self.flo_voxels = [tuple(vox) for vox in self.flo_voxels] self.out_voxel = tuple(self.out_voxel) self.origin_file_name = file_name self.path_to_bin = os.path.join(self.path_to_bin, "") if 0 < len(self.path_to_bin) and not os.path.exists(self.path_to_bin): print("Binary path could not be found, will try with global call") self.path_to_bin = "" class SpatialRegistration: @staticmethod def axis_rotation_matrix( axis: str, angle: float, min_space: Tuple[int, int, int] = None, max_space: Tuple[int, int, int] = None, ) -> np.ndarray: """Return the transformation matrix from the axis and angle necessary Args: axis (str): axis of rotation ("X", "Y" or "Z") angle (float) : angle of rotation (in degree) min_space (tuple(int, int, int)): coordinates of the bottom point (usually (0, 0, 0)) max_space (tuple(int, int, int)): coordinates of the top point (usually im shape) Returns: (ndarray): 4x4 rotation matrix """ import math I = np.linalg.inv D = np.dot if axis not in ["X", "Y", "Z"]: raise Exception(f"Unknown axis: {axis}") rads = math.radians(angle) s = math.sin(rads) c = math.cos(rads) centering = np.identity(4) if min_space is None and max_space is not None: min_space = np.array([0.0, 0.0, 0.0]) if max_space is not None: space_center = (max_space - min_space) / 2.0 offset = -1.0 * space_center centering[:3, 3] = offset rot = np.identity(4) if axis == "X": rot = np.array( [ [1.0, 0.0, 0.0, 0.0], [0.0, c, -s, 0.0], [0.0, s, c, 0.0], [0.0, 0.0, 0.0, 1.0], ] ) elif axis == "Y": rot = np.array( [ [c, 0.0, s, 0.0], [0.0, 1.0, 0.0, 0.0], [-s, 0.0, c, 0.0], [0.0, 0.0, 0.0, 1.0], ] ) elif axis == "Z": rot = np.array( [ [c, -s, 0.0, 0.0], [s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] ) return D(I(centering), D(rot, centering)) @staticmethod def flip_matrix(axis: str, im_size: tuple) -> np.ndarray: """ Build a matrix to flip an image according to a given axis Args: axis (str): axis along the flip is done ("X", "Y" or "Z") im_size (tuple(int, int, int)): coordinates of the top point (usually im shape) Returns: (ndarray): 4x4 flipping matrix """ out = np.identity(4) if axis == "X": out[0, 0] = -1 out[0, -1] = im_size[0] if axis == "Y": out[1, 1] = -1 out[1, -1] = im_size[1] if axis == "Z": out[2, 2] = -1 out[2, -1] = im_size[2] return out @staticmethod def translation_matrix(axis: str, tr: float) -> np.ndarray: """ Build a matrix to flip an image according to a given axis Args: axis (str): axis along the flip is done ("X", "Y" or "Z") tr (float): translation value Returns: (ndarray): 4x4 flipping matrix """ out = np.identity(4) if axis == "X": out[0, -1] = tr if axis == "Y": out[1, -1] = tr if axis == "Z": out[2, -1] = tr return out @classmethod def read_param_file( clf, p_param: trsf_parameters = None ) -> trsf_parameters: """ Asks for, reads and formats the parameter file """ if not isinstance(p_param, dict): if p_param is None: if len(sys.argv) < 2 or sys.argv[1] == "-f": p_param = input( "\nPlease inform the path to the json config file:\n" ) else: p_param = sys.argv[1] stable = False or isinstance(p_param, Path) while not stable: tmp = p_param.strip('"').strip("'").strip(" ") stable = tmp == p_param p_param = tmp if os.path.isdir(p_param): f_names = [ os.path.join(p_param, f) for f in os.listdir(p_param) if ".json" in f and not "~" in f ] else: f_names = [p_param] else: f_names = [p_param] params = [] for file_name in f_names: if isinstance(file_name, str): print("") print("Extraction of the parameters from file %s" % file_name) p = trsf_parameters(file_name) if not p.check_parameters_consistancy(): print("\n%s Failed the consistancy check, it will be skipped") else: params += [p] print("") return params @staticmethod def read_trsf(path: Union[str, Path]) -> np.ndarray: """ Read a transformation from a text file Args: path (str | Path): path to a transformation Returns: (ndarray): 4x4 transformation matrix """ f = open(path) if f.read()[0] == "(": f.close() f = open(path) lines = f.readlines()[2:-1] f.close() return np.array([[float(v) for v in l.split()] for l in lines]) else: f.close() return np.loadtxt(path) @staticmethod def prepare_paths(p: trsf_parameters): """ Prepare the paths in a format that is usable by the algorithm Args: p (trsf_parameters): path to a transformation """ p.ref_A = os.path.join(p.path_to_data, p.ref_im) p.flo_As = [] for flo_im in p.flo_ims: p.flo_As += [os.path.join(p.path_to_data, flo_im)] if os.path.split(p.out_pattern)[0] == "": ext = p.ref_im.split(".")[-1] p.ref_out = p.ref_A.replace(ext, p.out_pattern + "." + ext) p.flo_outs = [] for flo in p.flo_As: p.flo_outs += [flo.replace(ext, p.out_pattern + "." + ext)] else: if not os.path.exists(p.out_pattern): os.makedirs(p.out_pattern) p.ref_out = os.path.join(p.out_pattern, p.ref_im) p.flo_outs = [] for flo in p.flo_ims: p.flo_outs += [os.path.join(p.out_pattern, flo)] if not hasattr(p, "trsf_paths"): p.trsf_paths = [os.path.split(pi)[0] for pi in p.flo_outs] p.trsf_names = ["A{a:d}-{trsf:s}.trsf" for _ in p.flo_outs] else: formated_paths = [] p.trsf_names = [] for pi in p.trsf_paths: path, n = os.path.split(pi) if os.path.splitext(n)[-1] == "": n = "" path = pi if not os.path.exists(path): os.makedirs(path) if n == "": n = "A{a:d}-{trsf:s}.trsf" elif not "{a:" in n: if not "{trsf:" in n: n += "{a:d}-{trsf:s}.trsf" else: n += "{a:d}.trsf" elif not "{trsf:" in n: n += "{trsf:s}.trsf" formated_paths += [path] p.trsf_names += [n] p.trsf_paths = formated_paths if p.time_tag is not None: s = p.ref_A.find(p.time_tag) + len(p.time_tag) e = s while p.ref_A[e].isdigit() and e < len(p.ref_A): e += 1 p.begin = p.end = int(p.ref_A[s:e]) else: p.begin = p.end = None if p.flo_im_sizes is None: p.flo_im_sizes = [] for im_p in p.flo_As: p.flo_im_sizes.append(imread(im_p).shape) if ( not hasattr(p, "ref_im_size") or p.ref_im_size is None ) and p.flo_im_sizes is not None: p.ref_im_size = p.flo_im_sizes[0] else: p.ref_im_size = imread(p.ref_A).shape if not hasattr(p, "bdv_im") or p.bdv_im is None: p.bdv_im = [p.ref_A] + p.flo_As if not hasattr(p, "out_bdv") or p.out_bdv is None: p.out_bdv = os.path.join(p.trsf_paths[0], "bdv.xml") if p.bdv_voxel_size is None: p.bdv_voxel_size = p.ref_voxel @staticmethod def inv_trsf(trsf: Union[np.ndarray, List[List]]) -> np.ndarray: """ Inverse a given transformation Args: trsf (np.ndarray): 4x4 ndarray Returns: (np.ndarray): the 4x4 inverted matrix """ return np.linalg.lstsq(trsf, np.identity(4))[0] def vox_to_real( self, trsf: Union[np.ndarray, List[List]], ref_vs: List[float], ) -> np.ndarray: """ Transform a transformation for voxel units to physical units Args: trsf (ndarray): 4x4 matrix ref_vs (list(float, float, float)): initial voxel size in each dimension Returns: (np.ndarray): new matrix in metric size """ H_ref = [ [ref_vs[0], 0, 0, 0], [0, ref_vs[1], 0, 0], [0, 0, ref_vs[2], 0], [0, 0, 0, 1], ] H_ref_inv = self.inv_trsf(H_ref) return np.dot(trsf, H_ref_inv) def compute_trsfs(self, p: trsf_parameters): """ Here is where the magic happens, give as an input the trsf_parameters object, get your transformations computed Args: p (trsf_parameters): parameters to compute the transformation """ for A_num, flo_A in enumerate(p.flo_As): flo_voxel = p.flo_voxels[A_num] init_trsf = p.init_trsfs[A_num] trsf_path = p.trsf_paths[A_num] trsf_name = p.trsf_names[A_num] if isinstance(init_trsf, list): i = 0 trsfs = [] im_size = ( np.array(p.flo_im_sizes[A_num], dtype=float) * flo_voxel ) while i < len(init_trsf): t_type = init_trsf[i] i += 1 axis = init_trsf[i] i += 1 if "rot" in t_type: angle = init_trsf[i] i += 1 trsfs += [ self.axis_rotation_matrix( axis.upper(), angle, np.zeros(3), im_size ) ] elif "flip" in t_type: trsfs += [self.flip_matrix(axis.upper(), im_size)] elif "trans" in t_type: tr = init_trsf[i] i += 1 trsfs += [self.translation_matrix(axis, tr)] res = np.identity(4) for trsf in trsfs: res = np.dot(res, trsf) if not os.path.exists(trsf_path): os.makedirs(trsf_path) init_trsf = os.path.join( trsf_path, "A{:d}-init.trsf".format(A_num + 1) ) np.savetxt(init_trsf, res) elif not p.init_trsf_real_unit and init_trsf is not None: tmp = self.vox_to_real( self.inv_trsf(self.read_trsf(init_trsf)), flo_voxel, p.ref_voxel, ) init_ext = init_trsf.split(".")[-1] init_trsf = init_trsf.replace(init_ext, "real.txt") np.savetxt(init_trsf, self.inv_trsf(tmp)) if init_trsf is not None: init_trsf_command = " -init-trsf {:s}".format(init_trsf) else: init_trsf_command = "" i = 0 if not p.test_init: for i, trsf_type in enumerate(p.trsf_types[:-1]): if i != 0: init_trsf_command = " -init-trsf {:s}".format( os.path.join(trsf_path, res_trsf) ) res_trsf = os.path.join( trsf_path, trsf_name.format(a=A_num + 1, trsf=trsf_type), ) call( p.path_to_bin + "blockmatching -ref " + p.ref_A.format(t=p.begin) + " -flo " + flo_A.format(t=p.begin) + " -reference-voxel %f %f %f" % p.ref_voxel + " -floating-voxel %f %f %f" % flo_voxel + " -trsf-type %s -py-hl %d -py-ll %d" % ( trsf_type, p.registration_depth_start, p.registration_depth_end, ) + init_trsf_command + " -res-trsf " + res_trsf + " -composition-with-initial", shell=True, ) trsf_type = p.trsf_types[-1] i = len(p.trsf_types) - 1 if i != 0: init_trsf_command = " -init-trsf {:s}".format( os.path.join(trsf_path, res_trsf) ) res_trsf = os.path.join( trsf_path, trsf_name.format(a=A_num + 1, trsf=trsf_type) ) res_inv_trsf = os.path.join( trsf_path, ("inv-" + trsf_name).format(a=A_num + 1, trsf=trsf_type), ) call( p.path_to_bin + "blockmatching -ref " + p.ref_A.format(t=p.begin) + " -flo " + flo_A.format(t=p.begin) + " -reference-voxel %f %f %f" % p.ref_voxel + " -floating-voxel %f %f %f" % flo_voxel + " -trsf-type %s -py-hl %d -py-ll %d" % ( trsf_type, p.registration_depth_start, p.registration_depth_end, ) + init_trsf_command + " -res-trsf " + res_trsf + # ' -res-voxel-trsf ' + res_voxel_trsf + \ # ' -res ' + flo_out +\ " -composition-with-initial", shell=True, ) call( p.path_to_bin + "invTrsf %s %s" % (res_trsf, res_inv_trsf), shell=True, ) @staticmethod def pad_trsfs(p: trsf_parameters, t: int = None): """ Pad transformations Args: p (trsf_parameters): parameter object trsf_fmt (srt): the string format for the initial transformations """ out_voxel = p.out_voxel trsf_path = p.trsf_paths[0] trsf_name = p.trsf_names[0] trsf_type = p.trsf_types[-1] im_shape = imread(p.ref_A.format(t=t)).shape im = SpatialImage(np.ones(im_shape, dtype=np.uint8)) im.voxelsize = p.ref_voxel template = os.path.join(trsf_path, "tmp.tif") res_t = "template.tif" imsave(template, im) identity = np.identity(4) if p.test_init: trsf_name_only_a = "A{a:d}-init.trsf" else: where_a = trsf_name.find("{a:d}") no_a = (trsf_name[:where_a] + trsf_name[where_a + 5 :]).format( trsf=trsf_type ) trsf_name_only_a = no_a[:where_a] + "{a:d}" + no_a[where_a:] trsf_fmt = os.path.join(trsf_path, trsf_name_only_a) trsf_fmt_no_flo = trsf_fmt.replace("{a:d}", "%d") new_trsf_fmt = ".".join(trsf_fmt.split(".")[:-1]) + "-padded.txt" new_trsf_fmt_no_flo = new_trsf_fmt.replace("{a:d}", "%d") np.savetxt(trsf_fmt.format(a=0, trsf=trsf_type), identity) call( p.path_to_bin + "changeMultipleTrsfs -trsf-format " + trsf_fmt_no_flo + " -index-reference %d -first %d -last %d " % (0, 0, len(p.trsf_paths)) + " -template " + template + " -res " + new_trsf_fmt_no_flo + " -res-t " + os.path.join(trsf_path, res_t) + " " + " -trsf-type %s" % (trsf_type), shell=True, ) template = os.path.join(trsf_path, res_t) return new_trsf_fmt, template def apply_trsf(self, p, t=None): """ Apply the transformation according to `trsf_parameters` Args: p (trsf_parameters): parameters for the transformation """ if p.bbox_out: trsf_fmt, template = self.pad_trsfs(p, t) if p.out_voxel != p.ref_voxel: before, after = os.path.splitext(template) old_template = template template = "".join((before, ".final_template", after)) call( p.path_to_bin + f"applyTrsf {old_template} {template} " + "-vs %f %f %f" % p.out_voxel, shell=True, ) A0_trsf = ( " -trsf " + trsf_fmt.format(a=0) + " -template " + template ) else: A0_trsf = "" if p.out_voxel != p.ref_voxel or p.bbox_out: call( p.path_to_bin + "applyTrsf" + " -flo " + p.ref_A.format(t=t) + " -res " + p.ref_out.format(t=t) + " -floating-voxel %f %f %f" % p.ref_voxel + " -vs %f %f %f" % p.out_voxel + A0_trsf, shell=True, ) elif p.copy_ref: copyfile(p.ref_A.format(t=t), p.ref_out.format(t=t)) else: p.ref_out = p.ref_A for A_num, flo_A in enumerate(p.flo_As): flo_voxel = p.flo_voxels[A_num] trsf_path = p.trsf_paths[A_num] trsf_name = p.trsf_names[A_num] init_trsf = p.init_trsfs[A_num] if p.test_init: if isinstance(init_trsf, list): trsf = " -trsf " + os.path.join( trsf_path, "A{:d}-init.trsf".format(A_num + 1) ) else: trsf = " -trsf " + init_trsf elif not p.bbox_out: t_type = "" if len(p.trsf_types) < 1 else p.trsf_types[-1] trsf = " -trsf " + os.path.join( trsf_path, trsf_name.format(a=A_num + 1, trsf=t_type) ) else: trsf = ( " -trsf " + trsf_fmt.format(a=A_num + 1) + " -template " + template ) flo_out = p.flo_outs[A_num] call( p.path_to_bin + "applyTrsf" + " -flo " + flo_A.format(t=t) + " -floating-voxel %f %f %f" % flo_voxel + " -res " + flo_out.format(t=t) + " -ref " + p.ref_out.format(t=t) + " -reference-voxel %f %f %f" % p.out_voxel + trsf + " -interpolation %s" % p.image_interpolation, shell=True, ) @staticmethod def prettify(elem: ET.Element) -> str: """ Return a pretty-printed XML string for the Element. Args: elem (xml.etree.ElementTree.Element): xml element Returns: (str): a nice version of our xml file """ rough_string = ET.tostring(elem, "utf-8") reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=" ") @staticmethod def do_viewSetup( ViewSetup: ET.SubElement, p: trsf_parameters, im_size: Tuple[int, int, int], i: int, ): """ Setup xml elements for BigDataViewer Args: ViewSetup (ET.SubElement): ... p (trsf_parameters): Parameter object im_size (tuple): tuple of 3 integers with the dimension of the image i (int): angle id """ id_ = ET.SubElement(ViewSetup, "id") id_.text = "%d" % i name = ET.SubElement(ViewSetup, "name") name.text = "%d" % i size = ET.SubElement(ViewSetup, "size") size.text = "%d %d %d" % tuple(im_size) voxelSize = ET.SubElement(ViewSetup, "voxelSize") unit = ET.SubElement(voxelSize, "unit") unit.text = p.bdv_unit size = ET.SubElement(voxelSize, "size") size.text = "%f %f %f" % tuple(p.bdv_voxel_size) attributes = ET.SubElement(ViewSetup, "attributes") illumination = ET.SubElement(attributes, "illumination") illumination.text = "0" channel = ET.SubElement(attributes, "channel") channel.text = "0" tile = ET.SubElement(attributes, "tile") tile.text = "0" angle = ET.SubElement(attributes, "angle") angle.text = "%d" % i def do_ViewRegistration( self, ViewRegistrations: ET.SubElement, p: trsf_parameters, t: int, a: int, ): """ Write the view registration for BigDataViewer Args: ViewSetup (ET.SubElement): ... p (trsf_parameters): Parameter object t (int): time point to treat a (int): angle to treat """ ViewRegistration = ET.SubElement(ViewRegistrations, "ViewRegistration") ViewRegistration.set("timepoint", "%d" % t) ViewRegistration.set("setup", "%d" % a) ViewTransform = ET.SubElement(ViewRegistration, "ViewTransform") ViewTransform.set("type", "affine") if a != 0: affine = ET.SubElement(ViewTransform, "affine") trsf_path = p.trsf_paths[a - 1] trsf_name = p.trsf_names[a - 1] trsf_type = p.trsf_types[-1] f = os.path.join( trsf_path, ("inv-" + trsf_name).format(a=a, trsf=trsf_type) ) trsf = self.read_trsf(f) formated_trsf = tuple(trsf[:-1, :].flatten()) affine.text = ("%f " * 12) % formated_trsf ViewTransform = ET.SubElement(ViewRegistration, "ViewTransform") ViewTransform.set("type", "affine") affine = ET.SubElement(ViewTransform, "affine") affine.text = ( "%f 0.0 0.0 0.0 0.0 %f 0.0 0.0 0.0 0.0 %f 0.0" % p.flo_voxels[a - 1] ) else: affine = ET.SubElement(ViewTransform, "affine") affine.text = ( "%f 0.0 0.0 0.0 0.0 %f 0.0 0.0 0.0 0.0 %f 0.0" % p.ref_voxel ) def build_bdv(self, p: trsf_parameters): """ Build the BigDataViewer xml Args: p (trsf_parameters): Parameter object """ SpimData = ET.Element("SpimData") SpimData.set("version", "0.2") base_path = ET.SubElement(SpimData, "BasePath") base_path.set("type", "relative") base_path.text = "." SequenceDescription = ET.SubElement(SpimData, "SequenceDescription") ImageLoader = ET.SubElement(SequenceDescription, "ImageLoader") ImageLoader.set("format", "klb") Resolver = ET.SubElement(ImageLoader, "Resolver") Resolver.set( "type", "org.janelia.simview.klb.bdv.KlbPartitionResolver" ) for im_p in p.bdv_im: ViewSetupTemplate = ET.SubElement(Resolver, "ViewSetupTemplate") template = ET.SubElement(ViewSetupTemplate, "template") template.text = im_p timeTag = ET.SubElement(ViewSetupTemplate, "timeTag") timeTag.text = p.time_tag ViewSetups = ET.SubElement(SequenceDescription, "ViewSetups") ViewSetup = ET.SubElement(ViewSetups, "ViewSetup") i = 0 self.do_viewSetup(ViewSetup, p, p.ref_im_size, i) for i, pi in enumerate(p.flo_voxels): ViewSetup = ET.SubElement(ViewSetups, "ViewSetup") self.do_viewSetup(ViewSetup, p, p.flo_im_sizes[i], i + 1) Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "illumination") Illumination = ET.SubElement(Attributes, "Illumination") id_ = ET.SubElement(Illumination, "id") id_.text = "0" name = ET.SubElement(Illumination, "name") name.text = "0" Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "channel") Channel = ET.SubElement(Attributes, "Channel") id_ = ET.SubElement(Channel, "id") id_.text = "0" name = ET.SubElement(Channel, "name") name.text = "0" Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "tile") Tile = ET.SubElement(Attributes, "Tile") id_ = ET.SubElement(Tile, "id") id_.text = "0" name = ET.SubElement(Tile, "name") name.text = "0" Attributes = ET.SubElement(ViewSetups, "Attributes") Attributes.set("name", "angle") for i in range(len(p.flo_voxels) + 1): Angle = ET.SubElement(Attributes, "Angle") id_ = ET.SubElement(Angle, "id") id_.text = "%d" % i name = ET.SubElement(Angle, "name") name.text = "%d" % i TimePoints = ET.SubElement(SequenceDescription, "Timepoints") TimePoints.set("type", "range") first = ET.SubElement(TimePoints, "first") first.text = "%d" % p.begin last = ET.SubElement(TimePoints, "last") last.text = "%d" % p.end ViewRegistrations = ET.SubElement(SpimData, "ViewRegistrations") for t in range(p.begin, p.end + 1): self.do_ViewRegistration(ViewRegistrations, p, t, 0) for a in range(len(p.flo_voxels)): self.do_ViewRegistration(ViewRegistrations, p, t, a + 1) with open(p.out_bdv, "w") as f: f.write(self.prettify(SpimData)) f.close() def run_trsf(self): """ Start the Spatial registration after having informed the parameter files """ for p in self.params: try: print("Starting experiment") print(p) self.prepare_paths(p) if p.compute_trsf or p.test_init: self.compute_trsfs(p) if p.apply_trsf or p.test_init: if not (p.begin is None and p.end is None): for t in range(p.begin, p.end + 1): self.apply_trsf(p, t) else: self.apply_trsf(p) if p.do_bdv: self.build_bdv(p) except Exception as e: print("Failure of %s" % p.origin_file_name) print(e) def __init__(self, params=None): if params is None: self.params = self.read_param_file() elif ( isinstance(params, str) or isinstance(params, Path) or isinstance(params, dict) ): self.params = SpatialRegistration.read_param_file(params) else: self.params = params if self.params is not None and 0 < len(self.params): self.path_to_bin = self.params[0].path_to_bin def spatial_registration(): reg = SpatialRegistration() reg.run_trsf()
3D-registration
/3D-registration-0.4.3.tar.gz/3D-registration-0.4.3/src/registrationtools/spatial_registration.py
spatial_registration.py
import logging import numba.cuda as cuda import numpy as np from functtools import lru_cache @lru_cache def get_threads_blocks(length, max_thread_size=9): """Calculate thread/block sizes for launching CUDA kernels. Parameters ---------- length : int Number of threads. max_thread_size : int Maximum thread size in 2^N. Returns ------- (int, int) Number of threads and thread blocks. """ logger = logging.getLogger(__name__) counter = 0 _length = length while True: if _length % 2 == 1: logger.warning("get_threads_blocks could not fully factorize the number of threads") break _length //= 2 counter += 1 if counter >= max_thread_size: break return 2**counter, _length def initialize_array(shape, value, dtype=np.float32): """Create and initialize cuda device array. Parameters ---------- shape : tuple Array shape. value: np.float32 Value to fill array with. dtype: type, optional Array data type, by default np.float32. Returns ------- Initialized cuda device array. numba.cuda.cudadrv.devicearray.DeviceNDArray """ arr = cuda.device_array(shape, dtype=dtype).ravel() threads, blocks = get_threads_blocks(len(arr)) _cuda_initialize_array[blocks, threads](arr, value) return arr.reshape(shape) @cuda.jit def _cuda_initialize_array(array, value): i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x array[i] = value def extract_array_column(array, column): """Exctract column from array . Parameters ---------- array : numba.cuda.cudadrv.devicearray.DeviceNDArray Cuda Array column: int, optional Column to be extracted Returns ------- Extracted column as cuda device array. numba.cuda.cudadrv.devicearray.DeviceNDArray """ _array = cuda.device_array((len(array),), dtype=array.dtype) threads, blocks = get_threads_blocks(len(_array)) _cuda_extract_column[blocks, threads](array, column, _array) return _array @cuda.jit def _cuda_extract_column(array, column, out): i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x out[i] = array[i, column]
3DCORE
/3DCORE-1.1.4.tar.gz/3DCORE-1.1.4/py3dcore/_extcuda.py
_extcuda.py
import logging import numba import numpy as np import scipy import scipy.stats class Base3DCOREParameters(object): """Base 3DCORE parameters class. """ params_dict = None dtype = None qindices = None def __init__(self, params_dict, **kwargs): """Initialize Base3DCOREParameters class. Parameters ---------- params_dict : dict Parameter dictionary. Other Parameters ---------------- dtype: type Numpy data type, by default np.float32. qindices: np.ndarray Quaternion array columns, by default [1, 2, 3]. """ self.params_dict = params_dict self.dtype = kwargs.get("dtype", np.float32) self.qindices = np.array( kwargs.get("qindices", np.array([1, 2, 3])) ).ravel().astype(int) # update arrays self._update_arr() def __getitem__(self, key): for dk in self.params_dict: if self.params_dict[dk]["index"] == key or self.params_dict[dk]["name"] == key: return self.params_dict[dk] if isinstance(key, int): raise KeyError("key %i is out of range", key) else: raise KeyError("key \"%s\" does not exist", key) def __iter__(self): self.iter_n = 0 return self def __len__(self): return len(self.params_dict.keys()) def __next__(self): if self.iter_n < len(self): result = self[self.iter_n] self.iter_n += 1 return result else: raise StopIteration def generate(self, iparams_arr, **kwargs): """Generate initial parameters Parameters ---------- iparams : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Initial parameters array. Other Parameters ---------------- rng_states : List[numba.cuda.cudadrv.devicearray.DeviceNDArray] CUDA rng state array. use_cuda : bool CUDA flag, by default False. """ size = len(iparams_arr) if kwargs.get("use_cuda", False): raise NotImplementedError("CUDA functionality is not available yet") else: for param in self: index = param["index"] if param["distribution"] == "fixed": iparams_arr[:, index] = param["fixed_value"] elif param["distribution"] == "uniform": maxv = param["maximum"] minv = param["minimum"] iparams_arr[:, index] = np.random.rand(size) * (maxv - minv) + minv elif param["distribution"] == "gaussian": maxv = param["maximum"] minv = param["minimum"] kwargs = { "loc": param["mean"], "scale": param["std"] } iparams_arr[:, index] = draw_iparams(np.random.normal, maxv, minv, size, **kwargs) elif param["distribution"] == "gamma": maxv = param["maximum"] minv = param["minimum"] kwargs = { "loc": param["shape"], "scale": param["scale"] } iparams_arr[:, index] = draw_iparams(np.random.gamma, maxv, minv, size, **kwargs) elif param["distribution"] == "log-uniform": maxv = param["maximum"] minv = param["minimum"] kwargs = { "a": minv, "b": maxv } iparams_arr[:, index] = draw_iparams(scipy.stats.loguniform.rvs, maxv, minv, size, **kwargs) elif param["distribution"] == "exponential": maxv = param["maximum"] minv = param["minimum"] kwargs = { "scale": param["scale"] } iparams_arr[:, index] = draw_iparams(custom_exponential, maxv, minv, size, **kwargs) else: raise NotImplementedError("%s distribution is not implemented", param["distribution"]) self._update_arr() def perturb(self, iparams_arr, particles, weights, kernels_lower, **kwargs): """Perburb parameters. Parameters ---------- iparams : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Initial parameters array. particles : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Particles. weights : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Weight array. kernels_lower : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Transition kernels in the form of a lower triangular matrix. Number of dimensions determines the type of method used. Other Parameters ---------------- rng_states : List[numba.cuda.cudadrv.devicearray.DeviceNDArray] CUDA rng state array. use_cuda : bool CUDA flag, by default False. """ if kwargs.get("use_cuda", False): raise NotImplementedError("CUDA functionality is not available yet") else: if kernels_lower.ndim == 1: raise DeprecationWarning("1D transition kernels are no longer supported") elif kernels_lower.ndim == 2: # perturbation with one covariance matrix _numba_perturb_with_kernel(iparams_arr, particles, weights, kernels_lower, self.type_arr, self.bound_arr, self.maxv_arr, self.minv_arr) elif kernels_lower.ndim == 3: # perturbation with local covariance matrices _numba_perturb_with_kernels(iparams_arr, particles, weights, kernels_lower, self.type_arr, self.bound_arr, self.maxv_arr, self.minv_arr) else: raise ValueError("kernel array must be 3-dimensional or lower") def weight(self, particles, particles_old, weights, weights_old, kernels, **kwargs): """Update particle weights. Parameters ---------- particles : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Particle array. particles_old : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Old particle array. weights : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Paritcle weights array. weights_old : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Old particle weights array. kernels : Union[np.ndarray, List[numba.cuda.cudadrv.devicearray.DeviceNDArray]] Transition kernels. Number of dimensions determines the type of method used. Other Parameters ---------------- exclude_priors: bool Exclude prior distributions from weighting, by default False. use_cuda : bool CUDA flag, by default False. """ logger = logging.getLogger(__name__) if kwargs.get("use_cuda", False): raise NotImplementedError("CUDA functionality is not available yet") else: if kernels.ndim == 1: raise DeprecationWarning("1D transition kernels are no longer supported") elif kernels.ndim == 2: _numba_weights_with_kernel(particles, particles_old, weights, weights_old, kernels) elif kernels.ndim == 3: _numba_weights_with_kernels(particles, particles_old, weights, weights_old, kernels) else: raise ValueError("kernel array must be 3-dimensional or lower") # include priors into weighting scheme if not kwargs.get("exclude_priors", False): _numba_calculate_weights_priors( particles, weights, self.type_arr, self.dp1_arr, self.dp2_arr) # a hack for abnormally big weights quant = np.quantile(weights, 0.99) for i in range(0, len(weights)): if weights[i] > quant: weights[i] = 0 # find and remove bad weights (NaN) nanc = np.sum(np.isnan(weights)) infc = np.sum(weights == np.inf) if nanc + infc > 0: logger.warning("detected %i NaN/inf weights, setting to 0", nanc + infc) weights[np.isnan(weights)] = 0 weights[weights == np.inf] = 0 # renormalize wsum = np.sum(weights) for i in range(0, len(weights)): weights[i] /= wsum def _update_arr(self): """Translate params_dict to arrays. Following distributions are supported: - 0 fixed value (delta) - 1 uniform - 2 gaussian, sigma - 3 gamma, shape+scale - 4 log-uniform - 5 exponential, scale """ self.active = np.zeros((len(self), ), dtype=self.dtype) self.bound_arr = np.zeros((len(self), ), dtype=self.dtype) self.maxv_arr = np.zeros((len(self), ), dtype=self.dtype) self.dp1_arr = np.zeros((len(self), ), dtype=self.dtype) self.dp2_arr = np.zeros((len(self), ), dtype=self.dtype) self.minv_arr = np.zeros((len(self), ), dtype=self.dtype) self.type_arr = np.zeros((len(self), ), dtype=self.dtype) for param in self: index = param["index"] self.active[index] = param.get("active", 1) if param["distribution"] == "fixed": self.type_arr[index] = 0 self.maxv_arr[index] = param["fixed_value"] elif param["distribution"] == "uniform": self.type_arr[index] = 1 self.maxv_arr[index] = param["maximum"] self.minv_arr[index] = param["minimum"] elif param["distribution"] == "gaussian": self.type_arr[index] = 2 self.maxv_arr[index] = param["maximum"] self.minv_arr[index] = param["minimum"] self.dp1_arr[index] = param.get("mean", 0) self.dp2_arr[index] = param.get("std", 0) elif param["distribution"] == "gamma": self.type_arr[index] = 3 self.maxv_arr[index] = param["maximum"] self.minv_arr[index] = param["minimum"] self.dp1_arr[index] = param.get("shape", 0) self.dp2_arr[index] = param.get("scale", 0) elif param["distribution"] == "log-uniform": self.type_arr[index] = 4 self.maxv_arr[index] = param["maximum"] self.minv_arr[index] = param["minimum"] elif param["distribution"] == "exponential": self.type_arr[index] = 5 self.maxv_arr[index] = param["maximum"] self.minv_arr[index] = param["minimum"] self.dp1_arr[index] = param.get("scale", 0) else: raise NotImplementedError("%s distribution is not implemented", param["distribution"]) if param["boundary"] == "continuous": self.bound_arr[index] = 0 elif param["boundary"] == "periodic": self.bound_arr[index] = 1 else: raise NotImplementedError("%s boundary condition is not implemented", param["boundary"]) def draw_iparams(func, maxv, minv, size, **kwargs): """Draw random numbers from func, within the interval [minv, maxv]. """ i = 0 numbers = func(size=size, **kwargs) while True: filter = ((numbers > maxv) | (numbers < minv)) if np.sum(filter) == 0: break numbers[filter] = func(size=len(filter), **kwargs)[filter] i += 1 if i > 1000: raise RuntimeError("drawing numbers inefficiently (%i/%i after 1000 iterations)", len(filter), size) return numbers def custom_exponential(**kwargs): numbers = np.random.exponential(**kwargs) signs = np.random.randint(2, size=len(numbers)) return numbers * (1 - 2 * signs) @numba.njit def _numba_perturb_with_kernel(iparams_arr, particles, weights, kernel_lower, type_arr, bound_arr, maxv_arr, minv_arr): for i in range(len(iparams_arr)): # particle selector si r = np.random.rand(1)[0] for j in range(len(weights)): r -= weights[j] if r <= 0: si = j break # draw candidates until a candidite is within the valid range c = 0 Nc = 25 perturbations = np.dot(kernel_lower, np.random.randn(len(particles[si]), Nc)) while True: candidate = particles[si] + perturbations[:, c] accepted = True for k in range(len(candidate)): if candidate[k] > maxv_arr[k]: if bound_arr[k] == 0: accepted = False break elif bound_arr[k] == 1: candidate[k] = minv_arr[k] + candidate[k] - maxv_arr[k] else: raise NotImplementedError if candidate[k] < minv_arr[k]: if bound_arr[k] == 0: accepted = False break elif bound_arr[k] == 1: candidate[k] = maxv_arr[k] + candidate[k] - minv_arr[k] else: raise NotImplementedError if accepted: break c += 1 if c >= Nc - 1: c = 0 perturbations = np.dot(kernel_lower, np.random.randn(len(particles[si]), Nc)) iparams_arr[i] = candidate @numba.njit def _numba_perturb_with_kernels(iparams_arr, particles, weights, kernels_lower, type_arr, bound_arr, maxv_arr, minv_arr): for i in range(len(iparams_arr)): # particle selector si r = np.random.rand(1)[0] for j in range(len(weights)): r -= weights[j] if r <= 0: si = j break #print("selected candidate ", si) # draw candidates until a candidate is within the valid range c = 0 Nc = 25 perturbations = np.dot(kernels_lower[si], np.random.randn(len(particles[si]), Nc)) while True: #print("iter ", c) candidate = particles[si] + perturbations[:, c] #print(candidate) #print(bound_arr) accepted = True for k in range(len(candidate)): #print("cand k ", k) if candidate[k] > maxv_arr[k]: if bound_arr[k] == 0: accepted = False #print("out of bounds") break elif bound_arr[k] == 1: while candidate[k] > maxv_arr[k]: candidate[k] = minv_arr[k] + candidate[k] - maxv_arr[k] #print("redrawing") else: #print("error raise?") raise NotImplementedError if candidate[k] < minv_arr[k]: if bound_arr[k] == 0: accepted = False break elif bound_arr[k] == 1: while candidate[k] < minv_arr[k]: candidate[k] = maxv_arr[k] + candidate[k] - minv_arr[k] else: #print("error raise?") raise NotImplementedError if accepted: break c += 1 if c >= Nc - 1: c = 0 perturbations = np.dot(kernels_lower[si], np.random.randn(len(particles[si]), Nc)) #print("bad drawing") #print("saving candidate") iparams_arr[i] = candidate @numba.njit(parallel=True) def _numba_weights_with_kernel(particles, particles_prev, weights, weights_prev, kernel): inv_kernel = np.linalg.pinv(kernel).astype(particles.dtype) for i in numba.prange(len(particles)): nw = 0 for j in range(len(particles_prev)): v = _numba_calculate_weights_reduce(particles[i], particles_prev[j], inv_kernel) nw += weights_prev[j] * np.exp(-v) weights[i] = 1 / nw @numba.njit(parallel=True) def _numba_weights_with_kernels(particles, particles_prev, weights, weights_prev, kernels): inv_kernels = np.zeros_like(kernels).astype(particles.dtype) # compute kernel inverses for i in numba.prange(len(kernels)): inv_kernels[i] = np.linalg.pinv(kernels[i]) for i in numba.prange(len(particles)): nw = 0 for j in range(len(particles_prev)): v = _numba_calculate_weights_reduce(particles[i], particles_prev[j], inv_kernels[j]) nw += weights_prev[j] * np.exp(-v) weights[i] = 1 / nw @numba.njit(inline="always") def _numba_calculate_weights_reduce(x1, x2, A): dx = (x1 - x2).astype(A.dtype) return np.dot(dx, np.dot(A, dx)) # numba does not support scipy functions # @numba.njit(parallel=True) def _numba_calculate_weights_priors(particles, weights, type_arr, dp1_arr, dp2_arr): for i in range(len(weights)): for j in range(len(type_arr)): if type_arr[j] <= 1: # fixed or uniform, no weighting pass elif type_arr[j] == 2: # gaussian distribution weights[i] *= np.exp(-0.5 * (particles[i, j] - dp1_arr[j])**2/dp2_arr[j]**2) / dp2_arr[j] elif type_arr[j] == 3: # gamma distribution weights[i] *= np.exp(-particles[i, j]/dp2_arr[j]) * particles[i, j] ** ( dp1_arr[j] - 1) / scipy.special.gamma(dp1_arr[j]) / dp2_arr[j]**dp1_arr[j] elif type_arr[j] == 4: # log-uniform distribution weights[i] *= 1 / particles[i, j] elif type_arr[j] == 5: # exponential distribution value = np.abs(particles[i, j]) weights[i] *= np.exp(-value / dp1_arr[j]) else: raise NotImplementedError("distribution #%i is not implemented", type_arr[j])
3DCORE
/3DCORE-1.1.4.tar.gz/3DCORE-1.1.4/py3dcore/params.py
params.py
import numba import numpy as np from numba import guvectorize def generate_quaternions(iparams_arr, qs_sx, qs_xs, use_cuda=False, indices=None): """Wrapper function for generating rotational quaternions from iparams array. Parameters ---------- iparams_arr : Union[np.ndarray, numba.cuda.cudadrv.devicearray.DeviceNDArray] Initial parameters array. qs_sx : Union[np.ndarray, numba.cuda.cudadrv.devicearray.DeviceNDArray] Array for (s) -> (x) rotational quaternions. qs_xs : Union[np.ndarray, numba.cuda.cudadrv.devicearray.DeviceNDArray] Array for (x) -> (s) rotational quaternions. use_cuda : bool CUDA flag, by default False. indices : np.ndarray, optional Lon/Lat/Inc indices in params, by default None. """ if indices is None: indices = np.array([1, 2, 3]) else: indices = np.array(indices) if use_cuda: raise NotImplementedError("CUDA functionality is not available yet") else: (i1, i2, i3) = (indices[0], indices[1], indices[2]) (lon, lat, inc) = (iparams_arr[:, i1], iparams_arr[:, i2], iparams_arr[:, i3]) ux = np.array([0, 1.0, 0, 0]) uy = np.array([0, 0, 1.0, 0]) uz = np.array([0, 0, 0, 1.0]) rlon = _numba_quaternion_create(lon, uz) rlat = _numba_quaternion_create(-lat, quaternion_rotate(uy, rlon)) rinc = _numba_quaternion_create( inc, quaternion_rotate(ux, _numba_quaternion_multiply(rlat, rlon))) _numba_quaternion_multiply(rinc, _numba_quaternion_multiply(rlat, rlon), qs_xs) _numba_quaternion_conjugate(qs_xs, qs_sx) def quaternion_rotate(vec, q, use_cuda=False): if use_cuda: raise NotImplementedError("CUDA functionality is not available yet") else: return _numba_quaternion_multiply( q, _numba_quaternion_multiply(vec, _numba_quaternion_conjugate(q))) @numba.njit def _numba_quaternion_rotate(vec, q): qh = (q[0], -q[1], -q[2], -q[3]) # mul 1 ma = - vec[1] * qh[1] - vec[2] * qh[2] - vec[3] * qh[3] mb = + vec[1] * qh[0] + vec[2] * qh[3] - vec[3] * qh[2] mc = - vec[1] * qh[3] + vec[2] * qh[0] + vec[3] * qh[1] md = + vec[1] * qh[2] - vec[2] * qh[1] + vec[3] * qh[0] # mul 2 rb = q[0] * mb + q[1] * ma + q[2] * md - q[3] * mc rc = q[0] * mc - q[1] * md + q[2] * ma + q[3] * mb rd = q[0] * md + q[1] * mc - q[2] * mb + q[3] * ma return np.array([rb, rc, rd]) @guvectorize([ "void(float32, float32[:], float32[:])", "void(float64, float64[:], float64[:])"], '(), (n) -> (n)') def _numba_quaternion_create(rot, vec, res): argument = np.radians(rot / 2) res[0] = np.cos(argument) # due to ufunc broadcasting rules vec must be of length 4, first entry is not used res[1] = vec[1] * np.sin(argument) res[2] = vec[2] * np.sin(argument) res[3] = vec[3] * np.sin(argument) @guvectorize([ "void(float32[:], float32[:])", "void(float64[:], float64[:])"], '(n) -> (n)') def _numba_quaternion_conjugate(q, res): res[0] = q[0] res[1:] = -q[1:] @guvectorize([ "void(float32[:], float32[:], float32[:])", "void(float64[:], float64[:], float64[:])"], '(n), (n) -> (n)') def _numba_quaternion_multiply(q1, q2, res): (q1a, q1b, q1c, q1d) = (q1[0], q1[1], q1[2], q1[3]) (q2a, q2b, q2c, q2d) = (q2[0], q2[1], q2[2], q2[3]) res[0] = q1a * q2a - q1b * q2b - q1c * q2c - q1d * q2d res[1] = q1a * q2b + q1b * q2a + q1c * q2d - q1d * q2c res[2] = q1a * q2c - q1b * q2d + q1c * q2a + q1d * q2b res[3] = q1a * q2d + q1b * q2c - q1c * q2b + q1d * q2a
3DCORE
/3DCORE-1.1.4.tar.gz/3DCORE-1.1.4/py3dcore/rotqs.py
rotqs.py