code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
| 2vyper | /2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/__init__.py | __init__.py |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
| 2vyper | /2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/backends/__init__.py | __init__.py |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
from typing import Dict, Tuple
from twovyper.translation.variable import TranslatedVar
from twovyper.viper.typedefs import Var
State = Dict[str, TranslatedVar]
LocalVarSnapshot = Dict[str, Tuple[int, Var, bool]]
| 2vyper | /2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/translation/__init__.py | __init__.py |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
"""
Copyright (c) 2021 ETH Zurich
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
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 |
# -*- coding: utf-8 -*-
from distutils.core import setup
package_dir = \
{'': 'src'}
packages = \
['2wf90_assignment']
package_data = \
{'': ['*'], '2wf90_assignment': ['unused/*']}
entry_points = \
{'console_scripts': ['2wf90 = entry:main']}
setup_kwargs = {
'name': '2wf90-assignment',
'version': '1.0.8',
'description': 'Our attempt at the first software assignment.',
'long_description': None,
'author': 'Your Name',
'author_email': 'you@example.com',
'url': None,
'package_dir': package_dir,
'packages': packages,
'package_data': package_data,
'entry_points': entry_points,
'python_requires': '>=3.7,<4.0',
}
setup(**setup_kwargs)
| 2wf90-assignment | /2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/setup.py | setup.py |
import argparse
import sys
from Context import *
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help='name of input file')
parser.add_argument('output', help='name of output file')
args = parser.parse_args()
input = open(args.input, 'r') if args.input else sys.stdin
output = open(args.output, 'w', encoding='utf-8')
context = Context()
if not args.input:
print('Interactive mode. Ctrl-Z plus Return to exit.')
def read_line(line, last_line = False):
out = context.read_line(line)
if last_line: out = out[:-1]
output.write(out)
if not args.input:
print(f'OUT: {repr(out)}')
for line in input:
read_line(line)
read_line('\n', True)
| 2wf90-assignment | /2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/entry.py | entry.py |
# All algorithms combined
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 |
# Use like this: "from classes import Integer".
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 |
from .entry import main
| 2wf90-assignment | /2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/__init__.py | __init__.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 |
# declare variables
integer1 = [5,6,14,1]#[4,2,8,2,3,4,5,7,8,8,3,4,6,3,5,6,4,3,5,6,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
integer2 = [0,0,3,11]#[6,4,0,9,4,6,7,8,6,4,7,5,7,5,3,6,7,8,6,1,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
radix1 = 16
radix2 = 16
positive1 = True
positive2 = False
# Regular multiplication alghorithm
def multiplication(integer1, interger2, radix1, radix2, positive1, positive2):
# Define variables for wordlength, sign, output
n = len(integer1)
output = [0]*2*n
positive = not (positive1 ^ positive2)
# Multiply all digits seperately and add in the list
for i in range(0, n):
digit2 = integer2[-(i+1)]
for j in range(0, n):
digit1 = integer1[-(j+1)]
outputNumber = digit1*digit2
output[-(1+i+j)] += outputNumber
# Calculate the carry and add to the next digit
for i in range(1, len(output)+1):
if output[-i] >= radix1:
carry = output[-i]//radix1
output[-i] = output[-i]%radix1
output[-(i+1)] += carry
# Return a tuple with the sign and output list
return(positive, output)
multiplication(integer1, integer2, radix1, radix2, positive1, positive2) | 2wf90-assignment | /2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/unused/Multiplication.py | Multiplication.py |
def simple_division(x, y, b):
#very slow for big x and small y, only used to calculate the floor of r / y*b^i in the long division function
q, r = '0', x
sumy = '0'
#this covers the base case, which is also the worst case for this algorithm
if y == '1':
q, r = x, '0'
#the while loop counts how many times y is in x, outputs that number (which is the quotient) and the remainder
while subtract_function(x, add_function(sumy, y, b), b)[0] is not "-":
#keeps track of q times y
sumy = add_function(sumy, y, b)
#updates the remainder
r = str(subtract_function(r, y, b))
#adds 1 to the quotient
q = str(add_function(q, 1, b))
# print(str(q) +"*" + str(y) + "+" + str(r) + "=" + str(x))
return [q, r]
| 2wf90-assignment | /2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/unused/simple_division.py | simple_division.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 |
def reduce_function(x, m, b):
x, m = str(x), str(m)
x1 = x.strip('-')
k, n = len(x1), len(m)
for i in range(k-n, -1, -1):
reduct_value = m
if i == 0:
pass
else:
#used to calculate m times the base to the power of i
for j in range(0, i):
reduct_value = reduct_value + '0'
while subtract_function(x1, reduct_value , b)[0] is not "-":
x1 = subtract_function(x1, reduct_value, b)
if (x[0] is not "-") or (x1 == '0'):
y = x1
else:
y = subtract_function(m, x1, b)
return y
| 2wf90-assignment | /2wf90-assignment-1.0.8.tar.gz/2wf90-assignment-1.0.8/src/2wf90_assignment/unused/reduction.py | reduction.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 |
import os
import subprocess
imgcat_path = None
# TODO: Thorough way to find executable path for different environments
if os.path.isfile(os.path.expanduser("~/bin/imgcat")):
imgcat_path = os.path.expanduser("~/bin/imgcat")
def imgcat(filename, width_chars=None, height_chars=None):
if not imgcat_path:
return ""
options = ["inline=1"]
if width_chars:
options.append(f"width={width_chars}")
if height_chars:
options.append(f"height={height_chars}")
img = subprocess.check_output([imgcat_path, filename]).decode("utf-8")
img = img.replace("inline=1", ";".join(options))
return img
| 2xh-leet | /2xh_leet-1.0.1-py3-none-any.whl/leet/imgcat.py | imgcat.py |
from .imgcat import imgcat
__all__ = ["imgcat"]
| 2xh-leet | /2xh_leet-1.0.1-py3-none-any.whl/leet/__init__.py | __init__.py |
import os
def cdwalker(cdrom,cdfile):
exports = ""
for root,dirs,files in os.walk(cdrom):
exports+= ("\n %s;%s;%s" % (root,dirs,files))
open(cdfile, 'w').write(exports)
#cdwalker("d:","f:\\Python32\\py\\export2.cdc")
cdwalker("F:\\music\\main music\\周杰伦","f:\\Python32\\py\\export1.cdc")
print("END")
| 3-1 | /3-1-1.0.0.zip/3-1-1.0.0/3-1.py | 3-1.py |
from distutils.core import setup
setup(
name = '3-1',
version = '1.0.0',
py_modules=['3-1'],
author='DuYong',
author_email='duy1102002@gmail.com',
url='www.baidu.com',
description='test',
)
| 3-1 | /3-1-1.0.0.zip/3-1-1.0.0/setup.py | setup.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 |
# `3`
`.gitignore`-aware tree tool written in Python.
Example:
```
3
```
Output:

## Install
```
pip3 install 3-py
```
### Compatibility
If you are on Windows, install `colorama` in order to watch some colors.
| 3-py | /3-py-1.1.6.tar.gz/3-py-1.1.6/README.md | README.md |
import os
import setuptools
with open(f"{os.path.dirname(os.path.abspath(__file__))}/README.md") as readme:
setuptools.setup(
name="3-py",
version="1.1.6",
description="`.gitignore`-aware tree tool written in Python",
long_description=readme.read(),
long_description_content_type="text/markdown",
author="Vladimir Chebotarev",
author_email="vladimir.chebotarev@gmail.com",
license="MIT",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Software Development",
"Topic :: Terminals",
"Topic :: Utilities",
],
keywords=["git", "gitignore", "tree"],
project_urls={
"Documentation": "https://github.com/excitoon/3/blob/master/README.md",
"Source": "https://github.com/excitoon/3",
"Tracker": "https://github.com/excitoon/3/issues",
},
url="https://github.com/excitoon/3",
packages=[],
scripts=["3", "3.cmd"],
install_requires=["gitignorefile"],
)
| 3-py | /3-py-1.1.6.tar.gz/3-py-1.1.6/setup.py | setup.py |
# 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 setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="31",
version="2.2",
author="Kavi Gupta",
author_email="31@kavigupta.org",
description="Runs code in a specified environment in the background and notifies you when it is done.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/kavigupta/31",
packages=setuptools.find_packages(),
entry_points={
"console_scripts": ["31=s31.main:main"],
},
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Operating System :: OS Independent",
],
python_requires=">=3.5",
install_requires=[
"attrs>=20.1.0",
"display-timedelta==1.1",
"filelock==3.0.12",
"appdirs>=1.4.4",
"permacache>=3.6.1",
],
)
| 31 | /31-2.2.tar.gz/31-2.2/setup.py | setup.py |
import os
import subprocess
import tempfile
import unittest
RC_TEST = os.path.join(os.path.dirname(__file__), "testrc.json")
class Test31(unittest.TestCase):
@staticmethod
def get_output(command, check=True, **kwargs):
path = tempfile.mktemp()
with open(path, "wb") as f:
try:
subprocess.run(
[*command, "--config-file", RC_TEST],
stdout=f,
stderr=subprocess.STDOUT,
check=check,
**kwargs
)
except subprocess.TimeoutExpired:
pass
with open(path) as f:
return f.read().split("\n")
def assertOutput(self, command, output, **kwargs):
actual = self.get_output(command, **kwargs)
print(actual)
self.assertEqual(actual, output)
| 31 | /31-2.2.tar.gz/31-2.2/tests/test31.py | test31.py |
from .test31 import Test31
import os
class TestOptions(Test31):
def test_sync(self):
self.assertOutput(
["31", "c", "--sync", "echo test"],
[
"test",
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = 'Process succeeded in 0 seconds: echo test'",
"BODY = 'test\\n'",
"",
],
)
def test_name(self):
self.assertOutput(
["31", "c", "-n", "testing command", "echo test"],
[
"BEGIN SCREEN",
"NAME = 'testing_command'",
"test",
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = 'Process succeeded in 0 seconds: echo test'",
"BODY = 'test\\n'",
"END SCREEN",
"",
],
)
def test_no_emails(self):
self.assertOutput(
["31", "c", "--no-email", "echo test"],
[
"BEGIN SCREEN",
"NAME = 'echo_test'",
"test",
"END SCREEN",
"",
],
)
def test_pwd(self):
self.assertOutput(
[
"31",
"c",
"-l",
"..",
"-n",
"testing command",
"python -c 'import os; print(os.getcwd())'",
],
[
"BEGIN SCREEN",
"NAME = 'testing_command'",
os.path.abspath(".."),
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = \"Process succeeded in 0 seconds: python -c 'import os; print(os.getcwd())'\"",
"BODY = '{}\\n'".format(os.path.abspath("..")),
"END SCREEN",
"",
],
)
| 31 | /31-2.2.tar.gz/31-2.2/tests/options_test.py | options_test.py |
from .test31 import Test31
class BasicTest(Test31):
def test_success(self):
outputs = self.get_output(
[
"31",
"c",
"-s",
"--no-email",
'python -u -c "import time, itertools; [(print(k), time.sleep(2)) for k in itertools.count()]"',
],
check=0,
timeout=5,
)
self.assertIn(outputs, [["0", "1", "2", ""], ["0", "1", ""]])
| 31 | /31-2.2.tar.gz/31-2.2/tests/buf_test.py | buf_test.py |
from .test31 import Test31
class BasicTest(Test31):
def test_success(self):
self.assertOutput(
["31", "c", "echo test"],
[
"BEGIN SCREEN",
"NAME = 'echo_test'",
"test",
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = 'Process succeeded in 0 seconds: echo test'",
"BODY = 'test\\n'",
"END SCREEN",
"",
],
)
def test_failure(self):
self.assertOutput(
["31", "c", "exit 17"],
[
"BEGIN SCREEN",
"NAME = 'exit_17'",
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = 'Process failed with code 17 in 0 seconds: exit 17'",
"BODY = ''",
"END SCREEN",
"",
],
)
def test_multiline_output(self):
self.assertOutput(
["31", "c", "echo 2; echo 3"],
[
"BEGIN SCREEN",
"NAME = 'echo_2_echo_3'",
"2",
"3",
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = 'Process succeeded in 0 seconds: echo 2; echo 3'",
"BODY = '2\\n3\\n'",
"END SCREEN",
"",
],
)
def test_stdout_stderr_output(self):
self.assertOutput(
["31", "c", "echo 2; python3 -c 'import sys; print(3, file=sys.stderr)'"],
[
"BEGIN SCREEN",
"NAME = 'echo_2_python3_c_import_sys_print_3_file_sys.stderr'",
"2",
"3",
"SENDING EMAIL",
"TO = 'test@example.com'",
"SUBJECT = \"Process succeeded in 0 seconds: echo 2; python3 -c 'import sys; print(3, file=sys.stderr)'\"",
"BODY = '2\\n3\\n'",
"END SCREEN",
"",
],
)
| 31 | /31-2.2.tar.gz/31-2.2/tests/basic_test.py | basic_test.py |
import unittest
from .test31 import Test31
from s31.foreach import parse_foreach_statement, parse_foreach_statements
class TestForeachAPI(unittest.TestCase):
def test_single_statement(self):
self.assertEqual(
[[("%x", "1")], [("%x", "2")], [("%x", "3")]],
parse_foreach_statement(["%x", "1,2,3"]),
)
def test_zipped_statement(self):
self.assertEqual(
[
[("%x", "1"), ("%y", "a")],
[("%x", "2"), ("%y", "b")],
[("%x", "3"), ("%y", "c")],
],
parse_foreach_statement(["%x", "%y", "1,2,3", "a,b,c"]),
)
def test_multiple_statements(self):
self.assertEqual(
[
[("%x", "1"), ("%y", "a")],
[("%x", "1"), ("%y", "b")],
[("%x", "2"), ("%y", "a")],
[("%x", "2"), ("%y", "b")],
],
parse_foreach_statements([["%x", "1,2"], ["%y", "a,b"]]),
)
class TestForeachCLI(Test31):
def test_basic_foreach(self):
self.assertOutput(
["31", "c", "--no-email", "-s", "-f", "%x", "1,2,3", "echo %x"],
["1", "2", "3", ""],
)
def test_csv_foreach(self):
self.assertOutput(
["31", "c", "--no-email", "-s", "-f", "%x", '",",2,3', "echo %x"],
[",", "2", "3", ""],
)
def test_zip_foreach(self):
self.assertOutput(
[
"31",
"c",
"--no-email",
"-s",
"-f3",
"%x",
"%y",
"%z",
"1,2,3",
"a,b,c",
"x,y,z",
"echo %x %y %z",
],
["1 a x", "2 b y", "3 c z", ""],
)
def test_prod_foreach(self):
self.assertOutput(
[
"31",
"c",
"--no-email",
"-s",
"-f",
"%x",
"1,2,3",
"-f",
"%y",
"a,b",
"echo %x %y",
],
["1 a", "1 b", "2 a", "2 b", "3 a", "3 b", ""],
)
def test_screen_foreach(self):
self.assertOutput(
[
"31",
"c",
"--no-email",
"-f",
"%x",
"1,2,3",
"-f",
"%y",
"a,b",
"echo %x %y",
],
[
"BEGIN SCREEN",
"NAME = 'echo_1_a'",
"1 a",
"END SCREEN",
"BEGIN SCREEN",
"NAME = 'echo_1_b'",
"1 b",
"END SCREEN",
"BEGIN SCREEN",
"NAME = 'echo_2_a'",
"2 a",
"END SCREEN",
"BEGIN SCREEN",
"NAME = 'echo_2_b'",
"2 b",
"END SCREEN",
"BEGIN SCREEN",
"NAME = 'echo_3_a'",
"3 a",
"END SCREEN",
"BEGIN SCREEN",
"NAME = 'echo_3_b'",
"3 b",
"END SCREEN",
"",
],
)
def test_screen_foreach_name(self):
self.assertOutput(
[
"31",
"c",
"--no-email",
"-f",
"%x",
"1,2,3",
"-f",
"%y",
"a,b",
"-n %x_%y",
"echo %x %y",
],
[
"BEGIN SCREEN",
"NAME = '1_a'",
"1 a",
"END SCREEN",
"BEGIN SCREEN",
"NAME = '1_b'",
"1 b",
"END SCREEN",
"BEGIN SCREEN",
"NAME = '2_a'",
"2 a",
"END SCREEN",
"BEGIN SCREEN",
"NAME = '2_b'",
"2 b",
"END SCREEN",
"BEGIN SCREEN",
"NAME = '3_a'",
"3 a",
"END SCREEN",
"BEGIN SCREEN",
"NAME = '3_b'",
"3 b",
"END SCREEN",
"",
],
)
| 31 | /31-2.2.tar.gz/31-2.2/tests/foreach_test.py | foreach_test.py |
from .test31 import Test31
class WorkersTest(Test31):
# TODO(kavigupta) we probably should have some way to test the async aspect, which we aren't doing
def test_fw(self):
self.assertOutput(
[
"31",
"c",
"-s",
"-w",
"2",
"-fw",
"%w",
"w1,w2",
"-f",
"%x",
"a,b,c",
"--no-email",
"echo %x.%w",
],
[
"Completed: 0, In Progress: 0, Queued: 3",
"Launching echo_a.w1",
"BEGIN SCREEN",
"NAME = 'echo_a.w1'",
"a.w1",
"END SCREEN",
"Completed: 1, In Progress: 0, Queued: 2",
"Launching echo_b.w1",
"BEGIN SCREEN",
"NAME = 'echo_b.w1'",
"b.w1",
"END SCREEN",
"Completed: 2, In Progress: 0, Queued: 1",
"Launching echo_c.w1",
"BEGIN SCREEN",
"NAME = 'echo_c.w1'",
"c.w1",
"END SCREEN",
"All tasks completed",
"",
],
)
def test_worker_thread(self):
self.assertOutput(
[
"31",
"c",
"-w",
"2",
"-fw",
"%w",
"w1,w2",
"-f",
"%x",
"a,b,c",
"--no-email",
"echo %x.%w",
],
[
"BEGIN SCREEN",
"NAME = 'worker-monitor'",
"Completed: 0, In Progress: 0, Queued: 3",
"Launching echo_a.w1",
"BEGIN SCREEN",
"NAME = 'echo_a.w1'",
"a.w1",
"END SCREEN",
"Completed: 1, In Progress: 0, Queued: 2",
"Launching echo_b.w1",
"BEGIN SCREEN",
"NAME = 'echo_b.w1'",
"b.w1",
"END SCREEN",
"Completed: 2, In Progress: 0, Queued: 1",
"Launching echo_c.w1",
"BEGIN SCREEN",
"NAME = 'echo_c.w1'",
"c.w1",
"END SCREEN",
"All tasks completed",
"END SCREEN",
"",
],
)
def test_named_worker_thread(self):
self.assertOutput(
[
"31",
"c",
"-w",
"2",
"-wn",
"abc",
"-fw",
"%w",
"w1,w2",
"-f",
"%x",
"a,b,c",
"--no-email",
"echo %x.%w",
],
[
"BEGIN SCREEN",
"NAME = 'abc'",
"Completed: 0, In Progress: 0, Queued: 3",
"Launching echo_a.w1",
"BEGIN SCREEN",
"NAME = 'echo_a.w1'",
"a.w1",
"END SCREEN",
"Completed: 1, In Progress: 0, Queued: 2",
"Launching echo_b.w1",
"BEGIN SCREEN",
"NAME = 'echo_b.w1'",
"b.w1",
"END SCREEN",
"Completed: 2, In Progress: 0, Queued: 1",
"Launching echo_c.w1",
"BEGIN SCREEN",
"NAME = 'echo_c.w1'",
"c.w1",
"END SCREEN",
"All tasks completed",
"END SCREEN",
"",
],
)
| 31 | /31-2.2.tar.gz/31-2.2/tests/workers_test.py | workers_test.py |
from datetime import datetime
from display_timedelta import display_timedelta
FORMAT = "%Y.%m.%d.%H.%M.%S.%f"
def notify(config, command, runner):
start = datetime.now()
path = datetime.strftime(start, FORMAT)
logfile = config.create_log_file(path)
exitcode = runner.run_checking_interrupt(lambda: command.run_teed(logfile), logfile)
end = datetime.now()
with open(logfile, "rb") as f:
log_contents = f.read()
delta = end - start
subject = "{} in {}: {}".format(
"Process succeeded"
if exitcode == 0
else "Process interrupted"
if exitcode == "interrupted"
else "Process failed with code {}".format(exitcode),
display_timedelta(delta).replace("right now", "0 seconds"),
command.cmd_line,
)
config.send_mail(subject, log_contents)
| 31 | /31-2.2.tar.gz/31-2.2/s31/notify.py | notify.py |
import attr
import sys
import subprocess
from .utils import format_assignments
@attr.s
class Command:
cmd_line = attr.ib()
location = attr.ib()
def run_teed(self, logfile):
with open(logfile, "wb") as f:
def write(x):
f.write(x)
sys.stdout.buffer.write(x)
f.flush()
sys.stdout.flush()
p = subprocess.Popen(
self.cmd_line,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
**self.kwargs
)
while p.poll() is None:
line = p.stdout.read(1)
if line:
write(line)
while True:
line = p.stdout.readline()
if line:
write(line)
else:
break
return p.returncode
def replace(self, assignments):
return Command(
cmd_line=format_assignments(self.cmd_line, assignments),
location=format_assignments(self.location, assignments),
)
@property
def kwargs(self):
kwargs = dict(shell=1, bufsize=0)
if self.location is not None:
kwargs["cwd"] = self.location
return kwargs
def run(self):
subprocess.run(self.cmd_line, **self.kwargs)
def dry_run(self):
print(self.cmd_line)
| 31 | /31-2.2.tar.gz/31-2.2/s31/command.py | command.py |
import sys
import subprocess
import re
def get_screen_program(name):
if name == "screen":
return _screen
if name == "test":
return _test
else:
raise RuntimeError("Only screen is currently supported as a screen_program")
def _screen(command, name):
name = re.sub(r"[^A-Za-z0-9-._, ]", "-", name)
screen_command = ["screen", "-S", name, "-d", "-m", "--", *command]
subprocess.check_call(screen_command)
def _test(command, name):
print("BEGIN SCREEN")
print("NAME =", repr(name))
sys.stdout.flush()
subprocess.run(command)
sys.stdout.flush()
print("END SCREEN")
sys.stdout.flush()
| 31 | /31-2.2.tar.gz/31-2.2/s31/screen.py | screen.py |
import os
import re
import json
from .mail import get_mail_program
from .screen import get_screen_program
DEFAULT_CONFIG = dict(
log_location=os.path.expanduser("~/.log"),
mail_program="detect",
screen_program="screen",
)
class Config:
def __init__(self, config_file):
config = _load_config(config_file)
self._config = dict(DEFAULT_CONFIG)
self._config.update(config)
self._mail_program = get_mail_program(self._config["mail_program"])
self._screen_program = get_screen_program(self._config["screen_program"])
if "email" not in self._config:
raise RuntimeError(
"You need to provide an email address, please run `31 config email youraddress@example.com` to set this up"
)
self._email = self._config["email"]
def create_log_file(self, path):
ll = self._config["log_location"]
try:
os.makedirs(ll)
except FileExistsError:
pass
return os.path.join(ll, path)
def send_mail(self, subject, body):
return self._mail_program(to=self._email, subject=subject, body=body)
def launch_screen(self, command, name):
return self._screen_program(command=command, name=name)
def _load_config(config_file):
try:
with open(config_file) as f:
return json.load(f)
except FileNotFoundError:
return {}
def update_config(config_file, new_config):
config = _load_config(config_file)
config.update(new_config)
with open(config_file, "w") as f:
json.dump(config, f)
| 31 | /31-2.2.tar.gz/31-2.2/s31/config.py | config.py |
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 os
from appdirs import user_cache_dir
from permacache.locked_shelf import LockedShelf
def active_process_table():
return LockedShelf(
os.path.join(user_cache_dir("s31"), "active_process_table"),
multiprocess_safe=True,
)
| 31 | /31-2.2.tar.gz/31-2.2/s31/active_process_table.py | active_process_table.py |
import subprocess
import re
import shelve
from filelock import FileLock
def output_matches(command, regex):
output = subprocess.run(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
).stdout
return re.match(regex, output.decode("utf-8"))
def format_assignments(value, assignments):
if value is None:
return value
for var, val in assignments:
value = value.replace(var, val)
return value
def sanitize(name):
return re.sub("[^A-Za-z0-9_.]+", "_", name).strip("_")
def set_key(file, key):
with FileLock(file + ".lock"):
with shelve.open(file + ".shelve") as s:
s[key] = True
def get_keys(file):
with FileLock(file + ".lock"):
with shelve.open(file + ".shelve") as s:
return {k for k in s if s[k]}
| 31 | /31-2.2.tar.gz/31-2.2/s31/utils.py | utils.py |
import subprocess
import sys
from .utils import output_matches
def get_mail_program(program_name):
if program_name == "detect":
if output_matches("mail -V", "^mail \(GNU Mailutils\).*"):
program_name = "gnu_mail"
elif output_matches("mutt -h", "Mutt .*"):
program_name = "mutt"
else:
raise RuntimeError(
"Could not detect a mail program. Please see the documentation for a list of supported programs."
)
return dict(gnu_mail=_gnu_mail, mutt=_mutt, test=_test)[program_name]
def _gnu_mail(to, subject, body):
subprocess.run(["mail", "-s", subject, to], input=body)
def _mutt(to, subject, body):
subprocess.run(["mutt", "-s", subject, to], input=body)
def _test(to, subject, body):
print("SENDING EMAIL")
print("TO =", repr(to))
print("SUBJECT =", repr(subject))
print("BODY =", repr(body.decode("utf-8")))
sys.stdout.flush()
| 31 | /31-2.2.tar.gz/31-2.2/s31/mail.py | mail.py |
import tempfile
import uuid
import time
from .utils import get_keys
def dispatch_workers(num_workers, launch_worker, arguments):
used_workers = [None] * num_workers
arguments = arguments[::-1] # so we can pop from the back
completed = 0
file = tempfile.mktemp()
while True:
# check if any workers have completed
dones = get_keys(file)
for i, x in enumerate(used_workers):
if x in dones:
completed += 1
used_workers[i] = None
free = [i for i, w in enumerate(used_workers) if w is None]
if len(free) == num_workers and not arguments:
print("All tasks completed")
return
print(
"Completed: {}, In Progress: {}, Queued: {}".format(
completed, num_workers - len(free), len(arguments)
)
)
if not free or not arguments:
# Wait for some process to become free, or just wait for everything to end
time.sleep(1)
continue
worker_idx = free[0]
used_workers[worker_idx] = str(uuid.uuid4())
launch_worker(worker_idx, arguments.pop(), file, used_workers[worker_idx])
| 31 | /31-2.2.tar.gz/31-2.2/s31/workers.py | workers.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 |
import itertools
import csv
MAX_FOREACHES = 9
def parse_foreach_args(args):
foreach = []
if args.foreach is not None:
foreach += args.foreach
for k in range(2, 1 + MAX_FOREACHES):
foreach_k = getattr(args, "foreach_{}".format(k))
if foreach_k is not None:
foreach += foreach_k
return parse_foreach_statements(foreach)
def parse_foreach_statements(foreach):
all_assigns = [
list(itertools.chain(*x))
for x in itertools.product(
*[parse_foreach_statement(statement) for statement in foreach]
)
]
return all_assigns
def parse_foreach_statement(statement):
assert statement, "must provide at least one element"
assert len(statement) % 2 == 0, "must provide an even number of elements"
k = len(statement) // 2
variables = statement[:k]
values = statement[k:]
values = [parse_values(v) for v in values]
for v in values:
if len(v) != len(values[0]):
raise RuntimeError(
"Values must be the same length but have lengths of {} ({!r}) vs {} ({!r})".format(
len(values[0]), values[0], len(v), v
)
)
return [
[(variable, v) for variable, v in zip(variables, vals)]
for vals in list(zip(*values))
]
def parse_values(values):
return list(csv.reader([values]))[0]
| 31 | /31-2.2.tar.gz/31-2.2/s31/foreach.py | foreach.py |
import os
from datetime import timedelta
import signal
import time
from display_timedelta import display_timedelta
from .active_process_table import active_process_table
from .interruptable_runner import clean_table
def load_processes(prefix, ordering):
with active_process_table() as t:
clean_table(t)
t = dict(t.items())
if prefix is not None:
t = {k: v for k, v in t.items() if v["name"].startswith(prefix)}
return sorted(t.values(), key=lambda x: x[ordering])
def list_procesess(prefix, ordering):
processes = load_processes(prefix, ordering)
with_prefix = f"with prefix {prefix!r} " if prefix is not None else ""
print(f"Active processes {with_prefix}({len(processes)}):")
for proc in processes:
print(render(proc))
def render(proc):
return f"- {proc['name']} ({proc['pid']}) [started {display_timedelta(timedelta(seconds=time.time() - proc['timestamp']))} ago] {{{proc['cmd']}}}"
def stop_process(name):
if len(name) == 0:
print("No process name specified")
return 1
with_name_prefix = load_processes(name, "timestamp")
if len(with_name_prefix) == 0:
print(f"No process with name {name!r} found")
return 1
if with_name_prefix != [name]:
print(f"Processes with prefix {name!r}:")
for proc in with_name_prefix:
print(render(proc))
if input("Do you want to stop all of them? [y/N] ") != "y":
print("Aborting")
return 1
for proc in with_name_prefix:
stop(proc)
return 0
stop(name)
return 0
def stop(proc):
print(f"Stopping {render(proc)}")
os.kill(proc["pid"], signal.SIGINT)
| 31 | /31-2.2.tar.gz/31-2.2/s31/process_manager.py | process_manager.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 |
/* This is a generated file of CSS imports */
/* It was generated by @jupyterlab/builder in Build.ensureAssets() */
import '310_notebook/style/index.js';
| 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.js | style.js |
import json
from pathlib import Path
__all__ = ["__version__"]
def _fetchVersion():
HERE = Path(__file__).parent.resolve()
for settings in HERE.rglob("package.json"):
try:
with settings.open() as f:
version = json.load(f)["version"]
return (
version.replace("-alpha.", "a")
.replace("-beta.", "b")
.replace("-rc.", "rc")
)
except FileNotFoundError:
pass
raise FileNotFoundError(f"Could not find package.json under dir {HERE!s}")
__version__ = _fetchVersion()
| 310-notebook | /310_notebook-0.1.0-py3-none-any.whl/310_notebook/_version.py | _version.py |
import json
from pathlib import Path
from ._version import __version__
HERE = Path(__file__).parent.resolve()
with (HERE / "labextension" / "package.json").open() as fid:
data = json.load(fid)
def _jupyter_labextension_paths():
return [{
"src": "labextension",
"dest": data["name"]
}]
| 310-notebook | /310_notebook-0.1.0-py3-none-any.whl/310_notebook/__init__.py | __init__.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/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 |
/* This is a generated file of CSS imports */
/* It was generated by @jupyterlab/builder in Build.ensureAssets() */
import '310_notebook/style/index.js';
| 310-notebook | /310_notebook-0.1.0-py3-none-any.whl/310_notebook/labextension/static/style.js | style.js |
UNKNOWN
| 310 | /310-0.1.0-py3-none-any.whl/310-0.1.0.dist-info/DESCRIPTION.rst | DESCRIPTION.rst |
310 | /310-0.1.0-py3-none-any.whl/extras/multiply.py | multiply.py |
|
310 | /310-0.1.0-py3-none-any.whl/extras/divide.py | divide.py |
|
from multiply import multiply
from divide import divide
| 310 | /310-0.1.0-py3-none-any.whl/extras/__init__.py | __init__.py |
#!/usr/bin/env python3
from . import main
main()
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/__main__.py | __main__.py |
__version__ = '0.7.3'
import logging
import click
from .asset.builder import AssetTool
from .tool.cmake import cmake_cli
from .tool.dfu import dfu_cli
from .tool.flasher import flash_cli, install_cli, launch_cli
from .tool.metadata import metadata_cli
from .tool.packer import pack_cli
from .tool.relocs import relocs_cli
from .tool.setup import setup_cli
@click.group()
@click.option('--debug', is_flag=True)
@click.option('-v', '--verbose', count=True)
def main(debug, verbose):
log_format = '%(levelname)s: %(message)s'
log_verbosity = min(verbose, 3)
log_level = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG][log_verbosity]
logging.basicConfig(level=log_level, format=log_format)
for n, c in AssetTool._commands.items():
main.add_command(c)
main.add_command(cmake_cli)
main.add_command(flash_cli)
main.add_command(install_cli)
main.add_command(launch_cli)
main.add_command(metadata_cli)
main.add_command(pack_cli)
main.add_command(relocs_cli)
main.add_command(setup_cli)
main.add_command(dfu_cli)
@main.command(help='Print version and exit')
def version():
print(__version__)
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/__init__.py | __init__.py |
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 textwrap
from ..formatter import AssetFormatter
wrapper = textwrap.TextWrapper(
break_on_hyphens=False, initial_indent=' ', subsequent_indent=' ', width=80
)
def c_initializer(data):
if type(data) is str:
data = data.encode('utf-8')
values = ', '.join(f'0x{c:02x}' for c in data)
return f' = {{\n{wrapper.fill(values)}\n}}'
def c_declaration(types, symbol, data=None):
return textwrap.dedent(
'''\
{types} uint8_t {symbol}[]{initializer};
{types} uint32_t {symbol}_length{size};
'''
).format(
types=types,
symbol=symbol,
initializer=c_initializer(data) if data else '',
size=f' = sizeof({symbol})' if data else '',
)
def c_boilerplate(data, include, header=True):
lines = ['// Auto Generated File - DO NOT EDIT!']
if header:
lines.append('#pragma once')
lines.append(f'#include <{include}>')
lines.append('')
lines.extend(data)
return '\n'.join(lines)
@AssetFormatter(extensions=('.hpp', '.h'))
def c_header(symbol, data):
return {None: c_declaration('inline const', symbol, data)}
@c_header.joiner
def c_header(path, fragments):
return {None: c_boilerplate(fragments[None], include="cstdint", header=True)}
@AssetFormatter(components=('hpp', 'cpp'), extensions=('.cpp', '.c'))
def c_source(symbol, data):
return {
'hpp': c_declaration('extern const', symbol),
'cpp': c_declaration('const', symbol, data),
}
@c_source.joiner
def c_source(path, fragments):
include = path.with_suffix('.hpp').name
return {
'hpp': c_boilerplate(fragments['hpp'], include='cstdint', header=True),
'cpp': c_boilerplate(fragments['cpp'], include=include, header=False),
}
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/asset/formatters/c.py | c.py |
from ..formatter import AssetFormatter
@AssetFormatter(extensions=('.raw', '.bin'))
def raw_binary(symbol, data):
return {None: data}
@raw_binary.joiner
def raw_binary(path, fragments):
return {None: b''.join(fragments[None])}
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/asset/formatters/raw.py | raw.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 |
from ..builder import AssetBuilder, AssetTool
binary_typemap = {
'binary': {
'.bin': True,
'.raw': True,
},
'csv': {
'.csv': True
}
}
def csv_to_list(input_data, base):
if type(input_data) == bytes:
input_data = input_data.decode('utf-8')
# Strip leading/trailing whitespace
input_data = input_data.strip()
# Replace '1, 2, 3' to '1,2,3', might as well do it here
input_data = input_data.replace(' ', '')
# Split out into rows on linebreak
input_data = input_data.split('\n')
# Split every row into columns on the comma
input_data = [row.split(',') for row in input_data]
# Flatten our rows/cols 2d array into a 1d array of bytes
# Might as well do the int conversion here, to save another loop
return [int(col, base) for row in input_data for col in row if col != '']
@AssetBuilder(typemap=binary_typemap)
def raw(data, subtype):
if subtype == 'csv':
return bytes(csv_to_list(data, base=10))
else:
return data
@AssetTool(raw, 'Convert raw/binary or csv data for 32Blit')
def raw_cli(input_file, input_type):
return raw.from_file(input_file, input_type)
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/asset/builders/raw.py | raw.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 pathlib
import click
from ..core import dfu
@click.group('dfu', help='Pack or unpack DFU files')
def dfu_cli():
pass
@dfu_cli.command(help='Pack a .bin file into a DFU file')
@click.option('--input-file', type=pathlib.Path, help='Input .bin', required=True)
@click.option('--output-file', type=pathlib.Path, help='Output .dfu', required=True)
@click.option('--address', type=int, help='Offset address', default=0x08000000)
@click.option('--force/--no-force', help='Force file overwrite', default=True)
def build(input_file, output_file, address, force):
dfu.build(input_file, output_file, address, force)
@dfu_cli.command(help='Dump the .bin parts of a DFU file')
@click.option('--input-file', type=pathlib.Path, help='Input .bin', required=True)
@click.option('--force/--no-force', help='Force file overwrite', default=True)
def dump(input_file, force):
dfu.dump(input_file, force)
@dfu_cli.command(help='Read information from a DFU file')
@click.option('--input-file', type=pathlib.Path, help='Input .bin', required=True)
def read(input_file):
parsed = dfu.read(input_file)
dfu.display_dfu_info(parsed)
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/tool/dfu.py | dfu.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 logging
import os
import pathlib
import re
import shutil
import stat
import subprocess
import textwrap
import click
# check environment before prompting
class SetupCommand(click.Command):
def parse_args(self, ctx, args):
logging.info("Checking for prerequisites...")
# command/name/required version
prereqs = [
('git --version', 'Git', None),
('cmake --version', 'CMake', [3, 9]),
('arm-none-eabi-gcc --version', 'GCC Arm Toolchain', [7, 3])
]
# adjust path to dectct the VS Arm toolchain
path = os.getenv('PATH')
vs_dir = os.getenv('VSInstallDir')
if vs_dir:
path = ';'.join([path, vs_dir + 'Linux\\gcc_arm\\bin'])
print(path)
failed = False
for command, name, version in prereqs:
try:
result = subprocess.run(command, stdout=subprocess.PIPE, text=True, shell=True, env={'PATH': path})
version_str = ".".join([str(x) for x in version]) if version else 'any'
found_version_str = re.search(r'[0-9]+\.[0-9\.]+', result.stdout).group(0)
if version:
found_version_list = [int(x) for x in found_version_str.split('.')[:len(version)]]
if found_version_list < version:
logging.critical(f'Found {name} version {found_version_str}, {version_str} is required!')
failed = True
logging.info(f'Found {name} version {found_version_str} (required {version_str})')
except subprocess.CalledProcessError:
logging.critical(f'Could not find {name}!')
failed = True
if failed:
click.echo('\nCheck the documentation for info on installing.\nhttps://github.com/32blit/32blit-sdk#you-will-need')
raise click.Abort()
super().parse_args(ctx, args)
def install_sdk(sdk_path):
click.echo('Installing SDK...')
subprocess.run(['git', 'clone', 'https://github.com/32blit/32blit-sdk', str(sdk_path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# checkout the latest release
# TODO: could do something with the GitHub API and download the release?
result = subprocess.run(['git', 'describe', '--tags', '--abbrev=0'], cwd=sdk_path, text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
latest_tag = result.stdout.strip()
result = subprocess.run(['git', 'checkout', latest_tag], cwd=sdk_path, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def vscode_config(project_path, sdk_path):
(project_path / '.vscode').mkdir()
open(project_path / '.vscode' / 'settings.json', 'w').write(textwrap.dedent(
'''
{
"cmake.configureSettings": {
"32BLIT_DIR": "{sdk_path}"
},
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"
}
'''.replace('{sdk_path}', str(sdk_path).replace('\\', '\\\\'))))
open(project_path / '.vscode' / 'cmake-kits.json', 'w').write(textwrap.dedent(
'''
[
{
"name": "32blit",
"toolchainFile": "{sdk_path}/32blit.toolchain"
}
]
'''.replace('{sdk_path}', str(sdk_path).replace('\\', '\\\\'))))
def visualstudio_config(project_path, sdk_path):
open(project_path / 'CMakeSettings.json', 'w').write(textwrap.dedent(
'''
{
"configurations": [
{
"name": "x64-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"inheritEnvironments": [ "msvc_x64_x64" ],
"buildRoot": "${projectDir}\\\\out\\\\build\\\\${name}",
"installRoot": "${projectDir}\\\\out\\\\install\\\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"variables": [
{
"name": "32BLIT_DIR",
"value": "{sdk_path}",
"type": "PATH"
}
]
},
{
"name": "x64-Release",
"generator": "Ninja",
"configurationType": "Release",
"buildRoot": "${projectDir}\\\\out\\\\build\\\\${name}",
"installRoot": "${projectDir}\\\\out\\\\install\\\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"inheritEnvironments": [ "msvc_x64_x64" ],
"variables": [
{
"name": "32BLIT_DIR",
"value": "{sdk_path}",
"type": "PATH"
}
]
},
{
"name": "32Blit-Debug",
"generator": "Ninja",
"configurationType": "Debug",
"buildRoot": "${projectDir}\\\\out\\\\build\\\\${name}",
"installRoot": "${projectDir}\\\\out\\\\install\\\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"inheritEnvironments": [ "gcc-arm" ],
"variables": [],
"cmakeToolchain": "{sdk_path}\\\\32blit.toolchain",
"intelliSenseMode": "linux-gcc-arm"
},
{
"name": "32Blit-Release",
"generator": "Ninja",
"configurationType": "Release",
"buildRoot": "${projectDir}\\\\out\\\\build\\\\${name}",
"installRoot": "${projectDir}\\\\out\\\\install\\\\${name}",
"cmakeCommandArgs": "",
"buildCommandArgs": "",
"ctestCommandArgs": "",
"cmakeToolchain": "{sdk_path}\\\\32blit.toolchain",
"inheritEnvironments": [ "gcc-arm" ],
"variables": [],
"intelliSenseMode": "linux-gcc-arm"
}
]
}
'''.replace('{sdk_path}', str(sdk_path).replace('\\', '\\\\'))))
@click.command('setup', help='Setup a project', cls=SetupCommand)
@click.option('--project-name', prompt=True)
@click.option('--author-name', prompt=True)
@click.option('--sdk-path', type=pathlib.Path, default=lambda: os.path.expanduser('~/32blit-sdk'), prompt='32Blit SDK path')
@click.option('--git/--no-git', prompt='Initialise a Git repository?', default=True)
@click.option('--vscode/--no-vscode', prompt='Create VS Code configuration?', default=True)
@click.option('--visualstudio/--no-visualstudio', prompt='Create Visual Studio configuration?')
def setup_cli(project_name, author_name, sdk_path, git, vscode, visualstudio):
if not (sdk_path / '32blit.toolchain').exists():
click.confirm(f'32Blit SDK not found at "{sdk_path}", would you like to install it?', abort=True)
install_sdk(sdk_path)
project_name_clean = re.sub(r'[^a-z0-9]+', '-', project_name.lower()).strip('-')
project_path = pathlib.Path.cwd() / project_name_clean
if project_path.exists():
logging.critical(f'A project already exists at {project_path}!')
raise click.Abort()
# get the boilerplate
click.echo('Downloading boilerplate...')
subprocess.run(['git', 'clone', '--depth', '1', 'https://github.com/32blit/32blit-boilerplate', str(project_path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# de-git it (using the template on GitHub also removes the history)
def remove_readonly(func, path, _):
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree(pathlib.Path(project_name_clean) / '.git', onerror=remove_readonly)
# do some editing
cmakelists = open(project_path / 'CMakeLists.txt').read()
cmakelists = cmakelists.replace('project(game)', f'project({project_name_clean})')
open(project_path / 'CMakeLists.txt', 'w').write(cmakelists)
metadata = open(project_path / 'metadata.yml').read()
metadata = metadata.replace('game title', project_name).replace('you', author_name)
open(project_path / 'metadata.yml', 'w').write(metadata)
licence = open(project_path / 'LICENSE').read()
licence = licence.replace('<insert your name>', author_name)
open(project_path / 'LICENSE', 'w').write(licence)
# re-git it if we want a git repo
if git:
subprocess.run(['git', 'init'], cwd=project_path, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(['git', 'add', '.'], cwd=project_path, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(['git', 'commit', '-m', 'Initial commit'], cwd=project_path, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if vscode:
vscode_config(project_path, sdk_path)
if visualstudio:
visualstudio_config(project_path, sdk_path)
click.echo(f'\nYour new project has been created in: {project_path}!')
click.echo(f'If using CMake directly, make sure to pass -DCMAKE_TOOLCHAIN_FILE={sdk_path / "32blit.toolchain"} (building for the device)\nor -D32BLIT_DIR={sdk_path} when calling cmake.')
| 32blit | /32blit-0.7.3-py3-none-any.whl/ttblit/tool/setup.py | setup.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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.