code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.unify.exception as _exceptions from ._ktadapt import * NoUnifyException = _exceptions.NoUnifyException OccurCheckException = _exceptions.OccurCheckException logger.debug("Loaded JVM classes from it.unibo.tuprolog.unify.exception.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/unify/exception/__init__.py
__init__.py
from collections import Mapping from itertools import chain from tuprolog import logger # noinspection PyUnresolvedReferences import jpype from tuprolog.pyutils import iterable_or_varargs @jpype.JImplementationFor("it.unibo.tuprolog.solve.SolverFactory") class _KtSolverFactory: def __jclass_init__(self): pass @jpype.JImplementationFor("it.unibo.tuprolog.solve.SolveOptions") class _KtSolveOptions: _static_keys = {'lazy', 'is_lazy', 'eager', 'is_eager', 'timeout', 'limit'} def __jclass_init__(self): Mapping.register(self) @property def is_lazy(self): return self.isLazy() @property def is_eager(self): return self.isEager() @property def timeout(self): return self.getTimeout() @property def limit(self): return self.getLimit() @property def options(self): return self.getOptions() def __len__(self): return 4 + len(self.options) def __iter__(self): return chain(_KtSolveOptions._static_keys, self.options) def __contains__(self, item): return item in _KtSolveOptions._static_keys def __getitem__(self, item, default=None): if item in {'lazy', 'is_lazy'}: return self.is_lazy elif item in {'eager', 'is_eager'}: return self.is_eager elif item == 'timeout': return self.timeout elif item == 'limit': return self.limit elif item in self.options: return self.options[item] elif default is not None: return default return KeyError(f"No such option: {item}") @jpype.JImplementationFor("it.unibo.tuprolog.solve.ExecutionContextAware") class _KtExecutionContextAware: def __jclass_init__(self): pass @property def libraries(self): return self.getLibraries() @property def flags(self): return self.getFlags() @property def static_kb(self): return self.getStaticKb() @property def dynamic_kb(self): return self.getDynamicKb() @property def operators(self): return self.getOperators() @property def input_channels(self): return self.getInputChannles() @property def output_channels(self): return self.getOutputChannles() @property def standard_output(self): return self.getStandardOutput() @property def standard_input(self): return self.getStandardInput() @property def standard_error(self): return self.getStandardError() @property def warnings(self): return self.getWarnings() @jpype.JImplementationFor("it.unibo.tuprolog.solve.Solver") class _KtSolver: def __jclass_init__(self): pass @jpype.JOverride def solve(self, goal, options=None): if options is None: return self.solve_(goal) elif options.is_eager: return self.solveList(goal, options) else: return self.solve_(goal, options) @jpype.JOverride def solve_once(self, goal, options=None): if options is None: return self.solveOnce(goal) else: return self.solveOnce(goal, options) @jpype.JImplementationFor("it.unibo.tuprolog.solve.MutableSolver") class _KtMutableSolver: def __jclass_init__(self): pass def load_library(self, library): return self.loadLibrary(library) def unload_library(self, library): return self.unloadLibrary(library) def set_libraries(self, libraries): return self.setLibraries(libraries) def load_static_kb(self, theory): return self.loadStaticKb(theory) def load_static_clauses(self, *clauses): return iterable_or_varargs(clauses, lambda cs: self.loadStaticClauses(cs)) def append_static_kb(self, theory): return self.appendStaticKb(theory) def reset_static_kb(self): return self.resetStaticKb() def load_dynamic_kb(self, theory): return self.loadDynamicKb(theory) def load_dynamic_clauses(self, *clauses): return iterable_or_varargs(clauses, lambda cs: self.loadDynamicClauses(cs)) def append_dynamic_kb(self, theory): return self.appendDynamicKb(theory) def reset_dynamic_kb(self): return self.resetDynamicKb() def assert_a(self, clause): return self.assertA(clause) def assert_z(self, clause): return self.assertZ(clause) def retract_all(self, clause): return self.retractAll(clause) def set_flag(self, *args): return self.setFlag(*args) @property def standard_output(self): return self.getStandardOutput() @property def standard_input(self): return self.getStandardInput() @property def standard_error(self): return self.getStandardError() @property def warnings(self): return self.getWarnings() @standard_input.setter def standard_input(self, channel): return self.setStandardInput(channel) @standard_output.setter def standard_output(self, channel): return self.setStandardOutput(channel) @standard_error.setter def standard_error(self, channel): return self.setStandardError(channel) @warnings.setter def warnings(self, channel): return self.setWarnings(channel) @jpype.JImplementationFor("it.unibo.tuprolog.solve.Solution") class _KtSolution: def __jclass_init__(self): pass @property def is_yes(self): return self.isYes() @property def is_no(self): return self.isNo() @property def is_halt(self): return self.isHalt() @property def substitution(self): return self.getSubstitution() @property def exception(self): return self.getExecption() @property def solved_query(self): return self.getSolvedQuery() def clean_up(self): return self.cleanUp() def value_of(self, variable): return self.valueOf(variable) logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.solve.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/_ktadapt.py
_ktadapt.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports from ._ktadapt import * # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve as _solve from tuprolog.core import Indicator, Struct, Term, Substitution, EMPTY_UNIFIER, TermFormatter from tuprolog.solve.exception import ResolutionException from tuprolog.jvmutils import jlist, jmap, JavaSystem from functools import singledispatch from typing import Iterable, Mapping, Any ExecutionContext = _solve.ExecutionContext ExecutionContextAware = _solve.ExecutionContextAware MutableSolver = _solve.MutableSolver Signature = _solve.Signature Solution = _solve.Solution SolutionFormatter = _solve.SolutionFormatter SolveOptions = _solve.SolveOptions Solver = _solve.Solver SolverFactory = _solve.SolverFactory Time = _solve.Time @singledispatch def signature(name: str, arity: int, vararg: bool = False) -> Signature: return Signature(name, arity, vararg) @signature.register def _signature_from_indicator(indicator: Indicator) -> Signature: return Signature.fromIndicator(indicator) @signature.register def _signature_from_term(term: Term) -> Signature: return Signature.fromSignatureTerm(term) @singledispatch def yes_solution( signature: Signature, arguments: Iterable[Term], substitution: Substitution.Unifier = EMPTY_UNIFIER ) -> Solution.Yes: return Solution.yes(signature, jlist(arguments), substitution) @yes_solution.register def _yes_solution_from_query(query: Struct, substitution: Substitution.Unifier = EMPTY_UNIFIER) -> Solution.Yes: return Solution.yes(query, substitution) @singledispatch def no_solution(signature: Signature, arguments: Iterable[Term]) -> Solution.No: return Solution.no(signature, jlist(arguments)) @no_solution.register def _no_solution_from_query(query: Struct) -> Solution.No: return Solution.no(query) @singledispatch def halt_solution(signature: Signature, arguments: Iterable[Term], exception: ResolutionException) -> Solution.Halt: return Solution.halt(signature, jlist(arguments), exception) @halt_solution.register def _halt_solution_from_query(query: Struct, exception: ResolutionException) -> Solution.No: return Solution.halt(query, exception) def current_time_instant() -> int: return JavaSystem.currentTimeMillis() def solution_formatter(term_formatter: TermFormatter = TermFormatter.prettyExpressions()) -> SolutionFormatter: return SolutionFormatter.of(term_formatter) MAX_TIMEOUT: int = SolveOptions.MAX_TIMEOUT ALL_SOLUTIONS: int = SolveOptions.ALL_SOLUTIONS def solve_options( lazy: bool = True, timeout: int = MAX_TIMEOUT, limit: int = ALL_SOLUTIONS, custom: Mapping[str, Any] = dict(), **kwargs: Any ) -> SolveOptions: opts = dict(kwargs) for key in custom: opts[key] = custom[key] temp = SolveOptions.of(lazy, timeout, limit) if len(opts) > 0: return temp.setOptions(jmap(opts)) return temp logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/__init__.py
__init__.py
from tuprolog import logger from tuprolog.solve.flags import DEFAULT_FLAG_STORE, FlagStore from tuprolog.solve.library import libraries, Libraries from tuprolog.solve.channel import InputChannel, OutputChannel, std_out, std_in, std_err, warn from tuprolog.theory import theory, mutable_theory, Theory from tuprolog.solve import Solver, SolverFactory _CLASSIC_SOLVER_FACTORY = Solver.getClassic() def classic_solver( libraries: Libraries = libraries(), flags: FlagStore = DEFAULT_FLAG_STORE, static_kb: Theory = theory(), dynamic_kb: Theory = mutable_theory(), std_in: InputChannel = std_in(), std_out: OutputChannel = std_out(), std_err: OutputChannel = std_err(), warning: OutputChannel = warn(), mutable: bool = True ) -> Solver: if mutable: return _CLASSIC_SOLVER_FACTORY.mutableSolverWithDefaultBuiltins( libraries, flags, static_kb, dynamic_kb, std_in, std_out, std_err, warning ) else: return _CLASSIC_SOLVER_FACTORY.solverWithDefaultBuiltins( libraries, flags, static_kb, dynamic_kb, std_in, std_out, std_err, warning ) def classic_solver_factory() -> SolverFactory: return _CLASSIC_SOLVER_FACTORY logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.classic.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/classic/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.stdlib as _stdlib CommonBuiltins = _stdlib.CommonBuiltins CommonFunctions = _stdlib.CommonFunctions CommonPrimitives = _stdlib.CommonPrimitives CommonRules = _stdlib.CommonRules logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.stdlib.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/stdlib/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.stdlib.primitive as _primitive Abolish = _primitive.Abolish.INSTANCE Arg = _primitive.Arg.INSTANCE ArithmeticEqual = _primitive.ArithmeticEqual.INSTANCE ArithmeticGreaterThan = _primitive.ArithmeticGreaterThan.INSTANCE ArithmeticGreaterThanOrEqualTo = _primitive.ArithmeticGreaterThanOrEqualTo.INSTANCE ArithmeticLowerThan = _primitive.ArithmeticLowerThan.INSTANCE ArithmeticLowerThanOrEqualTo = _primitive.ArithmeticLowerThanOrEqualTo.INSTANCE ArithmeticNotEqual = _primitive.ArithmeticNotEqual.INSTANCE Assert = _primitive.Assert.INSTANCE AssertA = _primitive.AssertA.INSTANCE AssertZ = _primitive.AssertZ.INSTANCE Atom = _primitive.Atom.INSTANCE AtomChars = _primitive.AtomChars.INSTANCE AtomCodes = _primitive.AtomCodes.INSTANCE AtomConcat = _primitive.AtomConcat.INSTANCE AtomLength = _primitive.AtomLength.INSTANCE Atomic = _primitive.Atomic.INSTANCE BagOf = _primitive.BagOf.INSTANCE Between = _primitive.Between.INSTANCE Callable = _primitive.Callable.INSTANCE CharCode = _primitive.CharCode.INSTANCE Clause = _primitive.Clause.INSTANCE Compound = _primitive.Compound.INSTANCE CopyTerm = _primitive.CopyTerm.INSTANCE CurrentFlag = _primitive.CurrentFlag.INSTANCE CurrentOp = _primitive.CurrentOp.INSTANCE EnsureExecutable = _primitive.EnsureExecutable.INSTANCE FindAll = _primitive.FindAll.INSTANCE Float = _primitive.Float.INSTANCE Functor = _primitive.Functor.INSTANCE GetDurable = _primitive.GetDurable.INSTANCE GetEphemeral = _primitive.GetEphemeral.INSTANCE GetPersistent = _primitive.GetPersistent.INSTANCE Ground = _primitive.Ground.INSTANCE Halt = _primitive.Halt.INSTANCE Halt1 = _primitive.Halt1.INSTANCE Integer = _primitive.Integer.INSTANCE Is = _primitive.Is.INSTANCE Natural = _primitive.Natural.INSTANCE NewLine = _primitive.NewLine.INSTANCE NonVar = _primitive.NonVar.INSTANCE NotUnifiableWith = _primitive.NotUnifiableWith.INSTANCE Number = _primitive.Number.INSTANCE NumberChars = _primitive.NumberChars.INSTANCE NumberCodes = _primitive.NumberCodes.INSTANCE Op = _primitive.Op.INSTANCE Repeat = _primitive.Repeat.INSTANCE Retract = _primitive.Retract.INSTANCE RetractAll = _primitive.RetractAll.INSTANCE Reverse = _primitive.Reverse.INSTANCE SetDurable = _primitive.SetDurable.INSTANCE SetEphemeral = _primitive.SetEphemeral.INSTANCE SetFlag = _primitive.SetFlag.INSTANCE SetOf = _primitive.SetOf.INSTANCE SetPersistent = _primitive.SetPersistent.INSTANCE Sleep = _primitive.Sleep.INSTANCE SubAtom = _primitive.SubAtom.INSTANCE TermGreaterThan = _primitive.TermGreaterThan.INSTANCE TermGreaterThanOrEqualTo = _primitive.TermGreaterThanOrEqualTo.INSTANCE TermIdentical = _primitive.TermIdentical.INSTANCE TermLowerThan = _primitive.TermLowerThan.INSTANCE TermLowerThanOrEqualTo = _primitive.TermLowerThanOrEqualTo.INSTANCE TermNotIdentical = _primitive.TermNotIdentical.INSTANCE TermNotSame = _primitive.TermNotSame.INSTANCE TermSame = _primitive.TermSame.INSTANCE UnifiesWith = _primitive.UnifiesWith.INSTANCE Univ = _primitive.Univ.INSTANCE Var = _primitive.Var.INSTANCE Write = _primitive.Write.INSTANCE logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.stdlib.primitive.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/stdlib/primitive/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.stdlib.rule as _rule from tuprolog.solve import signature KtAppend = _rule.Append Arrow = _rule.Arrow CurrentPrologFlag = _rule.CurrentPrologFlag KtMember = _rule.Member Not = _rule.Not Once = _rule.Once KtSemicolon = _rule.Semicolon SetPrologFlag = _rule.SetPrologFlag class Append: FUNCTOR = KtAppend.FUNCTOR ARITY = KtAppend.ARITY SIGNATURE = signature(FUNCTOR, ARITY) Base = KtAppend.Base.INSTANCE Recursive = KtAppend.Recursive.INSTANCE Arrow = Arrow.INSTANCE CurrentPrologFlag = CurrentPrologFlag.INSTANCE class Member: FUNCTOR = KtMember.FUNCTOR ARITY = KtMember.ARITY SIGNATURE = signature(FUNCTOR, ARITY) Base = KtMember.Base.INSTANCE Recursive = KtMember.Recursive.INSTANCE Not = Not.INSTANCE Once = Once.INSTANCE class Semicolon: FUNCTOR = KtSemicolon.FUNCTOR ARITY = KtSemicolon.ARITY SIGNATURE = signature(FUNCTOR, ARITY) class If: Then = KtSemicolon.If.Then.INSTANCE Else = KtSemicolon.If.Else.INSTANCE class Or: Left = KtSemicolon.Or.Left.INSTANCE Right = KtSemicolon.Or.Right.INSTANCE logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.stdlib.rule.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/stdlib/rule/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.stdlib.function as _function AbsoluteValue = _function.AbsoluteValue.INSTANCE Addition = _function.Addition.INSTANCE ArcTangent = _function.ArcTangent.INSTANCE BitwiseAnd = _function.BitwiseAnd.INSTANCE BitwiseComplement = _function.BitwiseComplement.INSTANCE BitwiseLeftShift = _function.BitwiseLeftShift.INSTANCE BitwiseOr = _function.BitwiseOr.INSTANCE BitwiseRightShift = _function.BitwiseRightShift.INSTANCE Ceiling = _function.Ceiling.INSTANCE Cosine = _function.Cosine.INSTANCE Exponential = _function.Exponential.INSTANCE Exponentiation = _function.Exponentiation.INSTANCE FloatFractionalPart = _function.FloatFractionalPart.INSTANCE FloatIntegerPart = _function.FloatIntegerPart.INSTANCE FloatingPointDivision = _function.FloatingPointDivision.INSTANCE Floor = _function.Floor.INSTANCE IntegerDivision = _function.IntegerDivision.INSTANCE Modulo = _function.Modulo.INSTANCE Multiplication = _function.Multiplication.INSTANCE NaturalLogarithm = _function.NaturalLogarithm.INSTANCE Remainder = _function.Remainder.INSTANCE Round = _function.Round.INSTANCE Sign = _function.Sign.INSTANCE SignReversal = _function.SignReversal.INSTANCE Sine = _function.Sine.INSTANCE SquareRoot = _function.SquareRoot.INSTANCE Subtraction = _function.Subtraction.INSTANCE ToFloat = _function.ToFloat.INSTANCE Truncate = _function.Truncate.INSTANCE logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.stdlib.function.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/stdlib/function/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.channel as _channel # noinspection PyUnresolvedReferences import kotlin.jvm.functions as _kfunctions from tuprolog.jvmutils import jmap, kfunction from typing import Callable, Mapping from functools import singledispatch Channel = _channel.Channel ChannelStore = _channel.ChannelStore InputChannel = _channel.InputChannel InputStore = _channel.InputStore OutputChannel = _channel.OutputChannel OutputStore = _channel.OutputStore Listener = _kfunctions.Function1 def std_in() -> InputChannel: return InputChannel.stdIn() @singledispatch def input_channel(generator: Callable, availability_checker: Callable = None) -> InputChannel: if availability_checker is None: return InputChannel.of(kfunction(0)(generator)) else: return InputChannel.of(kfunction(0)(generator), kfunction(0)(availability_checker)) @input_channel.register def input_channel_from_string(string: str) -> InputChannel: return InputChannel.of(string) def input_store(stdin: InputChannel = None, channels: Mapping[str, InputChannel] = None) -> InputStore: if stdin is None and channels is None: return InputStore.fromStandard() elif channels is None: return InputStore.fromStandard(stdin) else: cs = {InputStore.STDIN: stdin or std_in()} for k, v in channels: cs[k] = v return InputStore.of(jmap(cs)) def std_out() -> OutputChannel: return OutputChannel.stdOut() def std_err() -> OutputChannel: return OutputChannel.stdErr() def warn() -> OutputChannel: return OutputChannel.warn() def output_channel(consumer: Callable) -> OutputChannel: return OutputChannel.of(kfunction(1)(consumer)) def output_store( stdout: OutputChannel = None, stderr: OutputChannel = None, warnings: OutputChannel = None, channels: Mapping[str, OutputChannel] = None ) -> OutputStore: if all((channel is None for channel in (stdout, stderr, warnings))): return OutputStore.fromStandard() elif channels is None: return OutputStore.fromStandard( stdout or std_out(), stderr or std_err(), warnings or warn() ) else: cs = { OutputStore.STDOUT: stdout or std_out(), OutputStore.STDERR: stderr or std_err() } for k, v in channels: cs[k] = v return OutputStore.of(jmap(cs), warnings or warn()) def listener(consumer: Callable) -> Listener: return kfunction(1)(consumer) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.channel.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/channel/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.flags as _flags from tuprolog.core import Term from tuprolog.jvmutils import kpair, jmap, jarray, Pair from typing import Iterable, Union, Mapping DoubleQuotes = _flags.DoubleQuotes FlagStore = _flags.FlagStore LastCallOptimization = _flags.LastCallOptimization MaxArity = _flags.MaxArity NotableFlag = _flags.NotableFlag Unknown = _flags.Unknown Flag = Pair EMPTY_FLAG_STORE: FlagStore = FlagStore.EMPTY DEFAULT_FLAG_STORE: FlagStore = FlagStore.DEFAULT DoubleQuotes: NotableFlag = DoubleQuotes.INSTANCE LastCallOptimization: NotableFlag = LastCallOptimization.INSTANCE MaxArity: NotableFlag = MaxArity.INSTANCE Unknown: NotableFlag = Unknown.INSTANCE def flag(first: Union[str, NotableFlag, Iterable], value: Term = None) -> Flag: if isinstance(first, NotableFlag): if value is None: return first.toPair() else: return first.to(value) elif isinstance(first, str): if value is None: raise ValueError("Argument value is None") return Flag(first, value) elif isinstance(first, Iterable) and value is None: return kpair(first) else: raise ValueError("Argument first is not iterable nor str") def flag_store(*flags: Union[NotableFlag, Flag, Iterable, FlagStore], **kwargs: Mapping[str, Term]): normal_flags = [] notable_flags = [] other_stores = [] for f in flags: if isinstance(f, NotableFlag): notable_flags.append(f) elif isinstance(f, Flag): normal_flags.append(f) elif isinstance(f, FlagStore): other_stores.append(f) else: normal_flags.append(flag(f)) store1 = FlagStore.of(jarray(NotableFlag)@notable_flags) store2 = FlagStore.of(jarray(Flag)@normal_flags) store3 = FlagStore.of(jmap(kwargs)) store = store1.plus(store2).plus(store3) for s in other_stores: store = store.plus(s) return store logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.flags.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/flags/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.problog as _problog Operators = _problog.Operators ANNOTATION_OPERATOR = Operators.ANNOTATION_OPERATOR PROBLOG_SPECIFIC_OPERATORS = Operators.PROBLOG_SPECIFIC_OPERATORS PROBLOG_OPERATORS = Operators.PROBLOG_OPERATORS logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.problog.operators")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/problog/operators.py
operators.py
from tuprolog import logger from tuprolog.solve.flags import DEFAULT_FLAG_STORE, FlagStore from tuprolog.solve.library import libraries, Libraries from tuprolog.solve.channel import InputChannel, OutputChannel, std_out, std_in, std_err, warn from tuprolog.theory import theory, mutable_theory, Theory from tuprolog.solve import Solver, SolverFactory _PROBLOG_SOLVER_FACTORY = Solver.getProblog() def problog_solver( libraries: Libraries = libraries(), flags: FlagStore = DEFAULT_FLAG_STORE, static_kb: Theory = theory(), dynamic_kb: Theory = mutable_theory(), std_in: InputChannel = std_in(), std_out: OutputChannel = std_out(), std_err: OutputChannel = std_err(), warning: OutputChannel = warn(), mutable: bool = True ) -> Solver: if mutable: return _PROBLOG_SOLVER_FACTORY.mutableSolverWithDefaultBuiltins( libraries, flags, static_kb, dynamic_kb, std_in, std_out, std_err, warning ) else: return _PROBLOG_SOLVER_FACTORY.solverWithDefaultBuiltins( libraries, flags, static_kb, dynamic_kb, std_in, std_out, std_err, warning ) def problog_solver_factory() -> SolverFactory: return _PROBLOG_SOLVER_FACTORY logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.problog.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/problog/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve as _solve from tuprolog.utils import Taggable from tuprolog.solve import SolveOptions, solve_options as _solve_options, MAX_TIMEOUT, ALL_SOLUTIONS from typing import TypeVar, Mapping, Any ProbExtensions = _solve.ProbExtensions def probability(taggable: Taggable) -> float: return ProbExtensions.getProbability(taggable) T = TypeVar("T", bound=Taggable, covariant=True) def set_probability(taggable: T) -> T: return ProbExtensions.setProbability(taggable) def is_probabilistic(solve_opts: SolveOptions) -> bool: return ProbExtensions.isProbabilistic(solve_opts) def set_probabilistic(solve_opts: SolveOptions, value: bool) -> SolveOptions: return ProbExtensions.setProbabilistic(solve_opts, value) def probabilistic(solve_opts: SolveOptions) -> SolveOptions: return ProbExtensions.probabilistic(solve_opts) def solve_options( lazy: bool = True, timeout: int = MAX_TIMEOUT, limit: int = ALL_SOLUTIONS, probabilistic: bool = False, custom: Mapping[str, Any] = dict(), **kwargs: Any ) -> SolveOptions: non_probabilistic = _solve_options(lazy, timeout, limit, custom, **kwargs) if probabilistic: return set_probabilistic(non_probabilistic, True) return non_probabilistic logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.plp.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/plp/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports from tuprolog.core import Term, Clause, Integer from tuprolog.solve import ExecutionContext, Signature, Solution, current_time_instant, MAX_TIMEOUT # from tuprolog.solve.sideffcts import SideEffect from tuprolog.pyutils import iterable_or_varargs from tuprolog.jvmutils import jlist from typing import List, Iterable, Callable # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.primitive as _primitive Primitive = _primitive.Primitive Solve = _primitive.Solve PrimitiveWrapper = _primitive.PrimitiveWrapper SolveRequest = Solve.Request SolveResponse = Solve.Request @jpype.JImplements(Primitive) class AbstractPrimitive(object): @jpype.JOverride def solve(self, request: SolveRequest) -> Iterable[SolveResponse]: raise NotImplementedError() def primitive(callable: Callable[[SolveResponse], Iterable[SolveResponse]]) -> Primitive: class CallableToPrimitiveAdapter(AbstractPrimitive): def solve(self, request: SolveRequest) -> Iterable[SolveResponse]: return callable(request) return CallableToPrimitiveAdapter() def solve_request( signature: Signature, arguments: List[Term], context: ExecutionContext, issuing_instant: int = current_time_instant(), max_duration: int = MAX_TIMEOUT ) -> SolveRequest: return SolveRequest(signature, arguments, context, issuing_instant, max_duration) def solve_response(solution: Solution, *side_effects) -> SolveResponse: return iterable_or_varargs(side_effects, lambda ses: SolveResponse(solution, None, jlist(ses))) def check_term_is_recursively_callable(request: SolveRequest, term: Term): return PrimitiveWrapper.checkTermIsRecursivelyCallable(request, term) def ensuring_all_arguments_are_instantiated(request: SolveRequest) -> SolveRequest: return PrimitiveWrapper.ensuringAllArgumentsAreInstantiated(request) def ensuring_procedure_has_permission(request: SolveRequest, signature: Signature, operation) -> SolveRequest: return PrimitiveWrapper.ensuringProcedureHasPermission(request, signature, operation) def ensuring_clause_procedure_has_permission(request: SolveRequest, clause: Clause, operation) -> SolveRequest: return PrimitiveWrapper.ensuringClauseProcedureHasPermission(request, clause, operation) def ensuring_argument_is_well_formed_indicator(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsWellFormedIndicator(request, index) def not_implemented(request: SolveRequest, message: str) -> SolveResponse: return PrimitiveWrapper.notImplemented(request, message) def not_supported(request: SolveRequest, message: str) -> SolveResponse: return PrimitiveWrapper.notSupported(request, message) def ensuring_argument_is_well_formed_clause(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsWellFormedClause(request, index) def ensuring_argument_is_instantiated(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsInstantiated(request, index) def ensuring_argument_is_numeric(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsNumeric(request, index) def ensuring_argument_is_struct(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsStruct(request, index) def ensuring_argument_is_callable(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsCallable(request, index) def ensuring_argument_is_variable(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsVariable(request, index) def ensuring_argument_is_compound(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsCompound(request, index) def ensuring_argument_is_atom(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsCompound(request, index) def ensuring_argument_is_constant(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsConstant(request, index) def ensuring_argument_is_ground(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsGround(request, index) def ensuring_argument_is_char(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsChar(request, index) def ensuring_argument_is_specifier(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsSpecifier(request, index) def ensuring_argument_is_integer(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsInteger(request, index) def ensuring_argument_is_list(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsList(request, index) def ensuring_argument_is_arity(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsArity(request, index) def ensuring_argument_is_non_negative_integer(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsNonNegativeInteger(request, index) def is_character_code(integer: Integer) -> bool: return PrimitiveWrapper.isCharacterCode(integer) def ensuring_term_is_char_code(request: SolveRequest, term: Term) -> SolveRequest: return PrimitiveWrapper.ensuringTermIsCharCode(request, term) def ensuring_term_is_well_formed_list(request: SolveRequest, term: Term) -> SolveRequest: return PrimitiveWrapper.ensuringTermIsWellFormedList(request, term) def ensuring_argument_is_char_code(request: SolveRequest, index: int) -> SolveRequest: return PrimitiveWrapper.ensuringArgumentIsCharCode(request, index) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.primitive.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/primitive/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception as _exceptions HaltException = _exceptions.HaltException LogicError = _exceptions.LogicError ResolutionException = _exceptions.ResolutionException TimeOutException = _exceptions.TimeOutException Warning = _exceptions.Warning logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/__init__.py
__init__.py
from .domain import * from .evaluation import * from .existence import * from .instantiation import * from .message import * from .permission import * from .representation import * from .syntax import * from .system import * from .type import *
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/__init__.py
__init__.py
from typing import Iterable, Union from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors from tuprolog.core import Term from tuprolog.solve import ExecutionContext, Signature DomainError = errors.DomainError Domain = DomainError.Expected DOMAIN_wATOM_PROPERTY = Domain.ATOM_PROPERTY DOMAIN_BUFFERING_MODE = Domain.BUFFERING_MODE DOMAIN_CHARACTER_CODE_LIST = Domain.CHARACTER_CODE_LIST DOMAIN_CLOSE_OPTION = Domain.CLOSE_OPTION DOMAIN_DATE_TIME = Domain.DATE_TIME DOMAIN_EOF_ACTION = Domain.EOF_ACTION DOMAIN_FLAG_VALUE = Domain.FLAG_VALUE DOMAIN_FORMAT_CONTROL_SEQUENCE = Domain.FORMAT_CONTROL_SEQUENCE DOMAIN_IO_MODE = Domain.IO_MODE DOMAIN_WELL_FORMED_LIST = Domain.WELL_FORMED_LIST DOMAIN_NON_EMPTY_LIST = Domain.NON_EMPTY_LIST DOMAIN_NOT_LESS_THAN_ZERO = Domain.NOT_LESS_THAN_ZERO DOMAIN_OPERATOR_PRIORITY = Domain.OPERATOR_PRIORITY DOMAIN_OPERATOR_SPECIFIER = Domain.OPERATOR_SPECIFIER DOMAIN_ORDER = Domain.ORDER DOMAIN_OS_FILE_PERMISSION = Domain.OS_FILE_PERMISSION DOMAIN_OS_FILE_PROPERTY = Domain.OS_FILE_PROPERTY DOMAIN_OS_PATH = Domain.OS_PATH DOMAIN_PREDICATE_PROPERTY = Domain.PREDICATE_PROPERTY DOMAIN_FLAG = Domain.FLAG DOMAIN_READ_OPTION = Domain.READ_OPTION DOMAIN_SELECTABLE_ITEM = Domain.SELECTABLE_ITEM DOMAIN_SOCKET_ADDRESS = Domain.SOCKET_ADDRESS DOMAIN_SOCKET_DOMAIN = Domain.SOCKET_DOMAIN DOMAIN_SOURCE_SINK = Domain.SOURCE_SINK DOMAIN_STREAM = Domain.STREAM DOMAIN_STREAM_OPTION = Domain.STREAM_OPTION DOMAIN_STREAM_OR_ALIAS = Domain.STREAM_OR_ALIAS DOMAIN_STREAM_POSITION = Domain.STREAM_POSITION DOMAIN_STREAM_PROPERTY = Domain.STREAM_PROPERTY DOMAIN_STREAM_SEEK_METHOD = Domain.STREAM_SEEK_METHOD DOMAIN_STREAM_TYPE = Domain.STREAM_TYPE DOMAIN_TERM_STREAM_OR_ALIAS = Domain.TERM_STREAM_OR_ALIAS DOMAIN_VAR_BINDING_OPTION = Domain.VAR_BINDING_OPTION DOMAIN_WRITE_OPTION = Domain.WRITE_OPTION DOMAIN_CLAUSE = Domain.CLAUSE DOMAIN_RULE = Domain.RULE DOMAIN_FACT = Domain.FACT DIRECTIVE = Domain.DIRECTIVE def domain_error_for_flag_values( context: ExecutionContext, procedure: Signature, flag_values: Iterable[Term], actual: Term, index: int = None ) -> DomainError: return DomainError.forFlagValues(context, procedure, flag_values, actual, index) def domain_error_for_argument( context: ExecutionContext, procedure: Signature, expected: Domain, actual: Term, index: int = None ) -> DomainError: return DomainError.forArgument(context, procedure, expected, actual, index) def domain_error_for_term( context: ExecutionContext, expected: Domain, actual_value: Term, ) -> DomainError: return DomainError.forTerm(context, expected, actual_value) def domain_error_for_goal( context: ExecutionContext, procedure: Signature, expected: Domain, actual: Term, ) -> DomainError: return DomainError.forGoal(context, procedure, expected, actual) def domain(name: Union[str, Term]) -> Domain: if isinstance(name, str): return Domain.of(name) else: return Domain.fromTerm(name) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.DomainError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/domain/__init__.py
__init__.py
from typing import Union from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors from tuprolog.core import Term, Atom from tuprolog.solve import ExecutionContext, Signature ExistenceError = errors.ExistenceError ObjectType = ExistenceError.ObjectType OBJECT_PROCEDURE = ObjectType.PROCEDURE OBJECT_SOURCE_SINK = ObjectType.SOURCE_SINK OBJECT_RESOURCE = ObjectType.RESOURCE OBJECT_STREAM = ObjectType.STREAM OBJECT_OOP_ALIAS = ObjectType.OOP_ALIAS OBJECT_OOP_METHOD = ObjectType.OOP_METHOD OBJECT_OOP_CONSTRUCTOR = ObjectType.OOP_CONSTRUCTOR OBJECT_OOP_PROPERTY = ObjectType.OOP_PROPERTY def existence_error( context: ExecutionContext, type: ObjectType, culprit: Term, message: str ) -> ExistenceError: return ExistenceError.of(context, type, culprit, message) def existence_error_for_source_sink( context: ExecutionContext, alias: Union[Atom, str] ) -> ExistenceError: return ExistenceError.forSourceSink(context, alias) def existence_error_for_procedure( context: ExecutionContext, procedure: Signature ) -> ExistenceError: return ExistenceError.forProcedure(context, procedure) def existence_error_for_stream( context: ExecutionContext, stream: Term ) -> ExistenceError: return ExistenceError.forStream(context, stream) def existence_error_for_resource( context: ExecutionContext, name: str ) -> ExistenceError: return ExistenceError.forResource(context, name) def object_type(name: Union[str, Term]) -> ObjectType: if isinstance(name, str): return ObjectType.of(name) else: return ObjectType.fromTerm(name) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.ExistenceError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/existence/__init__.py
__init__.py
# noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.solve import ExecutionContext # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors from tuprolog.solve.exception import LogicError SystemError = errors.SyntaxError def syntax_error(context: ExecutionContext, message: str, exception) -> SystemError: if isinstance(exception, LogicError): return SystemError.forUncaughtError(context, message, exception) return SystemError.forUncaughtException(context, message, exception) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.SystemError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/system/__init__.py
__init__.py
from typing import Union # noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.core import Term from tuprolog.solve import ExecutionContext, Signature # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors PermissionError = errors.PermissionError Operation = PermissionError.Operation Permission = PermissionError.Permission OPERATION_ACCESS = Operation.ACCESS OPERATION_ADD_ALIAS = Operation.ADD_ALIAS OPERATION_CLOSE = Operation.CLOSE OPERATION_CREATE = Operation.CREATE OPERATION_INPUT = Operation.INPUT OPERATION_INVOKE = Operation.INVOKE OPERATION_MODIFY = Operation.MODIFY OPERATION_OPEN = Operation.OPEN OPERATION_OUTPUT = Operation.OUTPUT OPERATION_REPOSITION = Operation.REPOSITION PERMISSION_BINARY_STREAM = Permission.BINARY_STREAM PERMISSION_FLAG = Permission.FLAG PERMISSION_OPERATOR = Permission.OPERATOR PERMISSION_PAST_END_OF_STREAM = Permission.PAST_END_OF_STREAM PERMISSION_PRIVATE_PROCEDURE = Permission.PRIVATE_PROCEDURE PERMISSION_SOURCE_SINK = Permission.SOURCE_SINK PERMISSION_STATIC_PROCEDURE = Permission.STATIC_PROCEDURE PERMISSION_OOP_METHOD = Permission.OOP_METHOD PERMISSION_STREAM = Permission.STREAM PERMISSION_TEXT_STREAM = Permission.TEXT_STREAM def permission_error( context: ExecutionContext, procedure: Signature, operation: Operation, permission: Permission, culprit: Term ) -> PermissionError: return PermissionError.of(context, procedure, operation, permission, culprit) def operation(name: Union[str, Term]) -> Operation: if isinstance(name, str): return Operation.of(name) else: return Operation.fromTerm(name) def permission(name: Union[str, Term]) -> Permission: if isinstance(name, str): return Permission.of(name) else: return Permission.fromTerm(name) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.PermissionError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/permission/__init__.py
__init__.py
from typing import Union # noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.core import Term from tuprolog.solve import ExecutionContext, Signature # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors RepresentationError = errors.RepresentationError Limit = RepresentationError.Limit LIMIT_CHARACTER = Limit.CHARACTER LIMIT_CHARACTER_CODE = Limit.CHARACTER_CODE LIMIT_IN_CHARACTER_CODE = Limit.IN_CHARACTER_CODE LIMIT_MAX_ARITY = Limit.MAX_ARITY LIMIT_MAX_INTEGER = Limit.MAX_INTEGER LIMIT_MIN_INTEGER = Limit.MIN_INTEGER LIMIT_OOP_OBJECT = Limit.OOP_OBJECT LIMIT_TOO_MANY_VARIABLES = Limit.TOO_MANY_VARIABLES def representation_error( context: ExecutionContext, procedure: Signature, limit: Limit, cause=None ) -> RepresentationError: return RepresentationError.of(context, procedure, limit, cause) def limit(name: Union[str, Term]) -> Limit: if isinstance(name, str): return Limit.of(name) else: return Limit.fromTerm(name) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.RepresentationError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/representation/__init__.py
__init__.py
# noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.solve import ExecutionContext # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors SyntaxError = errors.SyntaxError def syntax_error( context: ExecutionContext, message: str ) -> SyntaxError: return SyntaxError.of(context, message) def syntax_error_while_parsing_term( context: ExecutionContext, input: str, row: int, column: int, message: str ) -> SyntaxError: return SyntaxError.whileParsingTerm(context, input, row, column, message) def syntax_error_while_parsing_clauses( context: ExecutionContext, input: str, index: int, row: int, column: int, message: str ) -> SyntaxError: return SyntaxError.whileParsingClauses(context, input, index, row, column, message) def error_detector(text: str, line: int, column: int, message: str = None) -> str: return SyntaxError.errorDetector(text, line, column, message) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.SyntaxError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/syntax/__init__.py
__init__.py
from typing import Union from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors from tuprolog.core import Term, atom from tuprolog.solve import ExecutionContext EvaluationError = errors.EvaluationError ErrorType = EvaluationError.Type ERROR_INT_OVERFLOW = ErrorType.INT_OVERFLOW ERROR_FLOAT_OVERFLOW = ErrorType.FLOAT_OVERFLOW ERROR_UNDERFLOW = ErrorType.UNDERFLOW ERROR_ZERO_DIVISOR = ErrorType.ZERO_DIVISOR ERROR_UNDEFINED = ErrorType.UNDEFINED def evaluation_error( context: ExecutionContext, type: ErrorType, message: str ) -> EvaluationError: return EvaluationError(message, None, context, type, atom(message)) def error_type(name: Union[str, Term]) -> ErrorType: if isinstance(name, str): return ErrorType.valueOf(name) else: return ErrorType.fromTerm(name) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.EvaluationError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/evaluation/__init__.py
__init__.py
from typing import Union # noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.core import Term from tuprolog.solve import ExecutionContext, Signature # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors TypeError = errors.TypeError Type = TypeError.Expected TYPE_ATOM = Type.ATOM TYPE_ATOMIC = Type.ATOMIC TYPE_BOOLEAN = Type.BOOLEAN TYPE_BYTE = Type.BYTE TYPE_CALLABLE = Type.CALLABLE TYPE_CHARACTER = Type.CHARACTER TYPE_COMPOUND = Type.COMPOUND TYPE_DEALIASING_EXPRESSION = Type.DEALIASING_EXPRESSION TYPE_EVALUABLE = Type.EVALUABLE TYPE_FLOAT = Type.FLOAT TYPE_INTEGER = Type.INTEGER TYPE_IN_CHARACTER = Type.IN_CHARACTER TYPE_LIST = Type.LIST TYPE_NUMBER = Type.NUMBER TYPE_OBJECT_REFERENCE = Type.OBJECT_REFERENCE TYPE_PAIR = Type.PAIR TYPE_PREDICATE_INDICATOR = Type.PREDICATE_INDICATOR TYPE_REFERENCE = Type.REFERENCE TYPE_TYPE_REFERENCE = Type.TYPE_REFERENCE TYPE_URL = Type.URL TYPE_VARIABLE = Type.VARIABLE def type_error_for_flag_values( context: ExecutionContext, procedure: Signature, expected: Type, actual: Term, message: str ) -> TypeError: return TypeError.of(context, procedure, expected, actual, message) def type_error_for_argument_list( context: ExecutionContext, procedure: Signature, expected: Type, actual: Term, index: int = None ) -> TypeError: return TypeError.forArgumentList(context, procedure, expected, actual, index) def type_error_for_argument( context: ExecutionContext, procedure: Signature, expected: Type, actual: Term, index: int = None ) -> TypeError: return TypeError.forArgument(context, procedure, expected, actual, index) def type_error_for_term( context: ExecutionContext, expected: Type, actual_value: Term, ) -> TypeError: return TypeError.forTerm(context, expected, actual_value) def type_error_for_goal( context: ExecutionContext, procedure: Signature, expected: Type, actual: Term, ) -> TypeError: return TypeError.forGoal(context, procedure, expected, actual) def type(name: Union[str, Term]) -> Type: if isinstance(name, str): return TypeError.valueOf(name) else: return TypeError.fromTerm(name) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.TypeError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/type/__init__.py
__init__.py
# noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.core import Var from tuprolog.solve import ExecutionContext, Signature # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors InstantiationError = errors.InstantiationError def instantiation_error_for_argument( context: ExecutionContext, procedure: Signature, variable: Var, index: int = None ) -> InstantiationError: return InstantiationError.forArgument(context, procedure, variable, index) def instantiation_error_for_goal( context: ExecutionContext, procedure: Signature, variable: Var ) -> InstantiationError: return InstantiationError.forGoal(context, procedure, variable) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.InstantiationError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/instantiation/__init__.py
__init__.py
# noinspection PyUnresolvedReferences import jpype.imports from tuprolog import logger from tuprolog.core import Term from tuprolog.solve import ExecutionContext # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.error as errors MessageError = errors.MessageError def message_error(content: Term, context: ExecutionContext, cause=None) -> MessageError: return MessageError.of(content, context, cause) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.error.MessageError.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/error/message/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.exception.warning as warnings from tuprolog.core import Struct from tuprolog.solve import ExecutionContext, ResolutionException, Signature InitializationIssue = warnings.InitializationIssue MissingPredicate = warnings.MissingPredicate def initialization_issue( goal: Struct, context: ExecutionContext, cause: ResolutionException = None ) -> InitializationIssue: return InitializationIssue(goal, cause, context) def missing_predicate( signature: Signature, context: ExecutionContext, cause=None ) -> MissingPredicate: return MissingPredicate(cause, context, signature) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.exception.warning.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/exception/warning/__init__.py
__init__.py
from tuprolog import logger from tuprolog.solve.flags import DEFAULT_FLAG_STORE, FlagStore from tuprolog.solve.library import libraries, Libraries from tuprolog.solve.channel import InputChannel, OutputChannel, std_out, std_in, std_err, warn from tuprolog.theory import theory, mutable_theory, Theory from tuprolog.solve import Solver, SolverFactory _PROLOG_SOLVER_FACTORY = Solver.getProlog() def prolog_solver( libraries: Libraries = libraries(), flags: FlagStore = DEFAULT_FLAG_STORE, static_kb: Theory = theory(), dynamic_kb: Theory = mutable_theory(), std_in: InputChannel = std_in(), std_out: OutputChannel = std_out(), std_err: OutputChannel = std_err(), warning: OutputChannel = warn(), mutable: bool = True ) -> Solver: if mutable: return _PROLOG_SOLVER_FACTORY.mutableSolverWithDefaultBuiltins( libraries, flags, static_kb, dynamic_kb, std_in, std_out, std_err, warning ) else: return _PROLOG_SOLVER_FACTORY.solverWithDefaultBuiltins( libraries, flags, static_kb, dynamic_kb, std_in, std_out, std_err, warning ) def prolog_solver_factory() -> SolverFactory: return _PROLOG_SOLVER_FACTORY logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.prolog.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/prolog/__init__.py
__init__.py
from functools import reduce from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports from tuprolog.core.operators import OperatorSet, operator_set from tuprolog.theory import Theory, theory from tuprolog.solve import Signature from tuprolog.solve.primitive import Primitive from tuprolog.solve.function import LogicFunction from tuprolog.jvmutils import jiterable from typing import Union, Mapping, Iterable # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.library as _library Library = _library.Library Libraries = _library.Libraries LibraryGroup = _library.LibraryGroup AliasedLibrary = _library.AliasedLibrary def library( alias: str = None, primitives: Mapping[Signature, Primitive] = dict(), theory: Theory = theory(), operators: OperatorSet = operator_set(), functions: Mapping[Signature, LogicFunction] = dict(), ) -> Union[Library, AliasedLibrary]: if alias is None: return Library.unaliased(primitives, theory, operators, functions) else: return Library.aliased(alias, primitives, theory, operators, functions) def aliased(alias: str, library: Library) -> AliasedLibrary: return Library.of(alias, library) def libraries( *libs: Union[Libraries, AliasedLibrary, Iterable[Union[Libraries, AliasedLibrary]]], **kwargs: Library ) -> Libraries: all_libraries = [] aliased_libs = [] queue = list(libs) while len(queue) > 0: current = queue.pop() if isinstance(current, Libraries): all_libraries.append(current) elif isinstance(current, AliasedLibrary): aliased_libs.append(current) else: queue.extend(current) for alias in kwargs: aliased_libs.append(aliased(alias, kwargs[alias])) first = Libraries.of(jiterable(aliased_libs)) return reduce(lambda a, b: a.plus(b), all_libraries, first) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.library.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/library/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.library.exception as _exception AlreadyLoadedLibraryException = _exception.AlreadyLoadedLibraryException LibraryException = _exception.LibraryException NoSuchALibraryException = _exception.NoSuchALibraryException logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.library.exception.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/library/exception/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports from tuprolog.core import Term from tuprolog.solve import ExecutionContext, Signature, current_time_instant, MAX_TIMEOUT from tuprolog.solve.primitive import SolveRequest # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.function as _function from typing import List, Callable LogicFunction = _function.LogicFunction Compute = _function.Compute ArithmeticUtilsKt = _function.ArithmeticUtilsKt ComputeRequest = Compute.Request ComputeResponse = Compute.Request @jpype.JImplements(LogicFunction) class AbstractLogicFunction(object): @jpype.JOverride def compute(self, request: ComputeRequest) -> ComputeResponse: raise NotImplementedError() def logic_function(callable: Callable[[ComputeRequest], ComputeResponse]) -> LogicFunction: class CallableToLogicFunctionAdapter(AbstractLogicFunction): def compute(self, request: ComputeRequest) -> ComputeResponse: return callable(request) return CallableToLogicFunctionAdapter() def compute_request( signature: Signature, arguments: List[Term], context: ExecutionContext, issuing_instant: int = current_time_instant, max_duration: int = MAX_TIMEOUT ) -> ComputeRequest: return ComputeRequest(signature, arguments, context, issuing_instant, max_duration) def compute_response(result: Term) -> ComputeResponse: return ComputeResponse(result) def eval_as_expression(term: Term, request: SolveRequest, index: int = None) -> Term: return ArithmeticUtilsKt.evalAsExpression(term, request, index) def eval_as_arithmetic_expression(term: Term, request: SolveRequest, index: int = None) -> Term: return ArithmeticUtilsKt.evalAsArithmeticExpression(term, request, index) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.function.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/function/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.solve.data as _data from tuprolog.jvmutils import Map from tuprolog.pyutils import dict_or_keyword_args from tuprolog.jvmutils import jmap from typing import Mapping, Any CustomDataStore = _data.CustomDataStore CustomData = Map def custom_data(data: Mapping[str, Any] = {}, **kwargs) -> CustomData: return dict_or_keyword_args(data, kwargs, lambda ds: jmap(ds)) EMPTY_DATA: CustomData = custom_data() def custom_data_store( persistent: CustomData = EMPTY_DATA, durable: CustomData = EMPTY_DATA, ephemeral: CustomData = EMPTY_DATA ) -> CustomDataStore: return CustomDataStore.empty().copy(persistent, durable, ephemeral) EMPTY_DATA_STORE: CustomDataStore = CustomDataStore.empty() logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.data.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/data/__init__.py
__init__.py
from functools import reduce from tuprolog import logger # noinspection PyUnresolvedReferences import jpype # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences from it.unibo.tuprolog.solve.sideffects import SideEffect # noinspection PyUnresolvedReferences from it.unibo.tuprolog.solve.sideffects import SideEffectFactory # noinspection PyUnresolvedReferences from it.unibo.tuprolog.solve.sideffects import SideEffectsBuilder # noinspection PyUnresolvedReferences from tuprolog.core import Clause, Term # noinspection PyUnresolvedReferences from tuprolog.core.operators import Operator, OperatorSet # noinspection PyUnresolvedReferences from tuprolog.solve.library import Library, AliasedLibrary, Libraries, libraries as new_libraries # noinspection PyUnresolvedReferences from tuprolog.solve.channel import InputChannel, OutputChannel from tuprolog.pyutils import iterable_or_varargs, dict_or_keyword_args from tuprolog.jvmutils import jlist, jmap from typing import Mapping, Union, Iterable, Any def _forward_iterable_or_varargs(callable, args, *callable_args): return iterable_or_varargs(args, lambda xs: callable(jlist(xs), *callable_args)) def _forward_dict_or_keywords(callable, dict, kwargs, *callable_args): return dict_or_keyword_args(dict, kwargs, lambda ds: callable(jmap(ds), *callable_args)) def reset_static_kb(*clauses: Union[Clause, Iterable[Clause]]) -> SideEffect.ResetStaticKb: return _forward_iterable_or_varargs(SideEffect.ResetStaticKb, clauses) def add_static_clauses(*clauses: Union[Clause, Iterable[Clause]]) -> SideEffect.AddStaticClauses: return _forward_iterable_or_varargs(SideEffect.AddStaticClauses, clauses) def remove_static_clauses(*clauses: Union[Clause, Iterable[Clause]]) -> SideEffect.RemoveStaticClauses: return _forward_iterable_or_varargs(SideEffect.RemoveStaticClauses, clauses) def reset_dynamic_kb(*clauses: Union[Clause, Iterable[Clause]]) -> SideEffect.ResetDynamicKb: return _forward_iterable_or_varargs(SideEffect.ResetDynamicKb, clauses) def add_dynamic_clauses(*clauses: Union[Clause, Iterable[Clause]]) -> SideEffect.AddDynamicClauses: return _forward_iterable_or_varargs(SideEffect.AddDynamicClauses, clauses) def remove_dynamic_clauses(*clauses: Union[Clause, Iterable[Clause]]) -> SideEffect.RemoveDynamicClauses: return _forward_iterable_or_varargs(SideEffect.RemoveDynamicClauses, clauses) def set_flags(flags: Mapping[str, Term] = {}, **kwargs: Term) -> SideEffect.SetFlags: return _forward_dict_or_keywords(SideEffect.SetFlags, flags, kwargs) def reset_flags(flags: Mapping[str, Term] = {}, **kwargs: Term) -> SideEffect.ResetFlags: return _forward_dict_or_keywords(SideEffect.ResetFlags, flags, kwargs) def clear_flags(*flag_names: str) -> SideEffect.ClearFlags: return _forward_iterable_or_varargs(SideEffect.ClearFlags, flag_names) def load_library(alias: str, library: Library) -> SideEffect.LoadLibrary: return SideEffect.LoadLibrary(alias, library) def unload_libraries(*aliases: str) -> SideEffect.UnloadLibraries: return _forward_iterable_or_varargs(SideEffect.UnloadLibraries, aliases) def update_library(alias: str, library: Library) -> SideEffect.UpdateLibrary: return SideEffect.UpdateLibrary(alias, library) def add_libraries(*libraries: Union[Libraries, AliasedLibrary]) -> SideEffect.AddLibraries: return SideEffect.AddLibraries(new_libraries(libraries)) def reset_libraries(*libraries: Union[Libraries, AliasedLibrary]) -> SideEffect.ResetLibraries: return SideEffect.ResetLibraries(new_libraries(libraries)) def set_operators(*operators: Union[Operator, Iterable[Operator]]) -> SideEffect.SetOperators: return _forward_iterable_or_varargs(SideEffect.SetOperators, operators) def reset_operators(*operators: Union[Operator, Iterable[Operator]]) -> SideEffect.ResetOperators: return _forward_iterable_or_varargs(SideEffect.ResetOperators, operators) def remove_operators(*operators: Union[Operator, Iterable[Operator]]) -> SideEffect.RemoveOperators: return _forward_iterable_or_varargs(SideEffect.RemoveOperators, operators) def open_input_channels( channels: Mapping[str, InputChannel] = {}, **kwargs: InputChannel ) -> SideEffect.OpenInputChannels: return _forward_dict_or_keywords(SideEffect.OpenInputChannels, channels, kwargs) def reset_input_channels( channels: Mapping[str, InputChannel] = {}, **kwargs: InputChannel ) -> SideEffect.ResetInputChannels: return _forward_dict_or_keywords(SideEffect.ResetInputChannels, channels, kwargs) def close_input_channels(*names: Union[str, Iterable[str]]) -> SideEffect.CloseInputChannels: return _forward_iterable_or_varargs(SideEffect.CloseInputChannels, names) def open_output_channels( channels: Mapping[str, OutputChannel] = {}, **kwargs: OutputChannel ) -> SideEffect.OpenOutputChannels: return _forward_dict_or_keywords(SideEffect.OpenOutputChannels, channels, kwargs) def reset_output_channels( channels: Mapping[str, OutputChannel] = {}, **kwargs: OutputChannel ) -> SideEffect.ResetOutputChannels: return _forward_dict_or_keywords(SideEffect.ResetOutputChannels, channels, kwargs) def close_output_channels(*names: Union[str, Iterable[str]]) -> SideEffect.CloseOutputChannels: return _forward_iterable_or_varargs(SideEffect.CloseOutputChannels, names) def set_persistent_data( data: Mapping[str, Any] = {}, **kwargs: Any ) -> SideEffect.SetPersistentData: return _forward_dict_or_keywords(SideEffect.SetPersistentData, data, kwargs, False) def reset_persistent_data( data: Mapping[str, Any] = {}, **kwargs: Any ) -> SideEffect.SetPersistentData: return _forward_dict_or_keywords(SideEffect.SetPersistentData, data, kwargs, True) def set_durable_data( data: Mapping[str, Any] = {}, **kwargs: Any ) -> SideEffect.SetDurableData: return _forward_dict_or_keywords(SideEffect.SetDurableData, data, kwargs, False) def reset_durable_data( data: Mapping[str, Any] = {}, **kwargs: Any ) -> SideEffect.SetDurableData: return _forward_dict_or_keywords(SideEffect.SetDurableData, data, kwargs, True) def set_ephemeral_data( data: Mapping[str, Any] = {}, **kwargs: Any ) -> SideEffect.SetEphemeralData: return _forward_dict_or_keywords(SideEffect.SetEphemeralData, data, kwargs, False) def reset_ephemeral_data( data: Mapping[str, Any] = {}, **kwargs: Any ) -> SideEffect.SetEphemeralData: return _forward_dict_or_keywords(SideEffect.SetEphemeralData, data, kwargs, True) logger.debug("Loaded JVM classes from it.unibo.tuprolog.solve.sideffects.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/solve/sideffcts/__init__.py
__init__.py
from tuprolog import logger import jpype from tuprolog.core import indicator as new_indicator from tuprolog.jvmutils import jiterable, protect_iterable from tuprolog.pyutils import iterable_or_varargs from typing import Sized @jpype.JImplementationFor("it.unibo.tuprolog.theory.Theory") class _KtTheory: def __jclass_init__(cls): Sized.register(cls) @property def is_mutable(self): return self.isMutable() def to_mutable_theory(self): return self.toMutableTheory() def to_immutable_theory(self): return self.toImmutableTheory() @jpype.JOverride def getClauses(self): return protect_iterable(self.getClauses_()) @property def clauses(self): return self.getClauses() @jpype.JOverride def getRules(self): return protect_iterable(self.getRules_()) @property def rules(self): return self.getRules() @jpype.JOverride def getDirectives(self): return protect_iterable(self.getDirectives_()) @property def directives(self): return self.getDirectives() def __len__(self): return self.getSize() def __add__(self, other): return self.plus(other) def __contains__(self, item): return self.contains(item) def __getitem__(self, item): return self.get(item) def _assert(self, method, clause, *clauses): if len(clauses) == 0: return method(clause) return iterable_or_varargs((clause,) + clauses, lambda cs: method(jiterable(cs))) def assert_a(self, clause, *clauses): self._assert(self.assertA, clause, *clauses) def assert_z(self, clause, *clauses): self._assert(self.assertZ, clause, *clauses) @jpype.JOverride def retract(self, clause, *clauses): if len(clauses) == 0: return self.retract_(clause) return iterable_or_varargs((clause,) + clauses, lambda cs: self.retract_(jiterable(cs))) def retract_all(self, clause): return self.retractAll(clause) @jpype.JOverride def abolish(self, name, arity=None, indicator=None): if name is not None: if arity is not None: return self.abolish_(new_indicator(name, arity)) else: return self.abolish_(name) elif indicator is not None: return self.abolish_(indicator) raise ValueError("You should provide at least either a name-arity couple or an indicator") @jpype.JOverride def equals(self, other, use_var_complete_name=True): return self.equals_(other, use_var_complete_name) def __eq__(self, other): return self.equals(other, use_var_complete_name=True) def to_string(self, as_prolog_text=False): return self.toString(as_prolog_text) @jpype.JImplementationFor("it.unibo.tuprolog.theory.RetractResult") class _KtRetractResult: def __jclass_init__(cls): pass @property def is_success(self): return self.isSuccess() @property def is_failure(self): return self.isFailure() @property def theory(self): return self.getTheory() @property def clauses(self): return self.getClauses() @property def first_clause(self): return self.getFirstClause() logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.theory.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/theory/_ktadapt.py
_ktadapt.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.theory as _theory from typing import Iterable, Union from tuprolog.core import Clause from ._ktadapt import * Theory = _theory.Theory MutableTheory = _theory.MutableTheory RetractResult = _theory.RetractResult def theory(*clauses: Union[Clause, Iterable[Clause]]) -> Theory: return iterable_or_varargs(clauses, lambda ts: Theory.of(jiterable(ts))) def mutable_theory(*clauses: Union[Clause, Iterable[Clause]]) -> MutableTheory: return iterable_or_varargs(clauses, lambda ts: MutableTheory.of(jiterable(ts))) logger.debug("Loaded JVM classes from it.unibo.tuprolog.theory.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/theory/__init__.py
__init__.py
from tuprolog import logger import jpype from tuprolog.jvmioutils import ensure_input_steam @jpype.JImplementationFor("it.unibo.tuprolog.theory.parsing.ClausesParser") class _KtClausesParser: def __jclass_init__(cls): pass @property def default_operator_set(self): return self.getDefaultOperatorSet() def _parse(self, method, input, operators): if operators is None: return method(input) else: return method(input, operators) def parse_theory(self, input, operators): return self._parse(self.parseTheory, input, operators) def parse_clauses_lazily(self, input, operators): return self._parse(self.parseClausesLazily, input, operators) def parse_clauses(self, input, operators): return list(self.parse_clauses_lazily(input, operators)) @jpype.JImplementationFor("it.unibo.tuprolog.theory.parsing.ClausesReader") class _KtClausesReader: def __jclass_init__(cls): pass @property def default_operator_set(self): return self.getDefaultOperatorSet() def _read(self, method, input, operators): input_stream = ensure_input_steam(input) if operators is None: return method(input_stream) else: return method(input_stream, operators) def read_theory(self, input, operators): return self._read(self.readTheory, input, operators) def read_clauses_lazily(self, input, operators): return self._read(self.readClausesLazily, input, operators) def read_clauses(self, input, operators): return list(self.read_clauses_lazily(input, operators)) logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.theory.parsing.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/theory/parsing/_ktadapt.py
_ktadapt.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.theory.parsing as _parsing from tuprolog.core import Clause from tuprolog.core.parsing import _factory from tuprolog.theory import Theory from tuprolog.jvmutils import InputStream from tuprolog.core.operators import OperatorSet from typing import Union, Iterable from ._ktadapt import * ClausesParser = _parsing.ClausesParser ClausesReader = _parsing.ClausesReader def clauses_parser(with_default_operators: bool = True, operators: OperatorSet = None) -> ClausesParser: return _factory(ClausesParser, with_default_operators, operators) def clauses_reader(with_default_operators: bool = True, operators: OperatorSet = None) -> ClausesReader: return _factory(ClausesReader, with_default_operators, operators) DEFAULT_CLAUSES_PARSER = clauses_parser() DEFAULT_CLAUSES_READER = clauses_reader() def parse_theory(string: str, operators: OperatorSet = None) -> Theory: return DEFAULT_CLAUSES_PARSER.parse_theory(string, operators) def parse_clauses(string: str, operators: OperatorSet = None, lazy: bool = True) -> Iterable[Clause]: if lazy: return DEFAULT_CLAUSES_PARSER.parse_clauses_lazily(string, operators) else: return DEFAULT_CLAUSES_PARSER.parse_clauses(string, operators) def read_theory(input: Union[InputStream, str], operators: OperatorSet = None) -> Theory: return DEFAULT_CLAUSES_READER.read_theory(input, operators) def read_clauses(input: Union[InputStream, str], operators: OperatorSet = None, lazy: bool = True) -> Iterable[Clause]: if lazy: return DEFAULT_CLAUSES_READER.read_clauses_lazily(input, operators) else: return DEFAULT_CLAUSES_READER.read_clauses(input, operators) logger.debug("Loaded JVM classes from it.unibo.tuprolog.theory.parsing.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/theory/parsing/__init__.py
__init__.py
from decimal import Decimal from tuprolog import logger import jpype from ._ktmath import big_integer, big_decimal, BigInteger, BigDecimal from tuprolog.utils import * from typing import Sized, Callable from tuprolog.jvmutils import jiterable from tuprolog.pyutils import iterable_or_varargs from tuprolog.jvmutils import kfunction from ._ktmath import * @jpype.JImplementationFor("it.unibo.tuprolog.core.Term") class _KtTerm: def __jclass_init__(cls): pass def __getitem__(self, item, *items): return self.get(item, *items) @property def variables(self): return self.getVariables() def structurally_equals(self, other): return self.structurallyEquals(other) @jpype.JOverride() def equals(self, other, use_var_complete_name: bool = True): return self.equals_(other, use_var_complete_name) @property def is_var(self): return self.isVar() @property def is_ground(self): return self.isGround() @property def is_struct(self): return self.isStruct() @property def is_truth(self): return self.isTruth() @property def is_recursive(self): return self.isRecursive() @property def is_atom(self): return self.isAtom() @property def is_constant(self): return self.isConstant() @property def is_number(self): return self.isNumber() @property def is_integer(self): return self.isInteger() @property def is_real(self): return self.isReal() @property def is_list(self): return self.isList() @property def is_tuple(self): return self.isTuple() @property def is_block(self): return self.isBlock() @property def is_clause(self): return self.isClause() @property def is_rule(self): return self.isRule() @property def is_fact(self): return self.isFact() @property def is_directive(self): return self.isDirective() @property def is_cons(self): return self.isCons() @property def is_empty_list(self): return self.isEmptyList() @property def is_true(self): return self.isTrue() @property def is_fail(self): return self.isFail() @property def is_indicator(self): return self.isIndicator() def fresh_copy(self, scope=None): if scope is None: return self.freshCopy() else: return self.freshCopy(scope) @jpype.JImplementationFor("it.unibo.tuprolog.core.Struct") class _KtStruct: def __jclass_init__(cls): pass @property def functor(self): return self.getFunctor() @property def args(self): return self.getArgs() @property def argsSequence(self): return self.getArgsSequence() @property def arity(self): return self.getArity() @property def is_functor_well_formed(self): return self.isFunctorWellFormed() @property def indicator(self): return self.getIndicator() def get_arg_at(self, index): return self.getArgAt(index) def add_last(self, argument): return self.addLast(argument) def add_first(self, argument): return self.addFirst(argument) def insert_at(self, index, argument): return self.addFirst(index, argument) def set_functor(self, functor): return self.setFunctor(functor) def set_args(self, *args): return iterable_or_varargs(args, lambda xs: self.setArgs(jiterable(args))) @jpype.JImplementationFor("it.unibo.tuprolog.core.Var") class _KtVar: def __jclass_init__(cls): pass @property def is_anonymous(self): return self.isAnonymous() @property def name(self): return self.getName() @property def id(self): return self.getId() @property def complete_name(self): return self.getCompleteName() @property def is_name_well_formed(self): return self.isNameWellFormed() @jpype.JImplementationFor("it.unibo.tuprolog.core.Constant") class _KtConstant: def __jclass_init__(cls): pass @property def value(self): return self.getValue() @jpype.JImplementationFor("it.unibo.tuprolog.core.Numeric") class _KtNumeric: def __jclass_init__(cls): pass @property def int_value(self): return python_integer(self.getIntValue()) @property def decimal_value(self): return python_decimal(self.getDecimalValue()) def to_int(self): return self.int_value def to_float(self): return float(self.decimal_value) @jpype.JImplementationFor("it.unibo.tuprolog.core.Integer") class _KtInteger: def __jclass_init__(cls): pass @property def value(self): return self.int_value @jpype.JImplementationFor("it.unibo.tuprolog.core.Real") class _KtReal: def __jclass_init__(cls): pass @property def value(self): return self.decimal_value @jpype.JImplementationFor("it.unibo.tuprolog.core.Recursive") class _KtRecursive: def __jclass_init__(cls): Sized.register(cls) @property def lazily_unfolded(self): return self.getUnfoldedSequence() @property def unfolded(self): return self.getUnfoldedList() @property def __len__(self): return self.getSize() def to_iterable(self): return self.toSequence() def to_list(self): return self.toList() def to_array(self): return self.toArray() @jpype.JImplementationFor("it.unibo.tuprolog.core.List") class _KtList: def __jclass_init__(cls): pass @property def is_well_formed(self): return self.isWellFormed() @property def last(self): return self.getLast() def estimated_length(self): return self.getEstimatedLength() @jpype.JImplementationFor("it.unibo.tuprolog.core.Cons") class _KtCons: def __jclass_init__(cls): pass @property def head(self): return self.getHead() @property def tail(self): return self.getTail() @jpype.JImplementationFor("it.unibo.tuprolog.core.Tuple") class _KtTuple: def __jclass_init__(cls): pass @property def left(self): return self.getLeft() @property def right(self): return self.getRight() @jpype.JImplementationFor("it.unibo.tuprolog.core.Clause") class _KtClause: def __jclass_init__(cls): pass @property def head(self): return self.getHead() @property def body(self): return self.getBody() @property def is_well_formed(self): return self.isWellFormed() @property def body_items(self): return self.getBodyItems() @property def body_size(self): return self.getBodySize() def get_body_item(self, index): return self.getBodyItem(index) def set_head(self, head): return self.setHead(head) def set_body(self, term): return self.setBody(term) def set_head_functor(self, functor): return self.setHeadFunctor(functor) def set_head_args(self, *args): return iterable_or_varargs(args, lambda xs: self.setHeadArgs(jiterable(args))) def insert_head_arg(self, index, argument): return self.setHeadArg(index, argument) def add_first_head_arg(self, argument): return self.addFirstHeadArg(argument) def add_last_head_arg(self, argument): return self.addLastHeadArg(argument) def append_head_arg(self, argument): return self.appendHeadArg(argument) def set_body_items(self, *args): return iterable_or_varargs(args, lambda xs: self.setBodyItems(jiterable(args))) def insert_body_item(self, index, item): return self.insertBodyItem(index, item) def add_first_body_item(self, item): return self.addFirstBodyItem(item) def add_last_body_item(self, item): return self.addLastBodyItem(item) def append_body_item(self, item): return self.appendBodyItem(item) @jpype.JImplementationFor("it.unibo.tuprolog.core.Rule") class _KtRule: def __jclass_init__(cls): pass @property def head_args(self): return self.getHeadArgs() @property def head_arity(self): return self.getHeadArity() def get_head_arg(self, index): return self.getHeadArg(index) @jpype.JImplementationFor("it.unibo.tuprolog.core.TermConvertible") class _KtTermConvertible: def __jclass_init__(cls): pass def to_term(self): return self.toTerm() @jpype.JImplementationFor("it.unibo.tuprolog.core.Substitution") class _KtSubstitution: def __jclass_init__(cls): pass @property def is_success(self): return self.isSuccess() @property def is_failed(self): return self.isFailed() def apply_to(self, term): return self.applyTo(term) def get_original(self, variable): return self.getOriginal(variable) def get_by_name(self, name): return self.getByName(name) def __add__(self, other): return self.plus(other) def __sub__(self, other): return self.minus(other) @jpype.JOverride def filter(self, filter): if isinstance(filter, Callable): return self.filter_(kfunction(1)(filter)) else: return self.filter_(filter) @jpype.JImplementationFor("it.unibo.tuprolog.core.Scope") class _KtScope: def __jclass_init__(cls): pass def __contains__(self, item): return self.contains(item) def __getitem__(self, item): return self.get(item) @property def variables(self): return self.getVariables() @property def fail(self): return self.getFail() @property def empty_list(self): return self.getEmptyList() @property def empty_block(self): return self.getEmptyBlock() def atom(self, string): return self.atomOf(string) def block(self, *terms): return iterable_or_varargs(terms, lambda ts: self.blockOf(jiterable(ts))) def clause(self, head=None, *body): return iterable_or_varargs(body, lambda bs: self.clauseOf(head, jiterable(bs))) def cons(self, head, tail=None): if tail is None: return self.listOf(head) else: return self.consOf(head, tail) def directive(self, *goals): return iterable_or_varargs(goals, lambda gs: self.directiveOf(jiterable(gs))) def fact(self, head): return self.factOf(head) def indicator(self, name, arity): return self.indicatorOf(name, arity) def integer(self, value): return self.intOf(big_integer(value)) def real(self, value): return self.intOf(big_integer(value)) def numeric(self, value): if isinstance(value, str): return self.numOf(value) if isinstance(value, int) or isinstance(value, BigInteger): return self.intOf(value) return self.realOf(value) def rule(self, head, *body): return iterable_or_varargs(body, lambda bs: self.ruleOf(head, jiterable(bs))) def struct(self, functor, *args): return iterable_or_varargs(args, lambda xs: self.structOf(functor, jiterable(xs))) def truth(self, value): return self.truthOf(value) def var(self, name): return self.varOf(name) def list(self, *items): return iterable_or_varargs(items, lambda xs: self.listOf(jiterable(xs))) def list_from(self, items, last=None): return self.listFrom(jiterable(items), last) def tuple(self, first, second, *others): return iterable_or_varargs(others, lambda os: self.tupleOf(jiterable([first, second] + list(os)))) @property def anonymous(self): return self.getAnonymous() @property def whatever(self): return self.getWhatever() logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.core.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/_ktadapt.py
_ktadapt.py
# noinspection PyUnresolvedReferences from typing import Union import decimal import jpype.imports # noinspection PyUnresolvedReferences import org.gciatto.kt.math as _ktmath # noinspection PyUnresolvedReferences import java.lang as _java_lang from math import ceil from tuprolog.pyutils import and_then BigInteger = _ktmath.BigInteger BigDecimal = _ktmath.BigDecimal MathContext = _ktmath.MathContext RoundingMode = _ktmath.RoundingMode _MAX_LONG = _java_lang.Long.MAX_VALUE _MIN_LONG = _java_lang.Long.MIN_VALUE BIG_INTEGER_MAX_LONG = BigInteger.of(_MAX_LONG) BIG_INTEGER_MIN_LONG = BigInteger.of(_MIN_LONG) BIG_INTEGER_ZERO = BigInteger.ZERO BIG_INTEGER_TEN = BigInteger.TEN BIG_INTEGER_ONE = BigInteger.ONE BIG_INTEGER_NEGATIVE_ONE = BigInteger.NEGATIVE_ONE BIG_INTEGER_TWO = BigInteger.TWO BIG_DECIMAL_ZERO = BigDecimal.ZERO BIG_DECIMAL_ONE = BigDecimal.ONE BIG_DECIMAL_ONE_HALF = BigDecimal.ONE_HALF BIG_DECIMAL_ONE_TENTH = BigDecimal.ONE_TENTH BIG_DECIMAL_E = BigDecimal.E BIG_DECIMAL_PI = BigDecimal.PI def _int_to_bytes(n: int) -> bytes: try: size = n.bit_length() // 8 + 1 return n.to_bytes(size, 'big', signed=True) except OverflowError as e: e.args = ["%s: %d, whose size is %d" % (e.args[0], n, size)] raise e def big_integer(value: Union[str, int], radix: int = None) -> BigInteger: if radix is not None: assert isinstance(value, str) return BigInteger.of(value, radix) if isinstance(value, str): return BigInteger.of(jpype.JString @ value) assert isinstance(value, int) bs = _int_to_bytes(value) return BigInteger(jpype.JArray(jpype.JByte) @ bs, 0, len(bs)) def python_integer(value: BigInteger) -> int: return int.from_bytes(value.toByteArray(), byteorder='big', signed=True) _python_rounding_modes = {decimal.ROUND_DOWN, decimal.ROUND_HALF_UP, decimal.ROUND_HALF_EVEN, decimal.ROUND_CEILING, decimal.ROUND_FLOOR, decimal.ROUND_UP, decimal.ROUND_HALF_DOWN, decimal.ROUND_05UP} def jvm_rounding_mode(mode): if mode == decimal.ROUND_DOWN: return RoundingMode.DOWN elif mode == decimal.ROUND_UP: return RoundingMode.UP elif mode == decimal.ROUND_FLOOR: return RoundingMode.FLOOR elif mode == decimal.ROUND_CEILING: return RoundingMode.CEILING elif mode == decimal.ROUND_HALF_UP: return RoundingMode.HALF_UP elif mode == decimal.ROUND_HALF_EVEN: return RoundingMode.HALF_EVEN elif mode == decimal.ROUND_HALF_DOWN: return RoundingMode.HALF_DOWN elif mode == decimal.ROUND_05UP: raise ValueError(f"Rounding mode {decimal.ROUND_05UP} has no Java correspondence") else: raise ValueError(f"Not a rounding mode {mode}") @and_then(lambda bd: bd.stripTrailingZeros()) def big_decimal(value: Union[str, int, float, decimal.Decimal], precision=0, rounding=RoundingMode.HALF_UP) -> BigDecimal: if precision is None: precision = decimal.getcontext().prec assert isinstance(precision, int) if rounding is None: rounding = jvm_rounding_mode(decimal.getcontext().rounding) elif rounding in _python_rounding_modes: rounding = jvm_rounding_mode(rounding) assert isinstance(rounding, RoundingMode) context = MathContext(precision, rounding) if isinstance(value, str): return BigDecimal.of(value, context) if isinstance(value, decimal.Decimal): return BigDecimal.of(jpype.JString @ str(value), context) if isinstance(value, BigInteger): return BigDecimal.of(value, context) if isinstance(value, int): return BigDecimal.of(big_integer(value), context) assert isinstance(value, float) return BigDecimal.of(jpype.JDouble @ value, context) def python_decimal(value: BigDecimal) -> decimal.Decimal: return decimal.Decimal(str(value))
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/_ktmath.py
_ktmath.py
from tuprolog import logger import jpype from tuprolog.core import TermVisitor @jpype.JImplements(TermVisitor) class AbstractTermVisitor(object): @jpype.JOverride def defaultValue(self, term): raise NotImplementedError() @jpype.JOverride def visitTerm(self, term): return TermVisitor.DefaultImpls.visitTerm(self, term) @jpype.JOverride def visitVar(self, term): return TermVisitor.DefaultImpls.visitVar(self, term) @jpype.JOverride def visitConstant(self, term): return TermVisitor.DefaultImpls.visitConstant(self, term) @jpype.JOverride def visitStruct(self, term): return TermVisitor.DefaultImpls.visitStruct(self, term) @jpype.JOverride def visitCollection(self, term): return TermVisitor.DefaultImpls.visitCollection(self, term) @jpype.JOverride def visitAtom(self, term): return TermVisitor.DefaultImpls.visitAtom(self, term) @jpype.JOverride def visitTruth(self, term): return TermVisitor.DefaultImpls.visitTruth(self, term) @jpype.JOverride def visitNumeric(self, term): return TermVisitor.DefaultImpls.visitNumeric(self, term) @jpype.JOverride def visitInteger(self, term): return TermVisitor.DefaultImpls.visitInteger(self, term) @jpype.JOverride def visitReal(self, term): return TermVisitor.DefaultImpls.visitReal(self, term) @jpype.JOverride def visitBlock(self, term): return TermVisitor.DefaultImpls.visitBlock(self, term) @jpype.JOverride def visitEmpty(self, term): return TermVisitor.DefaultImpls.visitEmpty(self, term) @jpype.JOverride def visitEmptyBlock(self, term): return TermVisitor.DefaultImpls.visitEmptyBlock(self, term) @jpype.JOverride def visitList(self, term): return TermVisitor.DefaultImpls.visitList(self, term) @jpype.JOverride def visitCons(self, term): return TermVisitor.DefaultImpls.visitCons(self, term) @jpype.JOverride def visitEmptyList(self, term): return TermVisitor.DefaultImpls.visitEmptyList(self, term) @jpype.JOverride def visitTuple(self, term): return TermVisitor.DefaultImpls.visitTuple(self, term) @jpype.JOverride def visitIndicator(self, term): return TermVisitor.DefaultImpls.visitIndicator(self, term) @jpype.JOverride def visitClause(self, term): return TermVisitor.DefaultImpls.visitClause(self, term) @jpype.JOverride def visitRule(self, term): return TermVisitor.DefaultImpls.visitRule(self, term) @jpype.JOverride def visitFact(self, term): return TermVisitor.DefaultImpls.visitFact(self, term) @jpype.JOverride def visitDirective(self, term): return TermVisitor.DefaultImpls.visitDirective(self, term) logger.debug("Loaded compatibility layer for JVM subtypes of " + str(TermVisitor.class_.getName()))
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/visitors.py
visitors.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype import jpype.imports from tuprolog.core import Formatter, TermFormatter from tuprolog.core.visitors import AbstractTermVisitor @jpype.JImplements(Formatter) class AbstractFormatter(object): @jpype.JOverride def format(self, term): raise NotImplementedError() @jpype.JImplements(TermFormatter) class AbstractTermFormatter(AbstractFormatter, AbstractTermVisitor): @jpype.JOverride def format(self, term): return term.accept(self) @jpype.JOverride def defaultValue(self, term): return super(AbstractTermVisitor).defaultValue(self, term) @jpype.JOverride def visitTerm(self, term): return super(AbstractTermVisitor, self).visitTerm(term) @jpype.JOverride def visitVar(self, term): return super(AbstractTermVisitor, self).visitVar(term) @jpype.JOverride def visitConstant(self, term): return super(AbstractTermVisitor, self).visitConstant(term) @jpype.JOverride def visitStruct(self, term): return super(AbstractTermVisitor, self).visitStruct(term) @jpype.JOverride def visitCollection(self, term): return super(AbstractTermVisitor, self).visitCollection(term) @jpype.JOverride def visitAtom(self, term): return super(AbstractTermVisitor, self).visitAtom(term) @jpype.JOverride def visitTruth(self, term): return super(AbstractTermVisitor, self).visitTruth(term) @jpype.JOverride def visitNumeric(self, term): return super(AbstractTermVisitor, self).visitNumeric(term) @jpype.JOverride def visitInteger(self, term): return super(AbstractTermVisitor, self).visitInteger(term) @jpype.JOverride def visitReal(self, term): return super(AbstractTermVisitor, self).visitReal(term) @jpype.JOverride def visitBlock(self, term): return super(AbstractTermVisitor, self).visitBlock(term) @jpype.JOverride def visitEmpty(self, term): return super(AbstractTermVisitor, self).visitEmpty(term) @jpype.JOverride def visitEmptyBlock(self, term): return super(AbstractTermVisitor, self).visitEmptyBlock(term) @jpype.JOverride def visitList(self, term): return super(AbstractTermVisitor, self).visitList(term) @jpype.JOverride def visitCons(self, term): return super(AbstractTermVisitor, self).visitCons(term) @jpype.JOverride def visitEmptyList(self, term): return super(AbstractTermVisitor, self).visitEmptyList(term) @jpype.JOverride def visitTuple(self, term): return super(AbstractTermVisitor, self).visitTuple(term) @jpype.JOverride def visitIndicator(self, term): return super(AbstractTermVisitor, self).visitIndicator(term) @jpype.JOverride def visitClause(self, term): return super(AbstractTermVisitor, self).visitClause(term) @jpype.JOverride def visitRule(self, term): return super(AbstractTermVisitor, self).visitRule(term) @jpype.JOverride def visitFact(self, term): return super(AbstractTermVisitor, self).visitFact(term) @jpype.JOverride def visitDirective(self, term): return super(AbstractTermVisitor, self).visitDirective(term) logger.debug("Loaded compatibility layer for JVM subtypes of " + str(TermFormatter.class_.getName()))
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/formatters.py
formatters.py
from decimal import Decimal from tuprolog import logger import jpype import jpype.imports from ._ktadapt import * # noinspection PyUnresolvedReferences import it.unibo.tuprolog.core as _core from tuprolog.pyutils import iterable_or_varargs from tuprolog.jvmutils import jiterable, jmap from typing import Iterable, Dict, Tuple as PyTuple Atom = _core.Atom Block = _core.Block Clause = _core.Clause Cons = _core.Cons Constant = _core.Constant Directive = _core.Directive Empty = _core.Empty EmptyBlock = _core.EmptyBlock EmptyList = _core.EmptyList Fact = _core.Fact Formatter = _core.Formatter Indicator = _core.Indicator Integer = _core.Integer List = _core.List Numeric = _core.Numeric Real = _core.Real Recursive = _core.Recursive Rule = _core.Rule Scope = _core.Scope Struct = _core.Struct Substitution = _core.Substitution Term = _core.Term TermComparator = _core.TermComparator TermConvertible = _core.TermConvertible TermFormatter = _core.TermFormatter Terms = _core.Terms TermVisitor = _core.TermVisitor Truth = _core.Truth Tuple = _core.Tuple Var = _core.Var @jpype.JImplements(TermConvertible) class AbstractTermConvertible(object): @jpype.JOverride def toTerm(self): raise NotImplementedError() def atom(string: str) -> Atom: return Atom.of(string) def block(*terms: Union[Term, Iterable[Term]]) -> Block: return iterable_or_varargs(terms, lambda ts: Block.of(jiterable(ts))) def clause(head: Term = None, *body: Union[Term, Iterable[Term]]): return iterable_or_varargs(body, lambda bs: Clause.of(head, jiterable(bs))) def empty_logic_list() -> EmptyList: return EmptyList.getInstance() def cons(head: Term, tail: Term = None) -> Cons: if tail is None: return Cons.singleton(head) else: return Cons.of(head, tail) def directive(*goals: Union[Term, Iterable[Term]]) -> Directive: return iterable_or_varargs(goals, lambda gs: Directive.of(jiterable(gs))) def empty_block() -> Block: return EmptyBlock.getInstance() def fact(struct: Union[Term, Iterable[Term]]) -> Fact: return Fact.of(struct) def indicator(name: Union[str, Term], arity: Union[int, Term]) -> Indicator: return Indicator.of(name, arity) def integer(value: Union[int, BigInteger, str]) -> Integer: return Integer.of(big_integer(value)) def real(value: Union[float, BigDecimal, str, Decimal]) -> Real: return Real.of(big_decimal(value)) def numeric(value: Union[int, BigInteger, BigDecimal, str, float, Decimal]) -> Numeric: if isinstance(value, str): return Numeric.of(jpype.JString @ value) if isinstance(value, int) or isinstance(value, BigInteger): return integer(value) return real(value) def rule(head: Struct, *body: Union[Term, Iterable[Term]]) -> Rule: return iterable_or_varargs(body, lambda bs: Rule.of(head, jiterable(bs))) def struct(functor: str, *args: Union[Term, Iterable[Term]]) -> Struct: return iterable_or_varargs(args, lambda xs: Struct.of(functor, jiterable(xs))) def truth(boolean: bool) -> Truth: return Truth.of(boolean) TRUE = Truth.TRUE FALSE = Truth.FALSE FAIL = Truth.FAIL def logic_list(*items: Union[Term, Iterable[Term]]) -> List: return iterable_or_varargs(items, lambda xs: List.of(jiterable(xs))) def logic_list_from(items: Iterable[Term], last: Term = None) -> List: return List.from_(jiterable(items), last) def logic_tuple(first: Term, second: Term, *others: Union[Term, Iterable[Term]]) -> Tuple: return iterable_or_varargs(others, lambda os: Tuple.of(jiterable([first, second] + list(os)))) def var(name: str) -> Var: return Var.of(name) def unifier(assignments: Dict[Var, Term] = {}) -> Substitution.Unifier: return Substitution.unifier(jmap(assignments)) def substitution(assignments: Dict[Var, Term] = {}) -> Substitution: return Substitution.of(jmap(assignments)) def failed() -> Substitution.Fail: return Substitution.failed() EMPTY_UNIFIER: Substitution.Unifier = substitution() FAILED_SUBSTITUTION: Substitution.Fail = failed() def scope(*variables: Union[Var, str]) -> Scope: if len(variables) == 0: return Scope.empty() vars = [var(v) if isinstance(v, str) else v for v in variables] return Scope.of(jpype.JArray(Var) @ vars) def variables(*names: str) -> PyTuple[Var]: assert len(names) > 0 return tuple((var(n) for n in names)) logger.debug("Loaded JVM classes from it.unibo.tuprolog.core.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/__init__.py
__init__.py
from tuprolog import logger import jpype from tuprolog.core import TermComparator @jpype.JImplements(TermComparator) class AbstractTermComparator(object): @jpype.JOverride def equals(self, other): return self is other @jpype.JOverride def compare(self, first, second): raise NotImplementedError() logger.debug("Loaded compatibility layer for JVM subtypes of " + str(TermComparator.class_.getName()))
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/comparators.py
comparators.py
from tuprolog import logger import jpype @jpype.JImplementationFor("it.unibo.tuprolog.core.operators.Operator") class _KtOperator: def __jclass_init__(cls): pass @property def functor(self): return self.getFunctor() @property def specifier(self): return self.getSpecifier() @property def priority(self): return self.getPriority() @jpype.JImplementationFor("it.unibo.tuprolog.core.operators.OperatorSet") class _KtOperatorSet: def __jclass_init__(cls): pass def __add__(self, other): return self.plus(other) def __sub__(self, other): return self.minus(other) logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.core.operators.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/operators/_ktadapt.py
_ktadapt.py
from tuprolog import logger from ._ktadapt import * # noinspection PyUnresolvedReferences import jpype # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.core.operators as _operators from tuprolog.jvmutils import jiterable from tuprolog.pyutils import iterable_or_varargs from tuprolog.core import Atom, Integer, Struct, Term from functools import singledispatch Operator = _operators.Operator OperatorSet = _operators.OperatorSet Specifier = _operators.Specifier @singledispatch def operator(functor: str, specifier: Specifier, priority: int) -> Operator: return Operator(functor, specifier, priority) @operator.register def _(priority: Integer, specifier: Atom, functor: Atom) -> Operator: return Operator.fromTerms(priority, specifier, functor) @operator.register def _(term: Struct) -> Operator: return Operator.fromTerm(term) def operator_set(*operators) -> OperatorSet: return iterable_or_varargs(operators, lambda os: OperatorSet(jiterable(os))) @singledispatch def specifier(name: str) -> Specifier: return Specifier.valueOf(name.upper()) @specifier.register def _(term: Term) -> Specifier: return Specifier.fromTerm(term) EMPTY_OPERATORS: OperatorSet = OperatorSet.EMPTY DEFAULT_OPERATORS: OperatorSet = OperatorSet.DEFAULT STANDARD_OPERATORS: OperatorSet = OperatorSet.STANDARD XF: Specifier = Specifier.XF YF: Specifier = Specifier.YF FX: Specifier = Specifier.FX FY: Specifier = Specifier.FY XFX: Specifier = Specifier.XFX XFY: Specifier = Specifier.XFY YFX: Specifier = Specifier.YFX logger.debug("Loaded JVM classes from it.unibo.tuprolog.core.operators.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/operators/__init__.py
__init__.py
from tuprolog import logger import jpype from tuprolog.jvmioutils import ensure_input_steam @jpype.JImplementationFor("it.unibo.tuprolog.core.parsing.TermParser") class _KtTermParser: def __jclass_init__(cls): pass @property def default_operator_set(self): return self.getDefaultOperatorSet() def _parse(self, method, input, operators): if operators is None: return method(input) else: return method(input, operators) def parse(self, input, operators=None): return self.parse_term(input, operators) def parse_term(self, input, operators=None): return self._parse(self.parseTerm, input, operators) def parse_struct(self, input, operators=None): return self._parse(self.parseStruct, input, operators) def parse_constant(self, input, operators=None): return self._parse(self.parseConstant, input, operators) def parse_var(self, input, operators=None): return self._parse(self.parseVar, input, operators) def parse_atom(self, input, operators=None): return self._parse(self.parseAtom, input, operators) def parse_numeric(self, input, operators=None): return self._parse(self.parseNumeric, input, operators) def parse_integer(self, input, operators=None): return self._parse(self.parseInteger, input, operators) def parse_real(self, input, operators=None): return self._parse(self.parseReal, input, operators) def parse_clause(self, input, operators=None): return self._parse(self.parseClause, input, operators) @jpype.JImplementationFor("it.unibo.tuprolog.core.parsing.TermReader") class _KtTermReader: def __jclass_init__(cls): pass @property def default_operator_set(self): return self.getDefaultOperatorSet() def _read(self, method, input, operators): input_stream = ensure_input_steam(input) if operators is None: return method(input_stream) else: return method(input_stream, operators) def read(self, input, operators=None): return self.read_term(input, operators) def read_term(self, input, operators=None): return self._read(self.readTerm, input, operators) def read_all(self, input, operators=None): return self.read_terms(input, operators) def read_terms(self, input, operators=None): return self._read(self.readTerms, input, operators) logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.core.parsing.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/parsing/_ktadapt.py
_ktadapt.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.core.parsing as _parsing from tuprolog.core import Term, Struct, Constant, Var, Atom, Numeric, Integer, Real, Clause from tuprolog.jvmutils import InputStream from tuprolog.core.operators import OperatorSet, DEFAULT_OPERATORS from typing import Union, Iterable from ._ktadapt import * TermParser = _parsing.TermParser TermReader = _parsing.TermReader ParseException = _parsing.ParseException InvalidTermTypeException = _parsing.InvalidTermTypeException def _factory(source, with_default_operators: bool = True, operators: OperatorSet = None): if operators is None: if with_default_operators: return source.getWithDefaultOperators() else: return source.getWithNoOperator() else: if with_default_operators: return source.withOperators(DEFAULT_OPERATORS.plus(operators)) else: return source.withOperators(operators) def term_parser(with_default_operators: bool = True, operators: OperatorSet = None) -> TermParser: return _factory(TermParser, with_default_operators, operators) def term_reader(with_default_operators: bool = True, operators: OperatorSet = None) -> TermParser: return _factory(TermReader, with_default_operators, operators) DEFAULT_TERM_PARSER = term_parser() DEFAULT_TERM_READER = term_reader() def parse_term(string: str, operators: OperatorSet = None) -> Term: return DEFAULT_TERM_PARSER.parse_term(string, operators) def parse_struct(string: str, operators: OperatorSet = None) -> Struct: return DEFAULT_TERM_PARSER.parse_struct(string, operators) def parse_constant(string: str, operators: OperatorSet = None) -> Constant: return DEFAULT_TERM_PARSER.parse_constant(string, operators) def parse_var(string: str, operators: OperatorSet = None) -> Var: return DEFAULT_TERM_PARSER.parse_var(string, operators) def parse_atom(string: str, operators: OperatorSet = None) -> Atom: return DEFAULT_TERM_PARSER.parse_atom(string, operators) def parse_numeric(string: str, operators: OperatorSet = None) -> Numeric: return DEFAULT_TERM_PARSER.parse_numeric(string, operators) def parse_integer(string: str, operators: OperatorSet = None) -> Integer: return DEFAULT_TERM_PARSER.parse_integer(string, operators) def parse_real(string: str, operators: OperatorSet = None) -> Real: return DEFAULT_TERM_PARSER.parse_real(string, operators) def parse_clause(string: str, operators: OperatorSet = None) -> Clause: return DEFAULT_TERM_PARSER.parse_clause(string, operators) def read_term(input: Union[InputStream, str], operators: OperatorSet = None) -> Term: return DEFAULT_TERM_READER.read_term(input, operators) def read_terms(input: Union[InputStream, str], operators: OperatorSet = None) -> Iterable[Term]: return DEFAULT_TERM_READER.read_terms(input, operators) logger.debug("Loaded JVM classes from it.unibo.tuprolog.core.parsing.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/parsing/__init__.py
__init__.py
from tuprolog import logger import jpype @jpype.JImplementationFor("it.unibo.tuprolog.core.exception.SubstitutionException") class _KtSubstitutionException: def __jclass_init__(cls): pass @property def substitution(self): return self.getSubstitution() @jpype.JImplementationFor("it.unibo.tuprolog.core.exception.SubstitutionApplicationException") class _KtSubstitutionApplicationException: def __jclass_init__(cls): pass @property def term(self): return self.getTerm() logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.core.exception.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/exception/_ktadapt.py
_ktadapt.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.core.exception as _exceptions from ._ktadapt import * TuPrologException = _exceptions.TuPrologException SubstitutionException = _exceptions.TuPrologException SubstitutionApplicationException = _exceptions.TuPrologException logger.debug("Loaded JVM classes from it.unibo.tuprolog.core.exception.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/core/exception/__init__.py
__init__.py
from tuprolog import logger import jpype @jpype.JImplementationFor("it.unibo.tuprolog.utils.Taggable") class _KtTaggable: def __jclass_init__(cls): pass @property def tags(self): return self.getTags() def get_tag(self, name): return self.getTag(name) def replace_tags(self, tags): return self.replaceTags(tags) def contains_tag(self, name): return self.containsTag(name) logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.utils.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/utils/_ktadapt.py
_ktadapt.py
from tuprolog import logger from ._ktadapt import * # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.utils as _utils Taggable = _utils.Taggable logger.debug("Loaded JVM classes from it.unibo.tuprolog.utils.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/utils/__init__.py
__init__.py
from pathlib import Path CLASSPATH = Path(__file__).parents[0]
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/libs/__init__.py
__init__.py
from setuptools import setup, find_packages setup( name="2to3", description="Adds the 2to3 command directly to entry_points.", license="MIT", version="1.0", author="xoviat", author_email="xoviat@gmail.com", keywords=["2to3"], long_description="", packages=find_packages(), entry_points={ 'console_scripts' : [ '2to3 = cmd_2to3.__main__:main', ], }, )
2to3
/2to3-1.0.tar.gz/2to3-1.0/setup.py
setup.py
import sys from lib2to3.main import main as l2to3_main def main(): sys.exit(l2to3_main("lib2to3.fixes"))
2to3
/2to3-1.0.tar.gz/2to3-1.0/cmd_2to3/__main__.py
__main__.py
# __ (Double Underscores, 2us) Glueing functionals by `import __` for python! ## Install The package is written in pure python, with no dependencies other than the Python language. Just do: ```sh pip install 2us ``` Requires Python 3.5 or higher. ## Why this? Python is a great language for creating convenient wrappers around native code and implementing simple, human-friendly functions. In python, a bunch of builtin higher-order methods (which means that they accept functions as arguments) such as `map`, `filter` are available. They enable streamed data processing on containers that focus on the processing itself, in contrast with *noisy code* on traditional command-based languages that is heavily involved in loops. However, you may occasionally run into the situatiion where you find that there is no standard library functions to implement in-line unpacking of tuples, adding all numbers in a list by a constant shift, so you will have to write: ```python map(lambda x: x + 1, some_list) map(lambda x: x[0], some_list) ``` which seems rather dumb due to the inconvenient definition of lambda functions in python. ## Using __ Start using the package by importing `__`: ```python import __ ``` And then `__` can be used to create convenient functions that are identical to those written with `lambda`. Examples: ```python assert sum(map(__ + 1, range(1000))) == sum(map(lambda x: x + 1, range(1000))) assert set(map(__[0], {1: 2, 4: 6}.items())) == {1, 4} assert functools.reduce(__ + __, range(1000)) == sum(range(1000)) ``` Currently there is a drawback: python do not support overriding `__contains__` returning non-boolean values, so the `in` condition should be handled separately. ```python assert tuple(map(__.is_in([1, 2]), [3, 1, 5, 0, 2])) == (False, True, False, False, True) assert list(map(__.contains('1'), '13')) == [True, False] ```
2us
/2us-0.0.1.tar.gz/2us-0.0.1/README.md
README.md
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="2us", # Replace with your own username version="0.0.1", author="flandre.info", author_email="flandre@scarletx.cn", description="Glueing functionals with __.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/strongrex2001/__", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3 :: Only", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", ], python_requires='~=3.5', )
2us
/2us-0.0.1.tar.gz/2us-0.0.1/setup.py
setup.py
# -*- coding: utf-8 -*- """ Created on Fri Oct 30 12:59:11 2020 @author: eliphat """ import sys import operator import functools from types import ModuleType class LambdaProxyModule(ModuleType): def __getattr__(self, name): return lambda x: getattr(x, name) def __call__(self, *args, **kwargs): return lambda x: x(*args, **kwargs) def __getitem__(self, key): return operator.itemgetter(key) def is_in(self, it): return functools.partial(operator.contains, it) def contains(self, other): if self is other: return lambda x, y: y in x return lambda x: other in x def __lt__(self, other): if self is other: return operator.__lt__ return lambda x: x < other def __le__(self, other): if self is other: return operator.__le__ return lambda x: x <= other def __eq__(self, other): if self is other: return operator.__eq__ return lambda x: x == other def __ne__(self, other): if self is other: return operator.__ne__ return lambda x: x != other def __gt__(self, other): if self is other: return operator.__gt__ return lambda x: x > other def __ge__(self, other): if self is other: return operator.__ge__ return lambda x: x >= other def __add__(self, other): if self is other: return operator.__add__ return lambda x: x + other def __sub__(self, other): if self is other: return operator.__sub__ return lambda x: x - other def __mul__(self, other): if self is other: return operator.__mul__ return lambda x: x * other def __matmul__(self, other): if self is other: return operator.__matmul__ return lambda x: x @ other def __truediv__(self, other): if self is other: return operator.__truediv__ return lambda x: x / other def __floordiv__(self, other): if self is other: return operator.__floordiv__ return lambda x: x // other def __mod__(self, other): if self is other: return operator.__mod__ return lambda x: x % other def __pow__(self, other): if self is other: return operator.__pow__ return lambda x: x ** other def __lshift__(self, other): if self is other: return operator.__lshift__ return lambda x: x << other def __rshift__(self, other): if self is other: return operator.__rshift__ return lambda x: x >> other def __and__(self, other): if self is other: return operator.__and__ return lambda x: x & other def __xor__(self, other): if self is other: return operator.__xor__ return lambda x: x ^ other def __or__(self, other): if self is other: return operator.__or__ return lambda x: x | other def __radd__(self, other): if self is other: return lambda x, y: y + x return lambda x: other + x def __rsub__(self, other): if self is other: return lambda x, y: y - x return lambda x: other - x def __rmul__(self, other): if self is other: return lambda x, y: y * x return lambda x: other * x def __rmatmul__(self, other): if self is other: return lambda x, y: y @ x return lambda x: other @ x def __rtruediv__(self, other): if self is other: return lambda x, y: y / x return lambda x: other / x def __rfloordiv__(self, other): if self is other: return lambda x, y: y // x return lambda x: other // x def __rmod__(self, other): if self is other: return lambda x, y: y % x return lambda x: other % x def __rpow__(self, other): if self is other: return lambda x, y: y ** x return lambda x: other ** x def __rlshift__(self, other): if self is other: return lambda x, y: y << x return lambda x: other << x def __rrshift__(self, other): if self is other: return lambda x, y: y >> x return lambda x: other >> x def __rand__(self, other): if self is other: return lambda x, y: y & x return lambda x: other & x def __rxor__(self, other): if self is other: return lambda x, y: y ^ x return lambda x: other ^ x def __ror__(self, other): if self is other: return lambda x, y: y | x return lambda x: other | x sys.modules[__name__].__class__ = LambdaProxyModule
2us
/2us-0.0.1.tar.gz/2us-0.0.1/__/__init__.py
__init__.py
2vyper is an automatic verifier for smart contracts written in Vyper, based on the `Viper <http://viper.ethz.ch>`_ verification infrastructure. It is being developed at the `Programming Methodology Group <http://www.pm.inf.ethz.ch/>`_ at ETH Zurich. 2vyper was mainly developed by Robin Sierra, Christian Bräm, and Marco Eilers. For examples of the provided specification constructs, check out the `examples folder <tests/resources/examples>`_. Note that the examples are written in Vyper 0.1.0, but 2vyper supports different versions if a version pragma is set. A short overview of the most important specification constructs can be found `here <docs/specifications.md>`_. For further documentation, read `our paper <https://arxiv.org/abs/2104.10274>`_ about 2vyper's specification constructs, `Robin Sierra's <https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Education/Theses/Robin_Sierra_MA_Report.pdf>`_ and `Christian Bräm's <https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Education/Theses/Christian%20Br%C3%A4m_MS_Report.pdf>`_ Master's theses on the tool. Dependencies (Ubuntu Linux, MacOS) =================================== Install Java >= 11 (64 bit) and Python >= 3.7 (64 bit). For usage with the Viper's verification condition generation backend Carbon, you will also need to install the .NET / the Mono runtime. Dependencies (Windows) ========================== 1. Install Java >= 11 (64 bit) and Python >= 3.7 (64 bit). 2. Install either Visual C++ Build Tools 2015 (http://go.microsoft.com/fwlink/?LinkId=691126) or Visual Studio 2015. For the latter, make sure to choose the option "Common Tools for Visual C++ 2015" in the setup (see https://blogs.msdn.microsoft.com/vcblog/2015/07/24/setup-changes-in-visual-studio-2015-affecting-c-developers/ for an explanation). Getting Started =============== 1. Clone the 2vyper repository:: git clone https://github.com/viperproject/2vyper cd 2vyper/ 2. Create a virtual environment and activate it:: virtualenv env source env/bin/activate 3. Install 2vyper:: pip install . Command Line Usage ================== To verify a specific file from the 2vyper directory, run:: 2vyper [OPTIONS] path-to-file.vy The following command line options are available:: ``--verifier`` Selects the Viper backend to use for verification. Possible options are ``silicon`` (for Symbolic Execution) and ``carbon`` (for Verification Condition Generation based on Boogie). Default: ``silicon``. ``--viper-jar-path`` Sets the path to the required Viper binaries (``silicon.jar`` or ``carbon.jar``). Only the binary for the selected backend is required. We recommend that you use the provided binary packages installed by default, but you can or compile your own from source. Expects either a single path or a colon- (Unix) or semicolon- (Windows) separated list of paths. Alternatively, the environment variables ``SILICONJAR``, ``CARBONJAR`` or ``VIPERJAR`` can be set. ``--z3`` Sets the path of the Z3 executable. Alternatively, the ``Z3_EXE`` environment variable can be set. ``--boogie`` Sets the path of the Boogie executable. Required if the Carbon backend is selected. Alternatively, the ``BOOGIE_EXE`` environment variable can be set. ``--counterexample`` Produces a counterexample if the verification fails. Currently only works with the default ``silicon`` backend. ``--vyper-root`` Sets the root directory for the Vyper compiler. ``--skip-vyper`` Skips type checking the given Vyper program using the Vyper compiler. ``--print-viper`` Print the generated Viper file to the command line. To see all possible command line options, invoke ``2vyper`` without arguments. Alternative Viper Versions ========================== To use a custom version of the Viper infrastructure, follow the `instructions here <https://bitbucket.org/viperproject/documentation/wiki/Home>`_. Look for ``sbt assembly`` to find instructions for packaging the required JAR files. Use the parameters mentioned above to instruct 2vyper to use your custom Viper version. Note that 2vyper may not always work with the most recent Viper version. Troubleshooting ======================= 1. On Windows: During the setup, you get an error like ``Microsoft Visual C++ 14.0 is required.`` or ``Unable to fnd vcvarsall.bat``: Python cannot find the required Visual Studio 2015 C++ installation, make sure you have either installed the Build Tools or checked the "Common Tools" option in your regular VS 2015 installation (see above). 2. While verifying a file, you get a stack trace ending with something like ``No matching overloads found``: The version of Viper you're using does not match your version of 2vyper. Try using the the one that comes with 2vyper instead. Build Status ============ .. image:: https://pmbuilds.inf.ethz.ch/buildStatus/icon?job=2vyper-linux-xenial&style=plastic :alt: Build Status :target: https://pmbuilds.inf.ethz.ch/job/2vyper-linux-xenial
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/README.rst
README.rst
""" Copyright (c) 2019 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 setuptools import setup, find_packages setup( name='2vyper', version='0.3.0', license='MPL-2.0', packages=find_packages('src'), package_dir={'': 'src'}, package_data={ 'twovyper.backends': ['*.jar'], 'twovyper.parsing': ['*.lark'], 'twovyper.resources': ['*.vpr'], }, install_requires=[ 'jpype1==0.7.0', 'lark-parser>=0.8.1', 'vyper==0.1.0b16', 'vvm==0.1.0', 'z3-solver', ], tests_require=[ 'pytest==4.5.0' ], entry_points={ 'console_scripts': [ '2vyper = twovyper.main:main', ] }, author='Viper Team', author_email='viper@inf.ethz.ch', url='http://www.pm.inf.ethz.ch/research/nagini.html', description='Static verifier for Vyper, based on Viper.', long_description=(open('README.rst').read()), # Full list of classifiers could be found at: # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Software Development', ], )
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/setup.py
setup.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 os import sys import shutil import twovyper.backends def _backend_path(verifier: str): backends = os.path.dirname(twovyper.backends.__file__) return os.path.join(backends, f'{verifier}.jar') def _sif_path(): backends = os.path.dirname(twovyper.backends.__file__) return os.path.join(backends, 'silver-sif-extension.jar') def _executable_path(cmd: str, env: str = None) -> str: if env: env_var = os.environ.get(env) if env_var: return env_var return shutil.which(cmd, os.X_OK) def _construct_classpath(verifier: str = 'silicon'): """ Contstructs JAVA classpath. First tries environment variables ``VIPERJAVAPATH``, ``SILICONJAR`` and ``CARBONJAR``. If they are undefined, then uses packaged backends. """ viper_java_path = os.environ.get('VIPERJAVAPATH') silicon_jar = os.environ.get('SILICONJAR') carbon_jar = os.environ.get('CARBONJAR') sif_jar = os.environ.get('SIFJAR') if viper_java_path: return viper_java_path if silicon_jar and verifier == 'silicon': verifier_path = silicon_jar elif carbon_jar and verifier == 'carbon': verifier_path = carbon_jar else: verifier_path = _backend_path(verifier) sif_path = sif_jar or _sif_path() return os.pathsep.join([verifier_path, sif_path]) def _get_boogie_path(): """ Tries to detect path to Boogie executable. First tries the environment variable ``BOOGIE_EXE``. If it is not defined, it uses the system default. """ cmd = 'Boogie.exe' if sys.platform.startswith('win') else 'boogie' return _executable_path(cmd, 'BOOGIE_EXE') def _get_z3_path(): """ Tries to detect path to Z3 executable. First tries the environment variable ``Z3_EXE``. If it is not defined, it uses the system default (which is probably the one installed by the dependency). """ cmd = 'z3.exe' if sys.platform.startswith('win') else 'z3' return _executable_path(cmd, 'Z3_EXE') def set_classpath(v: str): global classpath classpath = _construct_classpath(v) classpath = _construct_classpath() z3_path = _get_z3_path() boogie_path = _get_boogie_path()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/config.py
config.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 argparse import logging import os from time import time from jpype import JException ######################################################################################################################## # DO NOT GLOBALLY IMPORT ANY SUBMODULE OF TWOVYPER THAT MIGHT DEPEND ON THE VYPER VERSION! # ######################################################################################################################## from twovyper import config from twovyper import vyper from twovyper.utils import reload_package from twovyper.viper.jvmaccess import JVM from twovyper.viper.typedefs import Program from twovyper.exceptions import ( InvalidVyperException, ParseException, UnsupportedException, InvalidProgramException, ConsistencyException ) class TwoVyper: def __init__(self, jvm: JVM, get_model: bool = False, check_ast_inconsistencies: bool = False): self.jvm = jvm self.get_model = get_model self.check_ast_inconsistencies = check_ast_inconsistencies def translate(self, path: str, vyper_root: str = None, skip_vyper: bool = False) -> Program: path = os.path.abspath(path) if not os.path.isfile(path): raise InvalidVyperException(f"Contract not found at the given location '{path}'.") vyper.set_vyper_version(path) from twovyper.verification import error_manager error_manager.clear() # Check that the file is a valid Vyper contract if not skip_vyper: vyper.check(path, vyper_root) logging.debug("Start parsing.") from twovyper.parsing import parser vyper_program = parser.parse(path, vyper_root, name=os.path.basename(path.split('.')[0])) logging.info("Finished parsing.") logging.debug("Start analyzing.") from twovyper.analysis import analyzer for interface in vyper_program.interfaces.values(): analyzer.analyze(interface) analyzer.analyze(vyper_program) logging.info("Finished analyzing.") logging.debug("Start translating.") from twovyper.translation import translator from twovyper.translation.translator import TranslationOptions options = TranslationOptions(self.get_model, self.check_ast_inconsistencies) translated = translator.translate(vyper_program, options, self.jvm) logging.info("Finished translating.") return translated def verify(self, program: Program, path: str, backend: str) -> 'VerificationResult': """ Verifies the given Viper program """ logging.debug("Start verifying.") from twovyper.verification.verifier import ( VerificationResult, ViperVerifier, AbstractVerifier ) verifier: AbstractVerifier = ViperVerifier[backend].value result = verifier.verify(program, self.jvm, path, self.get_model) logging.info("Finished verifying.") return result def main() -> None: """ Entry point for the verifier. """ parser = argparse.ArgumentParser() parser.add_argument( 'vyper_file', help='Python file to verify' ) parser.add_argument( '--verifier', help='verifier to be used (carbon or silicon)', choices=['silicon', 'carbon'], default='silicon' ) parser.add_argument( '--viper-jar-path', help='Java CLASSPATH that includes Viper class files', default=None ) parser.add_argument( '--z3', help='path to Z3 executable', default=config.z3_path ) parser.add_argument( '--boogie', help='path to Boogie executable', default=config.boogie_path ) parser.add_argument( '--counterexample', action='store_true', help='print a counterexample if the verification fails', ) parser.add_argument( '--check-ast-inconsistencies', action='store_true', help='Check the generated Viper AST for potential inconsistencies.', ) parser.add_argument( '--vyper-root', help='import root directory for the Vyper contract', default=None ) parser.add_argument( '--skip-vyper', action='store_true', help='skip validity check of contract with the Vyper compiler' ) parser.add_argument( '--print-viper', action='store_true', help='print generated Viper program' ) parser.add_argument( '--write-viper-to-file', default=None, help='write generated Viper program to specified file' ) parser.add_argument( '--log', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='log level', default='WARNING' ) parser.add_argument( '--benchmark', type=int, help='run verification the given number of times to benchmark performance', default=-1 ) parser.add_argument( '--ide-mode', action='store_true', help='output errors in IDE format' ) args = parser.parse_args() if args.viper_jar_path: config.classpath = args.viper_jar_path else: config.set_classpath(args.verifier) config.boogie_path = args.boogie config.z3_path = args.z3 if not config.classpath: parser.error('missing argument: --viper-jar-path') if not config.z3_path: parser.error('missing argument: --z3') if args.verifier == 'carbon' and not config.boogie_path: parser.error('missing argument: --boogie') if args.verifier == 'carbon' and args.counterexample: parser.error('counterexamples are only supported with the Silicon backend') formatter = logging.Formatter() handler = logging.StreamHandler() handler.setFormatter(formatter) logging.basicConfig(level=args.log, handlers=[handler]) jvm = JVM(config.classpath) translate_and_verify(args.vyper_file, jvm, args) def translate_and_verify(vyper_file, jvm, args, print=print): try: start = time() tw = TwoVyper(jvm, args.counterexample, args.check_ast_inconsistencies) program = tw.translate(vyper_file, args.vyper_root, args.skip_vyper) if args.print_viper: print(str(program)) if args.write_viper_to_file: with open(args.write_viper_to_file, 'w') as fp: fp.write(str(program)) backend = args.verifier if args.benchmark >= 1: print("Run, Total, Start, End, Time") for i in range(args.benchmark): start = time() prog = tw.translate(vyper_file, args.vyper_root, args.skip_vyper) vresult = tw.verify(prog, vyper_file, backend) end = time() print(f"{i}, {args.benchmark}, {start}, {end}, {end - start}") else: vresult = tw.verify(program, vyper_file, backend) print(vresult.string(args.ide_mode, include_model=args.counterexample)) end = time() duration = end - start print(f"Verification took {duration:.2f} seconds.") except (InvalidProgramException, UnsupportedException) as e: print(e.error_string()) except ConsistencyException as e: print(e.program) print(e.message) for error in e.errors: print(error.toString()) except (InvalidVyperException, ParseException) as e: print(e.message) except JException as e: print(e.stacktrace()) raise e def prepare_twovyper_for_vyper_version(path: str) -> bool: """ Checks if the current loaded vyper version differs from the vyper version used in a vyper contract. If it does differ, reload the whole twovyper module. Please note that all references (e.g. via a "from ... import ...") to the twovyper module are not refreshed automatically. Therefore, use this function with caution. :param path: The path to a vyper contract. :return: True iff a reload of the module was performed. """ version = vyper.get_vyper_version() vyper.set_vyper_version(path) if version != vyper.get_vyper_version(): import twovyper reload_package(twovyper) return True return False if __name__ == '__main__': main()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/main.py
main.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 argparse import zmq DEFAULT_CLIENT_SOCKET = "tcp://localhost:5555" DEFAULT_SERVER_SOCKET = "tcp://*:5555" context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect(DEFAULT_CLIENT_SOCKET) parser = argparse.ArgumentParser() parser.add_argument( 'python_file', help='Python file to verify') args = parser.parse_args() socket.send_string(args.python_file) response = socket.recv_string() print(response)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/client.py
client.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 importlib import os from contextlib import contextmanager from types import ModuleType from typing import Callable, Iterable, List, Optional, TypeVar _ = object() @contextmanager def switch(*values): def match(*v, where=True): if not where or len(values) != len(v): return False return all(case is _ or actual == case for actual, case in zip(values, v)) yield match T = TypeVar('T') def first(iterable: Iterable[T]) -> Optional[T]: return next(iter(iterable), None) def first_index(statisfying: Callable[[T], bool], l) -> int: return next((i for i, v in enumerate(l) if statisfying(v)), -1) def flatten(iterables: Iterable[Iterable[T]]) -> List[T]: return [item for subiterable in iterables for item in subiterable] def unique(eq, iterable: Iterable[T]) -> List[T]: unique_iterable: List[T] = [] for elem in iterable: for uelem in unique_iterable: if eq(elem, uelem): break else: unique_iterable.append(elem) return unique_iterable def seq_to_list(scala_iterable): lst = [] it = scala_iterable.iterator() while it.hasNext(): lst.append(it.next()) return lst def list_to_seq(lst, jvm): seq = jvm.scala.collection.mutable.ArraySeq(len(lst)) for i, element in enumerate(lst): seq.update(i, element) return seq def reload_package(package): assert(hasattr(package, "__package__")) fn = package.__file__ fn_dir = os.path.dirname(fn) + os.sep module_visit = {fn} del fn # Reloading all modules in a depth first search matter starting from "package". def reload_recursive_ex(module): importlib.reload(module) for module_child in vars(module).values(): if isinstance(module_child, ModuleType): fn_child = getattr(module_child, "__file__", None) if (fn_child is not None) and fn_child.startswith(fn_dir): if fn_child not in module_visit: module_visit.add(fn_child) reload_recursive_ex(module_child) reload_recursive_ex(package) class Subscriptable(type): """ A metaclass to add dictionary lookup functionality to a class. The class needs to implement the `_subscript(_)` method. """ def __getitem__(cls, val): return cls._subscript(val)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/utils.py
utils.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 logging import os import re from subprocess import Popen, PIPE from typing import Optional, List, Dict, TypeVar import vvm import vyper from semantic_version import NpmSpec, Version from vvm.utils.convert import to_vyper_version from twovyper.exceptions import InvalidVyperException, UnsupportedVersionException try: # noinspection PyUnresolvedReferences,PyUnboundLocalVariable _imported except NameError: _imported = True # means the module is being imported else: _imported = False # means the module is being reloaded if _imported: _original_get_executable = vvm.install.get_executable def _get_executable(version=None, vvm_binary_path=None) -> str: path = _original_get_executable(version, vvm_binary_path) return os.path.abspath(path) _version_pragma_pattern = re.compile(r"(?:\n|^)\s*#\s*@version\s*([^\n]*)") _comment_pattern = re.compile(r"(?:\n|^)\s*(#|$)") _VYPER_VERSION = to_vyper_version(vyper.__version__) _installed_vyper_versions: Optional[List[Version]] = None _available_vyper_versions: Optional[List[Version]] = None _current_vyper_version: Optional[Version] = None _cache_of_parsed_version_strings: Dict[str, NpmSpec] = {} # noinspection PyUnboundLocalVariable vvm.install.get_executable = _get_executable def _parse_version_string(version_str: str) -> NpmSpec: result = _cache_of_parsed_version_strings.get(version_str) if result is not None: return result try: result = NpmSpec(version_str) except ValueError: try: version = to_vyper_version(version_str) result = NpmSpec(str(version)) except Exception: raise InvalidVyperException(f"Cannot parse Vyper version from pragma: {version_str}") _cache_of_parsed_version_strings[version_str] = result return result def _get_vyper_pragma_spec(path: str) -> NpmSpec: pragma_string = None with open(path, 'r') as file: for line in file: pragma_match = _version_pragma_pattern.match(line) if pragma_match is not None: pragma_string = pragma_match.groups()[0] pragma_string = " ".join(pragma_string.split()) break comment_match = _comment_pattern.match(line) if comment_match is None: # version pragma has to comme before code break if pragma_string is None: pragma_string = vyper.__version__ logging.warning(f'No version pragma found. (Using vyper version "{pragma_string}" instead.)') return _parse_version_string(pragma_string) def _find_vyper_version(file: str) -> str: global _installed_vyper_versions if _installed_vyper_versions is None: _installed_vyper_versions = vvm.get_installed_vyper_versions() _installed_vyper_versions.append(_VYPER_VERSION) pragma_specs = _get_vyper_pragma_spec(file) version = pragma_specs.select(_installed_vyper_versions) if not version: global _available_vyper_versions if _available_vyper_versions is None: _available_vyper_versions = vvm.get_installable_vyper_versions() version = pragma_specs.select(_available_vyper_versions) if not version: raise InvalidVyperException(f"Invalid vyper version pragma: {pragma_specs}") lock = vvm.install.get_process_lock(f"locked${version}") with lock: try: _get_executable(version) except vvm.exceptions.VyperNotInstalled: vvm.install_vyper(version) if version not in _installed_vyper_versions: _installed_vyper_versions.append(version) return version def check(file: str, root=None): """ Checks that the file is a valid Vyper contract. If not, throws an `InvalidVyperException`. """ if _VYPER_VERSION == _current_vyper_version: path_str = 'vyper' else: path = _get_executable(_current_vyper_version) path_str = os.path.abspath(path) pipes = Popen([path_str, file], stdout=PIPE, stderr=PIPE, cwd=root) _, stderr = pipes.communicate() if pipes.returncode != 0: err_msg = stderr.strip().decode('utf-8') raise InvalidVyperException(err_msg) def get_vyper_version() -> Version: if _current_vyper_version is None: return _VYPER_VERSION return _current_vyper_version def set_vyper_version(file: str): global _current_vyper_version _current_vyper_version = _find_vyper_version(file) def is_compatible_version(version: str) -> bool: vyper_version = get_vyper_version() specs = _parse_version_string(version) return specs.match(vyper_version) T = TypeVar('T') def select_version(value_dict: Dict[str, T], default: T = None) -> T: for version_str, value in value_dict.items(): if is_compatible_version(version_str): return value else: if default is None: raise UnsupportedVersionException() return default
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/vyper.py
vyper.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/__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/. """ import os from twovyper.ast import ast_nodes as ast from twovyper.ast.text import pprint class TwoVyperException(Exception): def __init__(self, message: str): self.message = message class InvalidVyperException(TwoVyperException): """ Exception indicating that the file is not a valid Vyper contract. """ def __init__(self, vyper_output: str): message = f"Not a valid Vyper contract:\n{vyper_output}" super().__init__(message) class ParseException(TwoVyperException): """ Exception that is thrown if the contract cannot be parsed. """ def __init__(self, message: str): super().__init__(message) class TranslationException(TwoVyperException): def __init__(self, node: ast.Node, message: str): super().__init__(message) self.node = node def error_string(self) -> str: file_name = os.path.basename(self.node.file) line = self.node.lineno col = self.node.col_offset return f"{self.message} ({file_name}@{line}.{col})" class UnsupportedException(TranslationException): """ Exception that is thrown when attempting to translate a Vyper element not currently supported. """ def __init__(self, node: ast.Node, message: str = None): self.node = node if not message: message = pprint(node) super().__init__(node, f"Not supported: {message}") class InvalidProgramException(TranslationException): """ Signals that the input program is invalid and cannot be translated. """ def __init__(self, node: ast.Node, reason_code: str, message: str = None): self.node = node self.code = 'invalid.program' self.reason_code = reason_code if not message: node_msg = pprint(node, True) message = f"Node\n{node_msg}\nnot allowed here." super().__init__(node, f"Invalid program ({self.reason_code}): {message}") class ConsistencyException(TwoVyperException): """ Exception reporting that the translated AST has a consistency error. """ def __init__(self, program, message: str, errors): super().__init__(message) self.program = program self.errors = errors class UnsupportedVersionException(TwoVyperException): """ Exception that is thrown when a unsupported Vyper version is used by a contract. """ def __init__(self, message: str = None): if message is None: from twovyper.vyper import get_vyper_version message = f"The Vyper version ({get_vyper_version()}) used by the contract is not supported." super().__init__(message)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/exceptions.py
exceptions.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 os def viper_all(): resource_path = os.path.join(os.path.dirname(__file__), 'all.vpr') with open(resource_path, 'r') as resource_file: return resource_file.read(), resource_path
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/resources/__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/. """ import os from twovyper.ast import names from twovyper.ast.nodes import VyperProgram, VyperInterface from twovyper.exceptions import InvalidProgramException from twovyper.utils import first def check_symbols(program: VyperProgram): _check_ghost_functions(program) _check_ghost_implements(program) _check_resources(program) def _check_resources(program: VyperProgram): if not isinstance(program, VyperInterface): node = first(program.node.stmts) or program.node for interface in program.interfaces.values(): for resource_name, resources_list in interface.resources.items(): for resource in resources_list: if resource.file is None: if program.resources.get(resource_name) is None: if not program.config.has_option(names.CONFIG_ALLOCATION): raise InvalidProgramException(node, 'alloc.not.alloc', f'The interface "{interface.name}" uses the ' f'allocation config option. Therefore, this contract ' f'also has to enable this config option.') raise InvalidProgramException(node, 'missing.resource', f'The interface "{interface.name}" ' f'needs a default resource "{resource_name}" ' f'that is not present in this contract.') continue imported_resources = [r for r in program.resources.get(resource_name, []) if r.file == resource.file] if not imported_resources: prefix_length = len(os.path.commonprefix([resource.file, program.file])) raise InvalidProgramException(node, 'missing.resource', f'The interface "{interface.name}" ' f'needs a resource "{resource_name}" from ' f'".{os.path.sep}{resource.file[prefix_length:]}" but it ' f'was not imported for this contract.') imported_resources = [r for r in program.resources.get(resource_name) if r.interface == resource.interface] for imported_resource in imported_resources: if resource.file != imported_resource.file: prefix_length = len(os.path.commonprefix([resource.file, imported_resource.file])) resource_file = resource.file[prefix_length:] imported_resource_file = imported_resource.file[prefix_length:] raise InvalidProgramException(node, 'duplicate.resource', f'There are two versions of the resource ' f'"{resource_name}" defined in an interface ' f'"{imported_resource.interface}" one from ' f'[...]"{imported_resource_file}" the other from ' f'[...]"{resource_file}".') for interface_type in program.implements: interface = program.interfaces[interface_type.name] for resource_name, resource in program.declared_resources.items(): if resource_name in interface.own_resources: raise InvalidProgramException(resource.node, 'duplicate.resource', f'A contract cannot redeclare a resource it already imports. ' f'The resource "{resource_name}" got already declared in the ' f'interface {interface.name}.') def _check_ghost_functions(program: VyperProgram): if not isinstance(program, VyperInterface): node = first(program.node.stmts) or program.node for implemented_ghost in program.ghost_function_implementations.values(): if program.ghost_functions.get(implemented_ghost.name) is None: raise InvalidProgramException(implemented_ghost.node, 'missing.ghost', f'This contract is implementing an unknown ghost function. ' f'None of the interfaces, this contract implements, declares a ghost ' f'function "{implemented_ghost.name}".') for interface in program.interfaces.values(): for ghost_function_list in interface.ghost_functions.values(): for ghost_function in ghost_function_list: imported_ghost_functions = [ghost_func for ghost_func in program.ghost_functions.get(ghost_function.name, []) if ghost_func.file == ghost_function.file] if not imported_ghost_functions: prefix_length = len(os.path.commonprefix([ghost_function.file, program.file])) raise InvalidProgramException(node, 'missing.ghost', f'The interface "{interface.name}" ' f'needs a ghost function "{ghost_function.name}" from ' f'".{os.path.sep}{ghost_function.file[prefix_length:]}" but it ' f'was not imported for this contract.') imported_ghost_functions = [ghost_func for ghost_func in program.ghost_functions.get(ghost_function.name) if ghost_func.interface == ghost_function.interface] for imported_ghost_function in imported_ghost_functions: if ghost_function.file != imported_ghost_function.file: prefix_length = len(os.path.commonprefix( [ghost_function.file, imported_ghost_function.file])) ghost_function_file = ghost_function.file[prefix_length:] imported_ghost_function_file = imported_ghost_function.file[prefix_length:] raise InvalidProgramException(node, 'duplicate.ghost', f'There are two versions of the ghost function ' f'"{ghost_function.name}" defined in an interface ' f'"{ghost_function.interface}" one from ' f'[...]"{imported_ghost_function_file}" the other from ' f'[...]"{ghost_function_file}".') def _check_ghost_implements(program: VyperProgram): def check(cond, node, ghost_name, interface_name): if not cond: raise InvalidProgramException(node, 'ghost.not.implemented', f'The ghost function "{ghost_name}" from the interface "{interface_name}" ' f'has not been implemented correctly.') ghost_function_implementations = dict(program.ghost_function_implementations) for itype in program.implements: interface = program.interfaces[itype.name] for ghost in interface.own_ghost_functions.values(): implementation = ghost_function_implementations.pop(ghost.name, None) check(implementation is not None, program.node, ghost.name, itype.name) check(implementation.name == ghost.name, implementation.node, ghost.name, itype.name) check(len(implementation.args) == len(ghost.args), implementation.node, ghost.name, itype.name) check(implementation.type == ghost.type, implementation.node, ghost.name, itype.name) if len(ghost_function_implementations) > 0: raise InvalidProgramException(first(ghost_function_implementations.values()).node, 'invalid.ghost.implemented', f'This contract implements some ghost functions that have no declaration in ' f'any of the implemented interfaces.\n' f'(Ghost functions without declaration: {list(ghost_function_implementations)})')
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/analysis/symbol_checker.py
symbol_checker.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 zip_longest from contextlib import contextmanager from typing import Optional, Union, Dict, Iterable from twovyper.utils import first_index, switch, first from twovyper.ast import ast_nodes as ast, names, types from twovyper.ast.arithmetic import Decimal from twovyper.ast.types import ( TypeBuilder, VyperType, MapType, ArrayType, StringType, StructType, AnyStructType, SelfType, ContractType, InterfaceType, TupleType ) from twovyper.ast.nodes import VyperProgram, VyperFunction, GhostFunction, VyperInterface from twovyper.ast.text import pprint from twovyper.ast.visitors import NodeVisitor from twovyper.exceptions import InvalidProgramException, UnsupportedException from twovyper.vyper import is_compatible_version, select_version def _check(condition: bool, node: ast.Node, reason_code: str, msg: Optional[str] = None): if not condition: raise InvalidProgramException(node, reason_code, msg) class TypeAnnotator(NodeVisitor): # The type annotator annotates all expression nodes with type information. # It works by using the visitor pattern as follows: # - Each expression that is visited returns a list of possible types for it (ordered by # priority) and a list of nodes which will have that type, e.g., the literal 5 will return # the types [int128, uint256, address] when visited, and itself as the only node. # - Statements simply return None, as they don't have types. # - Some operations, e.g., binary operations, have as their result type the same type # as the input type. The 'combine' method combines the input type sets for that. # - If the required type is known at some point, 'annotate_expected' can be called with # the expected type as the argument. It then checks that the nodes of the expected type # and annotates all nodes. # - If any type can be used, 'annotate' can be called to annotate all nodes with the first # type in the list, i.e., the type with the highest priority. def __init__(self, program: VyperProgram): type_map = {} for name, struct in program.structs.items(): type_map[name] = struct.type for name, contract in program.contracts.items(): type_map[name] = contract.type for name, interface in program.interfaces.items(): type_map[name] = interface.type self.type_builder = TypeBuilder(type_map) self.program = program self.current_func: Union[VyperFunction, None] = None self.current_loops: Dict[str, ast.For] = {} self_type = self.program.fields.type # Contains the possible types a variable can have self.known_variables = { names.BLOCK: [types.BLOCK_TYPE], names.CHAIN: [types.CHAIN_TYPE], names.TX: [types.TX_TYPE], names.MSG: [types.MSG_TYPE], names.SELF: [types.VYPER_ADDRESS, self_type], names.LOG: [None], names.LEMMA: [None] } self.known_variables.update({interface: [None] for interface in program.interfaces.keys()}) self.variables = self.known_variables.copy() self.undecided_nodes = False self.type_resolver = TypeResolver() @contextmanager def _function_scope(self, func: Union[VyperFunction, GhostFunction]): old_func = self.current_func self.current_func = func old_variables = self.variables.copy() self.variables = self.known_variables.copy() self.variables.update({k: [v.type] for k, v in func.args.items()}) yield self.current_func = old_func self.variables = old_variables @contextmanager def _quantified_vars_scope(self): old_variables = self.variables.copy() yield self.variables = old_variables @contextmanager def _loop_scope(self): current_loops = self.current_loops yield self.current_loops = current_loops @property def method_name(self): return 'visit' def check_number_of_arguments(self, node: Union[ast.FunctionCall, ast.ReceiverCall], *expected: int, allowed_keywords: Iterable[str] = (), required_keywords: Iterable[str] = (), resources: int = 0): _check(len(node.args) in expected, node, 'invalid.no.args') for kw in node.keywords: _check(kw.name in allowed_keywords, node, 'invalid.no.args') for kw in required_keywords: _check(any(k.name == kw for k in node.keywords), node, 'invalid.no.args') if resources > 0 and self.program.config.has_option(names.CONFIG_NO_DERIVED_WEI): _check(node.resource is not None, node, 'invalid.resource', 'The derived wei resource got disabled and cannot be used.') if isinstance(node, ast.FunctionCall) and node.resource: if resources == 1: cond = not isinstance(node.resource, ast.Exchange) elif resources == 2: cond = isinstance(node.resource, ast.Exchange) else: cond = False _check(cond, node, 'invalid.no.resources') def annotate_program(self): for resources in self.program.resources.values(): for resource in resources: if (isinstance(resource.type, types.DerivedResourceType) and isinstance(resource.type.underlying_resource, types.UnknownResourceType)): underlying_resource, args = self._annotate_resource(resource.underlying_resource) resource.underlying_address = underlying_resource.own_address underlying_resource.derived_resources.append(resource) if len(args) != 0: _check(False, args[0], 'invalid.derived.resource', 'The underlying resource type must be declared without arguments.') resource.type.underlying_resource = underlying_resource.type derived_resource_member_types = resource.type.member_types.values() underlying_resource_member_types = underlying_resource.type.member_types.values() _check(resource.file != underlying_resource.file, resource.node, 'invalid.derived.resource', 'A resource cannot be a derived resource from a resource of the same contract.') _check(resource.underlying_address is not None, resource.node, 'invalid.derived.resource', 'The underlying resource of a derived resource must have an address specified.') for derived_member_type, underlying_member_type \ in zip_longest(derived_resource_member_types, underlying_resource_member_types): _check(derived_member_type == underlying_member_type, resource.node, 'invalid.derived.resource', 'Arguments of derived resource are not matching underlying resource.') if not isinstance(self.program, VyperInterface): # Set analysed flag to True for all resources for resources in self.program.resources.values(): for resource in resources: resource.analysed = True for function in self.program.functions.values(): with self._function_scope(function): for pre in function.preconditions: self.annotate_expected(pre, types.VYPER_BOOL, resolve=True) for performs in function.performs: self.annotate(performs, resolve=True) self.visit(function.node) self.resolve_type(function.node) for name, default in function.defaults.items(): if default: self.annotate_expected(default, function.args[name].type, resolve=True) for post in function.postconditions: self.annotate_expected(post, types.VYPER_BOOL, resolve=True) for check in function.checks: self.annotate_expected(check, types.VYPER_BOOL, resolve=True) for loop_invariants in function.loop_invariants.values(): for loop_invariant in loop_invariants: self.annotate_expected(loop_invariant, types.VYPER_BOOL, resolve=True) for lemma in self.program.lemmas.values(): with self._function_scope(lemma): for stmt in lemma.node.body: assert isinstance(stmt, ast.ExprStmt) self.annotate_expected(stmt.value, types.VYPER_BOOL, resolve=True) for name, default in lemma.defaults.items(): if default: self.annotate_expected(default, lemma.args[name].type, resolve=True) for pre in lemma.preconditions: self.annotate_expected(pre, types.VYPER_BOOL, resolve=True) for ghost_function in self.program.ghost_function_implementations.values(): assert isinstance(ghost_function, GhostFunction) with self._function_scope(ghost_function): expression_stmt = ghost_function.node.body[0] assert isinstance(expression_stmt, ast.ExprStmt) self.annotate_expected(expression_stmt.value, ghost_function.type.return_type, resolve=True) for inv in self.program.invariants: self.annotate_expected(inv, types.VYPER_BOOL, resolve=True) for post in self.program.general_postconditions: self.annotate_expected(post, types.VYPER_BOOL, resolve=True) for post in self.program.transitive_postconditions: self.annotate_expected(post, types.VYPER_BOOL, resolve=True) for check in self.program.general_checks: self.annotate_expected(check, types.VYPER_BOOL, resolve=True) if isinstance(self.program, VyperInterface): for caller_private in self.program.caller_private: self.annotate(caller_private, resolve=True) def resolve_type(self, node: ast.Node): if self.undecided_nodes: self.type_resolver.resolve_type(node) self.undecided_nodes = False def generic_visit(self, node: ast.Node, *args): assert False def pass_through(self, node1, node=None): vyper_types, nodes = self.visit(node1) if node is not None: nodes.append(node) return vyper_types, nodes def combine(self, node1, node2, node=None, allowed=lambda t: True): types1, nodes1 = self.visit(node1) types2, nodes2 = self.visit(node2) def is_array(t): return isinstance(t, ArrayType) and not t.is_strict def longest_array(matching, lst): try: arrays = [t for t in lst if is_array(t) and t.element_type == matching.element_type] return max(arrays, key=lambda t: t.size) except ValueError: raise InvalidProgramException(node if node is not None else node2, 'wrong.type') def intersect(l1, l2): for e in l1: if is_array(e): yield longest_array(e, l2) else: for t in l2: if types.matches(e, t): yield e elif types.matches(t, e): yield t intersection = list(filter(allowed, intersect(types1, types2))) if not intersection: raise InvalidProgramException(node if node is not None else node2, 'wrong.type') else: if node: return intersection, [*nodes1, *nodes2, node] else: return intersection, [*nodes1, *nodes2] def annotate(self, node1, node2=None, allowed=lambda t: True, resolve=False): if node2 is None: combined, nodes = self.visit(node1) else: combined, nodes = self.combine(node1, node2, allowed=allowed) for node in nodes: if len(combined) > 1: self.undecided_nodes = True node.type = combined else: node.type = combined[0] if resolve: self.resolve_type(node1) if node2 is not None: self.resolve_type(node2) def annotate_expected(self, node, expected, orelse=None, resolve=False): """ Checks that node has type `expected` (or matches the predicate `expected`) or, if that isn't the case, that is has type `orelse` (or matches the predicate `orelse`). """ tps, nodes = self.visit(node) def annotate_nodes(t): node.type = t for n in nodes: n.type = t if resolve: self.resolve_type(node) if isinstance(expected, VyperType): if any(types.matches(t, expected) for t in tps): annotate_nodes(expected) return else: for t in tps: if expected(t): annotate_nodes(t) return if orelse: self.annotate_expected(node, orelse) else: raise InvalidProgramException(node, 'wrong.type') def visit_FunctionDef(self, node: ast.FunctionDef): for stmt in node.body: self.visit(stmt) def visit_Return(self, node: ast.Return): if node.value: # Interfaces are allowed to just have `pass` as a body instead of a correct return, # therefore we don't check for the correct return type. if self.program.is_interface(): self.annotate(node.value) else: self.annotate_expected(node.value, self.current_func.type.return_type) def visit_Assign(self, node: ast.Assign): self.annotate(node.target, node.value) def visit_AugAssign(self, node: ast.AugAssign): self.annotate(node.target, node.value, types.is_numeric) def visit_AnnAssign(self, node: ast.AnnAssign): # This is a variable declaration so we add it to the type map. Since Vyper # doesn't allow shadowing, we can just override the previous value. variable_name = node.target.id variable_type = self.type_builder.build(node.annotation) self.variables[variable_name] = [variable_type] self.annotate_expected(node.target, variable_type) if node.value: self.annotate_expected(node.value, variable_type) def visit_For(self, node: ast.For): self.annotate_expected(node.iter, lambda t: isinstance(t, ArrayType)) # Add the loop variable to the type map var_name = node.target.id var_type = node.iter.type.element_type self.variables[var_name] = [var_type] self.annotate_expected(node.target, var_type) with self._loop_scope(): self.current_loops[var_name] = node # Visit loop invariants for loop_inv in self.current_func.loop_invariants.get(node, []): self.annotate_expected(loop_inv, types.VYPER_BOOL) # Visit body for stmt in node.body: self.visit(stmt) def visit_If(self, node: ast.If): self.annotate_expected(node.test, types.VYPER_BOOL) for stmt in node.body + node.orelse: self.visit(stmt) def visit_Raise(self, node: ast.Raise): if node.msg: if not (isinstance(node.msg, ast.Name) and node.msg.id == names.UNREACHABLE): self.annotate(node.msg) def visit_Assert(self, node: ast.Assert): self.annotate_expected(node.test, types.VYPER_BOOL) def visit_ExprStmt(self, node: ast.ExprStmt): self.annotate(node.value) def visit_Log(self, node: ast.Log): _check(isinstance(node.body, ast.FunctionCall), node, 'invalid.log') assert isinstance(node.body, ast.FunctionCall) for arg in node.body.args: self.annotate(arg) for kw in node.body.keywords: self.annotate(kw.value) def visit_Pass(self, node: ast.Pass): pass def visit_Continue(self, node: ast.Continue): pass def visit_Break(self, node: ast.Break): pass def visit_BoolOp(self, node: ast.BoolOp): self.annotate_expected(node.left, types.VYPER_BOOL) self.annotate_expected(node.right, types.VYPER_BOOL) return [types.VYPER_BOOL], [node] def visit_Not(self, node: ast.Not): self.annotate_expected(node.operand, types.VYPER_BOOL) return [types.VYPER_BOOL], [node] def visit_ArithmeticOp(self, node: ast.ArithmeticOp): return self.combine(node.left, node.right, node, types.is_numeric) def visit_UnaryArithmeticOp(self, node: ast.UnaryArithmeticOp): return self.pass_through(node.operand, node) def visit_IfExpr(self, node: ast.IfExpr): self.annotate_expected(node.test, types.VYPER_BOOL) return self.combine(node.body, node.orelse, node) def visit_Comparison(self, node: ast.Comparison): self.annotate(node.left, node.right) return [types.VYPER_BOOL], [node] def visit_Containment(self, node: ast.Containment): self.annotate_expected(node.list, lambda t: isinstance(t, ArrayType)) array_type = node.list.type assert isinstance(array_type, ArrayType) self.annotate_expected(node.value, array_type.element_type) return [types.VYPER_BOOL], [node] def visit_Equality(self, node: ast.Equality): self.annotate(node.left, node.right) return [types.VYPER_BOOL], [node] def visit_FunctionCall(self, node: ast.FunctionCall): name = node.name if node.resource: self._visit_resource(node.resource, node) with switch(name) as case: if case(names.CONVERT): self.check_number_of_arguments(node, 2) self.annotate(node.args[0]) ntype = self.type_builder.build(node.args[1]) return [ntype], [node] elif case(names.SUCCESS): self.check_number_of_arguments(node, 0, 1, allowed_keywords=[names.SUCCESS_IF_NOT]) if node.args: argument = node.args[0] assert isinstance(argument, ast.ReceiverCall) self.annotate(argument) _check(isinstance(argument.receiver.type, types.SelfType), argument, 'spec.success', 'Only functions defined in this contract can be called from the specification.') return [types.VYPER_BOOL], [node] elif case(names.REVERT): self.check_number_of_arguments(node, 0, 1) if node.args: argument = node.args[0] assert isinstance(argument, ast.ReceiverCall) self.annotate(argument) _check(isinstance(argument.receiver.type, types.SelfType), argument, 'spec.success', 'Only functions defined in this contract can be called from the specification.') return [types.VYPER_BOOL], [node] elif case(names.FORALL): return self._visit_forall(node) elif case(names.ACCESSIBLE): return self._visit_accessible(node) elif case(names.EVENT): self.check_number_of_arguments(node, 1, 2) return self._visit_event(node) elif case(names.PREVIOUS): self.check_number_of_arguments(node, 1) self.annotate(node.args[0]) loop = self._retrieve_loop(node, names.PREVIOUS) loop_array_type = loop.iter.type assert isinstance(loop_array_type, ArrayType) return [ArrayType(loop_array_type.element_type, loop_array_type.size, False)], [node] elif case(names.LOOP_ARRAY): self.check_number_of_arguments(node, 1) self.annotate(node.args[0]) loop = self._retrieve_loop(node, names.LOOP_ARRAY) loop_array_type = loop.iter.type assert isinstance(loop_array_type, ArrayType) return [loop_array_type], [node] elif case(names.LOOP_ITERATION): self.check_number_of_arguments(node, 1) self.annotate(node.args[0]) self._retrieve_loop(node, names.LOOP_ITERATION) return [types.VYPER_UINT256], [node] elif case(names.CALLER): self.check_number_of_arguments(node, 0) return [types.VYPER_ADDRESS], [node] elif case(names.RANGE): self.check_number_of_arguments(node, 1, 2) return self._visit_range(node) elif case(names.MIN) or case(names.MAX): self.check_number_of_arguments(node, 2) return self.combine(node.args[0], node.args[1], node, types.is_numeric) elif case(names.ADDMOD) or case(names.MULMOD): self.check_number_of_arguments(node, 3) for arg in node.args: self.annotate_expected(arg, types.VYPER_UINT256) return [types.VYPER_UINT256], [node] elif case(names.SQRT): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_DECIMAL) return [types.VYPER_DECIMAL], [node] elif case(names.SHIFT): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.VYPER_UINT256) self.annotate_expected(node.args[1], types.VYPER_INT128) elif case(names.BITWISE_NOT): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_UINT256) return [types.VYPER_UINT256], [node] elif case(names.BITWISE_AND) or case(names.BITWISE_OR) or case(names.BITWISE_XOR): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.VYPER_UINT256) self.annotate_expected(node.args[1], types.VYPER_UINT256) return [types.VYPER_UINT256], [node] elif case(names.OLD) or case(names.PUBLIC_OLD) or case(names.ISSUED): self.check_number_of_arguments(node, 1) return self.pass_through(node.args[0], node) elif case(names.INDEPENDENT): self.check_number_of_arguments(node, 2) self.annotate(node.args[0]) self.annotate(node.args[1]) return [types.VYPER_BOOL], [node] elif case(names.REORDER_INDEPENDENT): self.check_number_of_arguments(node, 1) self.annotate(node.args[0]) return [types.VYPER_BOOL], [node] elif case(names.FLOOR) or case(names.CEIL): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_DECIMAL) return [types.VYPER_INT128], [node] elif case(names.LEN): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], lambda t: isinstance(t, types.ArrayType)) return_type = select_version({'^0.2.0': types.VYPER_UINT256, '>=0.1.0-beta.16 <0.1.0': types.VYPER_INT128}) return [return_type], [node] elif case(names.STORAGE): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) # We know that storage(self) has the self-type first_arg = node.args[0] if isinstance(first_arg, ast.Name) and first_arg.id == names.SELF: return [self.program.type, AnyStructType()], [node] # Otherwise it is just some struct, which we don't know anything about else: return [AnyStructType()], [node] elif case(names.ASSERT_MODIFIABLE): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_BOOL) return [None], [node] elif case(names.SEND): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) self.annotate_expected(node.args[1], types.VYPER_WEI_VALUE) return [None], [node] elif case(names.SELFDESTRUCT): self.check_number_of_arguments(node, 0, 1) if node.args: # The selfdestruct Vyper function self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [None], [node] else: # The selfdestruct verification function return [types.VYPER_BOOL], [node] elif case(names.CLEAR): # Not type checking is needed here as clear may only occur in actual Vyper code self.annotate(node.args[0]) return [None], [node] elif case(names.RAW_CALL): # No type checking is needed here as raw_call may only occur in actual Vyper code for arg in node.args: self.annotate(arg) for kwarg in node.keywords: self.annotate(kwarg.value) idx = first_index(lambda n: n.name == names.RAW_CALL_OUTSIZE, node.keywords) outsize_arg = node.keywords[idx].value assert isinstance(outsize_arg, ast.Num) size = outsize_arg.n return [ArrayType(types.VYPER_BYTE, size, False)], [node] elif case(names.RAW_LOG): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], ArrayType(types.VYPER_BYTES32, 4, False)) self.annotate_expected(node.args[1], types.is_bytes_array) return [None], [node] elif case(names.CREATE_FORWARDER_TO): self.check_number_of_arguments(node, 1, allowed_keywords=[names.CREATE_FORWARDER_TO_VALUE]) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) if node.keywords: self.annotate_expected(node.keywords[0].value, types.VYPER_WEI_VALUE) return [types.VYPER_ADDRESS], [node] elif case(names.AS_WEI_VALUE): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.is_integer) unit = node.args[1] _check(isinstance(unit, ast.Str) and # Check that the unit exists next((v for k, v in names.ETHER_UNITS.items() if unit.s in k), False), node, 'invalid.unit') return [types.VYPER_WEI_VALUE], [node] elif case(names.AS_UNITLESS_NUMBER): self.check_number_of_arguments(node, 1) # We ignore units completely, therefore the type stays the same return self.pass_through(node.args[0], node) elif case(names.EXTRACT32): self.check_number_of_arguments(node, 2, allowed_keywords=[names.EXTRACT32_TYPE]) self.annotate_expected(node.args[0], types.is_bytes_array) self.annotate_expected(node.args[1], types.VYPER_INT128) return_type = self.type_builder.build(node.keywords[0].value) if node.keywords else types.VYPER_BYTES32 return [return_type], [node] elif case(names.CONCAT): _check(bool(node.args), node, 'invalid.no.args') for arg in node.args: self.annotate_expected(arg, types.is_bytes_array) size = sum(arg.type.size for arg in node.args) return [ArrayType(node.args[0].type.element_type, size, False)], [node] elif case(names.KECCAK256) or case(names.SHA256): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.is_bytes_array) return [types.VYPER_BYTES32], [node] elif case(names.BLOCKHASH): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_UINT256) return [types.VYPER_BYTES32], [node] elif case(names.METHOD_ID): if is_compatible_version('>=0.1.0-beta.16 <0.1.0'): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], lambda t: isinstance(t, StringType)) ntype = self.type_builder.build(node.args[1]) elif is_compatible_version('^0.2.0'): self.check_number_of_arguments(node, 1, allowed_keywords=[names.METHOD_ID_OUTPUT_TYPE]) self.annotate_expected(node.args[0], lambda t: isinstance(t, StringType)) ntype = types.ArrayType(types.VYPER_BYTE, 4) for keyword in node.keywords: if keyword.name == names.METHOD_ID_OUTPUT_TYPE: ntype = self.type_builder.build(keyword.value) else: assert False is_bytes32 = ntype == types.VYPER_BYTES32 is_bytes4 = (isinstance(ntype, ArrayType) and ntype.element_type == types.VYPER_BYTE and ntype.size == 4) _check(is_bytes32 or is_bytes4, node, 'invalid.method_id') return [ntype], [node] elif case(names.ECRECOVER): self.check_number_of_arguments(node, 4) self.annotate_expected(node.args[0], types.VYPER_BYTES32) self.annotate_expected(node.args[1], types.VYPER_UINT256) self.annotate_expected(node.args[2], types.VYPER_UINT256) self.annotate_expected(node.args[3], types.VYPER_UINT256) return [types.VYPER_ADDRESS], [node] elif case(names.ECADD) or case(names.ECMUL): self.check_number_of_arguments(node, 2) int_pair = ArrayType(types.VYPER_UINT256, 2) self.annotate_expected(node.args[0], int_pair) arg_type = int_pair if case(names.ECADD) else types.VYPER_UINT256 self.annotate_expected(node.args[1], arg_type) return [int_pair], [node] elif case(names.EMPTY): self.check_number_of_arguments(node, 1) ntype = self.type_builder.build(node.args[0]) return [ntype], [node] elif case(names.IMPLIES): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.VYPER_BOOL) self.annotate_expected(node.args[1], types.VYPER_BOOL) return [types.VYPER_BOOL], [node] elif case(names.RESULT): self.check_number_of_arguments(node, 0, 1, allowed_keywords=[names.RESULT_DEFAULT]) if node.args: argument = node.args[0] _check(isinstance(argument, ast.ReceiverCall), argument, 'spec.result', 'Only functions defined in this contract can be called from the specification.') assert isinstance(argument, ast.ReceiverCall) self.annotate(argument) _check(isinstance(argument.receiver.type, types.SelfType), argument, 'spec.result', 'Only functions defined in this contract can be called from the specification.') func = self.program.functions[argument.name] for kw in node.keywords: self.annotate_expected(kw.value, func.type.return_type) return [func.type.return_type], [node] elif len(node.keywords) > 0: _check(False, node.keywords[0].value, 'spec.result', 'The default keyword argument can only be used in combination with a pure function.') return [self.current_func.type.return_type], [node] elif case(names.SUM): self.check_number_of_arguments(node, 1) def is_numeric_map_or_array(t): return isinstance(t, types.MapType) and types.is_numeric(t.value_type) \ or isinstance(t, types.ArrayType) and types.is_numeric(t.element_type) self.annotate_expected(node.args[0], is_numeric_map_or_array) if isinstance(node.args[0].type, types.MapType): vyper_type = node.args[0].type.value_type elif isinstance(node.args[0].type, types.ArrayType): vyper_type = node.args[0].type.element_type else: assert False return [vyper_type], [node] elif case(names.TUPLE): return self._visit_tuple(node.args), [node] elif case(names.SENT) or case(names.RECEIVED) or case(names.ALLOCATED): self.check_number_of_arguments(node, 0, 1, resources=1 if case(names.ALLOCATED) else 0) if not node.args: map_type = types.MapType(types.VYPER_ADDRESS, types.NON_NEGATIVE_INT) return [map_type], [node] else: self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [types.NON_NEGATIVE_INT], [node] elif case(names.LOCKED): self.check_number_of_arguments(node, 1) lock = node.args[0] _check(isinstance(lock, ast.Str) and lock.s in self.program.nonreentrant_keys(), node, 'invalid.lock') return [types.VYPER_BOOL], [node] elif case(names.OVERFLOW) or case(names.OUT_OF_GAS): self.check_number_of_arguments(node, 0) return [types.VYPER_BOOL], [node] elif case(names.FAILED): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [types.VYPER_BOOL], [node] elif case(names.IMPLEMENTS): self.check_number_of_arguments(node, 2) address = node.args[0] interface = node.args[1] is_interface = (isinstance(interface, ast.Name) and (interface.id in self.program.interfaces or isinstance(self.program, VyperInterface) and interface.id == self.program.name)) _check(is_interface, node, 'invalid.interface') self.annotate_expected(address, types.VYPER_ADDRESS) return [types.VYPER_BOOL], [node] elif case(names.INTERPRETED): self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_BOOL) return [types.VYPER_BOOL], [node] elif case(names.CONDITIONAL): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.VYPER_BOOL) return self.pass_through(node.args[1], node) elif case(names.REALLOCATE): keywords = [names.REALLOCATE_TO, names.REALLOCATE_ACTOR] required = [names.REALLOCATE_TO] self.check_number_of_arguments(node, 1, allowed_keywords=keywords, required_keywords=required, resources=1) self.annotate_expected(node.args[0], types.VYPER_WEI_VALUE) self.annotate_expected(node.keywords[0].value, types.VYPER_ADDRESS) for kw in node.keywords: self.annotate_expected(kw.value, types.VYPER_ADDRESS) return [None], [node] elif case(names.FOREACH): return self._visit_foreach(node) elif case(names.OFFER): keywords = { names.OFFER_TO: types.VYPER_ADDRESS, names.OFFER_ACTOR: types.VYPER_ADDRESS, names.OFFER_TIMES: types.VYPER_UINT256 } required = [names.OFFER_TO, names.OFFER_TIMES] self.check_number_of_arguments(node, 2, allowed_keywords=keywords.keys(), required_keywords=required, resources=2) self.annotate_expected(node.args[0], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[1], types.VYPER_WEI_VALUE) for kw in node.keywords: self.annotate_expected(kw.value, keywords[kw.name]) return [None], [node] elif case(names.ALLOW_TO_DECOMPOSE): self.check_number_of_arguments(node, 2, resources=1) self.annotate_expected(node.args[0], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[1], types.VYPER_ADDRESS) return [None], [node] elif case(names.REVOKE): keywords = { names.REVOKE_TO: types.VYPER_ADDRESS, names.REVOKE_ACTOR: types.VYPER_ADDRESS } required = [names.REVOKE_TO] self.check_number_of_arguments(node, 2, allowed_keywords=keywords.keys(), required_keywords=required, resources=2) self.annotate_expected(node.args[0], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[1], types.VYPER_WEI_VALUE) for kw in node.keywords: self.annotate_expected(kw.value, keywords[kw.name]) return [None], [node] elif case(names.EXCHANGE): keywords = [names.EXCHANGE_TIMES] self.check_number_of_arguments(node, 4, allowed_keywords=keywords, required_keywords=keywords, resources=2) self.annotate_expected(node.args[0], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[1], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[2], types.VYPER_ADDRESS) self.annotate_expected(node.args[3], types.VYPER_ADDRESS) self.annotate_expected(node.keywords[0].value, types.VYPER_UINT256) return [None], [node] elif case(names.CREATE): keywords = { names.CREATE_TO: types.VYPER_ADDRESS, names.CREATE_ACTOR: types.VYPER_ADDRESS } self.check_number_of_arguments(node, 1, allowed_keywords=keywords.keys(), resources=1) _check(node.resource is not None and node.underlying_resource is None, node, 'invalid.create', 'Only non-derived resources can be used with "create"') self.annotate_expected(node.args[0], types.VYPER_UINT256) for kw in node.keywords: self.annotate_expected(kw.value, keywords[kw.name]) return [None], [node] elif case(names.DESTROY): keywords = [names.DESTROY_ACTOR] self.check_number_of_arguments(node, 1, resources=1, allowed_keywords=keywords) _check(node.resource is not None and node.underlying_resource is None, node, 'invalid.destroy', 'Only non-derived resources can be used with "destroy"') self.annotate_expected(node.args[0], types.VYPER_UINT256) for kw in node.keywords: self.annotate_expected(kw.value, types.VYPER_ADDRESS) return [None], [node] elif case(names.RESOURCE_PAYABLE): keywords = [names.RESOURCE_PAYABLE_ACTOR] self.check_number_of_arguments(node, 1, resources=1, allowed_keywords=keywords) _check(node.resource is None or node.underlying_resource is not None, node, 'invalid.payable', 'Only derived resources can be used with "payable"') self.annotate_expected(node.args[0], types.VYPER_UINT256) for kw in node.keywords: self.annotate_expected(kw.value, types.VYPER_ADDRESS) return [None], [node] elif case(names.RESOURCE_PAYOUT): keywords = [names.RESOURCE_PAYOUT_ACTOR] self.check_number_of_arguments(node, 1, resources=1, allowed_keywords=keywords) _check(node.resource is None or node.underlying_resource is not None, node, 'invalid.payout', 'Only derived resources can be used with "payout"') self.annotate_expected(node.args[0], types.VYPER_UINT256) for kw in node.keywords: self.annotate_expected(kw.value, types.VYPER_ADDRESS) return [None], [node] elif case(names.TRUST): keywords = [names.TRUST_ACTOR] self.check_number_of_arguments(node, 2, allowed_keywords=keywords) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) self.annotate_expected(node.args[1], types.VYPER_BOOL) for kw in node.keywords: self.annotate_expected(kw.value, types.VYPER_ADDRESS) return [None], [node] elif case(names.ALLOCATE_UNTRACKED): self.check_number_of_arguments(node, 1, resources=0) # By setting resources to 0 we only allow wei. _check(node.resource is None or node.underlying_resource is not None, node, 'invalid.allocate_untracked', 'Only derived resources can be used with "allocate_untracked"') self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [None], [node] elif case(names.OFFERED): self.check_number_of_arguments(node, 4, resources=2) self.annotate_expected(node.args[0], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[1], types.VYPER_WEI_VALUE) self.annotate_expected(node.args[2], types.VYPER_ADDRESS) self.annotate_expected(node.args[3], types.VYPER_ADDRESS) return [types.NON_NEGATIVE_INT], [node] elif case(names.NO_OFFERS): self.check_number_of_arguments(node, 1, resources=1) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [types.VYPER_BOOL], [node] elif case(names.ALLOWED_TO_DECOMPOSE): self.check_number_of_arguments(node, 1, resources=1) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [types.VYPER_UINT256], [node] elif case(names.TRUSTED): keywords = [names.TRUSTED_BY, names.TRUSTED_WHERE] required_keywords = [names.TRUSTED_BY] self.check_number_of_arguments(node, 1, allowed_keywords=keywords, required_keywords=required_keywords) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) for kw in node.keywords: self.annotate_expected(kw.value, types.VYPER_ADDRESS) return [types.VYPER_BOOL], [node] elif case(names.TRUST_NO_ONE): self.check_number_of_arguments(node, 2) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) self.annotate_expected(node.args[1], types.VYPER_ADDRESS) return [types.VYPER_BOOL], [node] elif len(node.args) == 1 and isinstance(node.args[0], ast.Dict): # This is a struct initializer self.check_number_of_arguments(node, 1) return self._visit_struct_init(node) elif name in self.program.contracts: # This is a contract initializer self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [self.program.contracts[name].type], [node] elif name in self.program.interfaces: # This is an interface initializer self.check_number_of_arguments(node, 1) self.annotate_expected(node.args[0], types.VYPER_ADDRESS) return [self.program.interfaces[name].type], [node] elif name in self.program.ghost_functions: possible_functions = self.program.ghost_functions[name] if len(possible_functions) != 1: if isinstance(self.program, VyperInterface): function = [fun for fun in possible_functions if fun.file == self.program.file][0] else: implemented_interfaces = [self.program.interfaces[i.name].file for i in self.program.implements] function = [fun for fun in possible_functions if fun.file in implemented_interfaces][0] else: function = possible_functions[0] self.check_number_of_arguments(node, len(function.args) + 1) arg_types = [types.VYPER_ADDRESS, *[arg.type for arg in function.args.values()]] for arg_type, arg in zip(arg_types, node.args): self.annotate_expected(arg, arg_type) return [function.type.return_type], [node] else: raise UnsupportedException(node, "Unsupported function call") def visit_ReceiverCall(self, node: ast.ReceiverCall): receiver = node.receiver if isinstance(receiver, ast.Name): # A lemma call if receiver.id == names.LEMMA: self.annotate(receiver) _check(not isinstance(receiver.type, (ContractType, InterfaceType)), receiver, 'invalid.lemma.receiver', 'A receiver, with name "lemma" and with a contract- or interface-type, is not supported.') lemma = self.program.lemmas[node.name] self.check_number_of_arguments(node, len(lemma.args)) for arg, func_arg in zip(node.args, lemma.args.values()): self.annotate_expected(arg, func_arg.type) return [types.VYPER_BOOL], [node] # A receiver ghost function call elif receiver.id in self.program.interfaces.keys(): self.annotate(receiver) function = self.program.interfaces[receiver.id].own_ghost_functions[node.name] self.check_number_of_arguments(node, len(function.args) + 1) arg_types = [types.VYPER_ADDRESS, *[arg.type for arg in function.args.values()]] for arg_type, arg in zip(arg_types, node.args): self.annotate_expected(arg, arg_type) return [function.type.return_type], [node] def expected(t): is_self_call = isinstance(t, SelfType) is_external_call = isinstance(t, (ContractType, InterfaceType)) is_log = t is None return is_self_call or is_external_call or is_log self.annotate_expected(receiver, expected) receiver_type = receiver.type # A self call if isinstance(receiver_type, SelfType): function = self.program.functions[node.name] num_args = len(function.args) num_defaults = len(function.defaults) self.check_number_of_arguments(node, *range(num_args - num_defaults, num_args + 1)) for arg, func_arg in zip(node.args, function.args.values()): self.annotate_expected(arg, func_arg.type) return [function.type.return_type], [node] else: for arg in node.args: self.annotate(arg) for kw in node.keywords: self.annotate(kw.value) # A logging call if not receiver_type: return [None], [node] # A contract call elif isinstance(receiver_type, ContractType): return [receiver_type.function_types[node.name].return_type], [node] elif isinstance(receiver_type, InterfaceType): interface = self.program.interfaces[receiver_type.name] function = interface.functions[node.name] return [function.type.return_type], [node] else: assert False def _visit_resource_address(self, node: ast.Node, resource_name: str, interface: Optional[VyperInterface] = None): self.annotate_expected(node, types.VYPER_ADDRESS) _check(resource_name != names.UNDERLYING_WEI, node, 'invalid.resource.address', 'The underlying wei resource cannot have an address.') is_wei = resource_name == names.WEI ref_interface = None if isinstance(node, ast.Name): ref_interface = self.program elif isinstance(node, ast.Attribute): for field, field_type in self.program.fields.type.member_types.items(): if node.attr == field: _check(isinstance(field_type, types.InterfaceType), node, 'invalid.resource.address') assert isinstance(field_type, types.InterfaceType) ref_interface = self.program.interfaces[field_type.name] _check(is_wei or resource_name in ref_interface.own_resources, node, 'invalid.resource.address') break else: _check(False, node, 'invalid.resource.address') elif isinstance(node, ast.FunctionCall): if node.name in self.program.ghost_functions: if isinstance(self.program, VyperInterface): function = self.program.ghost_functions[node.name][0] else: function = self.program.ghost_function_implementations.get(node.name) if function is None: function = self.program.ghost_functions[node.name][0] _check(isinstance(function.type.return_type, types.InterfaceType), node, 'invalid.resource.address') assert isinstance(function.type.return_type, types.InterfaceType) program = first(interface for interface in self.program.interfaces.values() if interface.file == function.file) or self.program ref_interface = program.interfaces[function.type.return_type.name] else: self.check_number_of_arguments(node, 1) ref_interface = self.program.interfaces[node.name] _check(is_wei or resource_name in ref_interface.own_resources, node, 'invalid.resource.address') elif isinstance(node, ast.ReceiverCall): assert node.name in self.program.ghost_functions assert isinstance(node.receiver, ast.Name) interface_name = node.receiver.id function = self.program.interfaces[interface_name].own_ghost_functions.get(node.name) _check(isinstance(function.type.return_type, types.InterfaceType), node, 'invalid.resource.address') assert isinstance(function.type.return_type, types.InterfaceType) program = first(interface for interface in self.program.interfaces.values() if interface.file == function.file) or self.program ref_interface = program.interfaces[function.type.return_type.name] _check(is_wei or resource_name in ref_interface.own_resources, node, 'invalid.resource.address') else: assert False if not is_wei and ref_interface is not None: if interface is not None: if isinstance(ref_interface, VyperInterface): _check(ref_interface.file == interface.file, node, 'invalid.resource.address') else: interface_names = [t.name for t in ref_interface.implements] interfaces = [ref_interface.interfaces[name] for name in interface_names] files = [ref_interface.file] + [i.file for i in interfaces] _check(interface.file in files, node, 'invalid.resource.address') elif isinstance(ref_interface, VyperInterface): self_is_interface = isinstance(self.program, VyperInterface) self_does_not_have_resource = resource_name not in self.program.own_resources _check(self_is_interface or self_does_not_have_resource, node, 'invalid.resource.address') def _annotate_resource(self, node: ast.Node, top: bool = False): if isinstance(node, ast.Name): resources = self.program.resources.get(node.id) if resources is not None and len(resources) == 1: resource = resources[0] if self.program.config.has_option(names.CONFIG_NO_DERIVED_WEI): _check(resource.name != names.WEI, node, 'invalid.resource') if (top and self.program.file != resource.file and resource.name != names.WEI and resource.name != names.UNDERLYING_WEI): interface = first(i for i in self.program.interfaces.values() if i.file == resource.file) _check(any(i.name == interface.name for i in self.program.implements), node, 'invalid.resource') _check(node.id in interface.declared_resources, node, 'invalid.resource') else: resource = self.program.declared_resources.get(node.id) args = [] elif isinstance(node, ast.FunctionCall) and node.name == names.CREATOR: resource, args = self._annotate_resource(node.args[0]) node.type = node.args[0].type elif isinstance(node, ast.FunctionCall): resources = self.program.resources.get(node.name) if resources is not None and len(resources) == 1: resource = resources[0] else: resource = self.program.declared_resources.get(node.name) if self.program.config.has_option(names.CONFIG_NO_DERIVED_WEI): _check(resource.name != names.WEI, node, 'invalid.resource') if node.resource is not None: assert isinstance(node.resource, ast.Expr) self._visit_resource_address(node.resource, node.name) resource.own_address = node.resource elif (top and self.program.file != resource.file and resource.name != names.WEI and resource.name != names.UNDERLYING_WEI): interface = first(i for i in self.program.interfaces.values() if i.file == resource.file) _check(any(i.name == interface.name for i in self.program.implements), node, 'invalid.resource') _check(node.name in interface.declared_resources, node, 'invalid.resource') args = node.args elif isinstance(node, ast.Attribute): assert isinstance(node.value, ast.Name) interface = self.program.interfaces[node.value.id] if top: _check(any(i.name == interface.name for i in self.program.implements), node, 'invalid.resource') _check(node.attr in interface.declared_resources, node, 'invalid.resource') resource = interface.declared_resources.get(node.attr) args = [] elif isinstance(node, ast.ReceiverCall): address = None if isinstance(node.receiver, ast.Name): interface = self.program.interfaces[node.receiver.id] if top: _check(any(i.name == interface.name for i in self.program.implements), node, 'invalid.resource') _check(node.name in interface.declared_resources, node, 'invalid.resource') 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 = self.program.interfaces[interface_name] if top: _check(node.name in interface.declared_resources, node, 'invalid.resource') address = node.receiver.index self._visit_resource_address(address, node.name, interface) else: assert False resource = interface.declared_resources.get(node.name) resource.own_address = address args = node.args elif isinstance(node, ast.Subscript): address = node.index resource, args = self._annotate_resource(node.value) node.type = node.value.type interface = None if isinstance(node.value, ast.Name): resource_name = node.value.id elif isinstance(node.value, ast.Attribute): assert isinstance(node.value.value, ast.Name) interface = self.program.interfaces[node.value.value.id] resource_name = node.value.attr _check(resource_name in interface.declared_resources, node, 'invalid.resource') else: assert False self._visit_resource_address(address, resource_name, interface) resource.own_address = address else: assert False if not resource: raise InvalidProgramException(node, 'invalid.resource', f'Could not find a resource for node:\n{pprint(node, True)}') for arg_type, arg in zip(resource.type.member_types.values(), args): self.annotate_expected(arg, arg_type) node.type = resource.type return resource, args def _visit_resource(self, node: ast.Node, top_node: Optional[ast.FunctionCall] = None): if isinstance(node, ast.Exchange): self._visit_resource(node.left, top_node) self._visit_resource(node.right, top_node) return resource, args = self._annotate_resource(node, True) if len(args) != len(resource.type.member_types): raise InvalidProgramException(node, 'invalid.resource') if top_node is not None and top_node.underlying_resource is None: top_node.underlying_resource = resource.underlying_resource def _add_quantified_vars(self, var_decls: ast.Dict): vars_types = zip(var_decls.keys, var_decls.values) for name, type_annotation in vars_types: var_type = self.type_builder.build(type_annotation) self.variables[name.id] = [var_type] name.type = var_type def _visit_forall(self, node: ast.FunctionCall): with self._quantified_vars_scope(): # Add the quantified variables {<x1>: <t1>, <x2>: <t2>, ...} to the # variable map first_arg = node.args[0] assert isinstance(first_arg, ast.Dict) self._add_quantified_vars(first_arg) # Triggers can have any type for arg in node.args[1:-1]: self.annotate(arg) # The quantified expression is always a Boolean self.annotate_expected(node.args[-1], types.VYPER_BOOL) return [types.VYPER_BOOL], [node] def _visit_foreach(self, node: ast.FunctionCall): with self._quantified_vars_scope(): # Add the quantified variables {<x1>: <t1>, <x2>: <t2>, ...} to the # variable map first_arg = node.args[0] assert isinstance(first_arg, ast.Dict) self._add_quantified_vars(first_arg) # Triggers can have any type for arg in node.args[1:-1]: self.annotate(arg) # Annotate the body self.annotate(node.args[-1]) return [None], [node] def _visit_accessible(self, node: ast.FunctionCall): self.annotate_expected(node.args[0], types.VYPER_ADDRESS) self.annotate_expected(node.args[1], types.VYPER_WEI_VALUE) if len(node.args) == 3: function_call = node.args[2] assert isinstance(function_call, ast.ReceiverCall) function = self.program.functions[function_call.name] for arg, arg_type in zip(function_call.args, function.type.arg_types): self.annotate_expected(arg, arg_type) return [types.VYPER_BOOL], [node] def _visit_event(self, node: ast.FunctionCall): event = node.args[0] assert isinstance(event, ast.FunctionCall) event_name = event.name event_type = self.program.events[event_name].type for arg, arg_type in zip(event.args, event_type.arg_types): self.annotate_expected(arg, arg_type) if len(node.args) == 2: self.annotate_expected(node.args[1], types.VYPER_UINT256) return [types.VYPER_BOOL], [node] def _visit_struct_init(self, node: ast.FunctionCall): ntype = self.program.structs[node.name].type struct_dict = node.args[0] assert isinstance(struct_dict, ast.Dict) for key, value in zip(struct_dict.keys, struct_dict.values): value_type = ntype.member_types[key.id] self.annotate_expected(value, value_type) return [ntype], [node] def _visit_range(self, node: ast.FunctionCall): _check(len(node.args) > 0, node, 'invalid.range') first_arg = node.args[0] self.annotate_expected(first_arg, types.is_integer) if len(node.args) == 1: # A range expression of the form 'range(n)' where 'n' is a constant assert isinstance(first_arg, ast.Num) size = first_arg.n elif len(node.args) == 2: second_arg = node.args[1] self.annotate_expected(second_arg, types.is_integer) if isinstance(second_arg, ast.ArithmeticOp) \ and second_arg.op == ast.ArithmeticOperator.ADD \ and ast.compare_nodes(first_arg, second_arg.left): assert isinstance(second_arg.right, ast.Num) # A range expression of the form 'range(x, x + n)' where 'n' is a constant size = second_arg.right.n else: assert isinstance(first_arg, ast.Num) and isinstance(second_arg, ast.Num) # A range expression of the form 'range(n1, n2)' where 'n1' and 'n2 are constants size = second_arg.n - first_arg.n else: raise InvalidProgramException(node, 'invalid.range') _check(size > 0, node, 'invalid.range', 'The size of a range(...) must be greater than zero.') return [ArrayType(types.VYPER_INT128, size, True)], [node] def _retrieve_loop(self, node, name): loop_var_name = node.args[0].id loop = self.current_loops.get(loop_var_name) _check(loop is not None, node, f"invalid.{name}") return loop @staticmethod def visit_Bytes(node: ast.Bytes): # Bytes could either be non-strict or (if it has length 32) strict non_strict = types.ArrayType(types.VYPER_BYTE, len(node.s), False) if len(node.s) == 32: return [non_strict, types.VYPER_BYTES32], [node] else: return [non_strict], [node] @staticmethod def visit_Str(node: ast.Str): string_bytes = bytes(node.s, 'utf-8') ntype = StringType(len(string_bytes)) return [ntype], [node] # Sets occur in trigger expressions def visit_Set(self, node: ast.Set): for elem in node.elements: # Triggers can have any type self.annotate(elem) return [None], [node] @staticmethod def visit_Num(node: ast.Num): if isinstance(node.n, int): max_int128 = 2 ** 127 - 1 max_address = 2 ** 160 - 1 if 0 <= node.n <= max_int128: tps = [types.VYPER_INT128, types.VYPER_UINT256, types.VYPER_ADDRESS, types.VYPER_BYTES32] elif max_int128 < node.n <= max_address: tps = [types.VYPER_UINT256, types.VYPER_ADDRESS, types.VYPER_BYTES32] elif max_address < node.n: tps = [types.VYPER_UINT256, types.VYPER_BYTES32] else: tps = [types.VYPER_INT128] nodes = [node] return tps, nodes elif isinstance(node.n, Decimal): return [types.VYPER_DECIMAL], [node] else: assert False @staticmethod def visit_Bool(node: ast.Bool): return [types.VYPER_BOOL], [node] def visit_Attribute(self, node: ast.Attribute): self.annotate_expected(node.value, lambda t: isinstance(t, StructType), types.VYPER_ADDRESS) struct_type = node.value.type if isinstance(node.value.type, StructType) else types.AddressType() ntype = struct_type.member_types.get(node.attr) if not ntype: raise InvalidProgramException(node, 'invalid.storage.var') return [ntype], [node] def visit_Subscript(self, node: ast.Subscript): self.annotate_expected(node.value, lambda t: isinstance(t, (ArrayType, MapType))) if isinstance(node.value.type, MapType): key_type = node.value.type.key_type self.annotate_expected(node.index, key_type) ntype = node.value.type.value_type elif isinstance(node.value.type, ArrayType): self.annotate_expected(node.index, types.is_integer) ntype = node.value.type.element_type else: assert False return [ntype], [node] def visit_Name(self, node: ast.Name): _check(node.id in self.variables, node, 'invalid.local.var') return self.variables[node.id], [node] def visit_List(self, node: ast.List): # Vyper guarantees that size > 0 size = len(node.elements) for e in node.elements: self.annotate(e) element_types = [e.type for e in node.elements] possible_types = [] for element_type in element_types: if isinstance(element_type, list): if possible_types: possible_types = [t for t in possible_types if t in element_type] else: possible_types = element_type else: _check(not possible_types or element_type in possible_types, node, 'invalid.element.types') possible_types = [element_type] break return [types.ArrayType(element_type, size) for element_type in possible_types], [node] def visit_Tuple(self, node: ast.Tuple): return self._visit_tuple(node.elements), [node] def _visit_tuple(self, elements): length = len(elements) for e in elements: self.annotate(e) element_types = [e.type if isinstance(e.type, list) else [e.type] for e in elements] sizes = [len(element_type) for element_type in element_types] index = [0] * length possible_types = [] while True: possible_type = TupleType([element_types[i][index[i]] for i in range(length)]) possible_types.append(possible_type) for i in range(length): index[i] = (index[i] + 1) % sizes[i] if index[i]: break else: break return possible_types class TypeResolver(NodeVisitor): def resolve_type(self, node: ast.Node): self.visit(node, None) def visit(self, node, *args): assert len(args) == 1 if hasattr(node, "type"): if isinstance(node.type, list): node.type = args[0] or node.type[0] return super().visit(node, *args) @staticmethod def first_intersect(left, right): if not isinstance(left, list): left = [left] if not isinstance(right, list): right = [right] for t in left: if t in right: return t def visit_Assign(self, node: ast.Assign, _: Optional[VyperType]): self.visit(node.target, self.first_intersect(node.target.type, node.value.type)) return self.visit(node.value, node.target.type) def visit_AugAssign(self, node: ast.AugAssign, _: Optional[VyperType]): self.visit(node.target, self.first_intersect(node.target.type, node.value.type)) return self.visit(node.value, node.target.type) def visit_Comparison(self, node: ast.Comparison, _: Optional[VyperType]): self.visit(node.left, self.first_intersect(node.left.type, node.right.type)) return self.visit(node.right, node.left.type) def visit_Equality(self, node: ast.Equality, _: Optional[VyperType]): self.visit(node.left, self.first_intersect(node.left.type, node.right.type)) return self.visit(node.right, node.left.type) def visit_FunctionCall(self, node: ast.FunctionCall, _: Optional[VyperType]): self.generic_visit(node, None) def visit_ReceiverCall(self, node: ast.ReceiverCall, _: Optional[VyperType]): return self.generic_visit(node, None) def visit_Set(self, node: ast.Set, _: Optional[VyperType]): return self.generic_visit(node, None) def visit_List(self, node: ast.List, _: Optional[VyperType]): return self.generic_visit(node, node.type.element_type)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/analysis/type_annotator.py
type_annotator.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 enum import Enum from itertools import chain from typing import Optional, Union from twovyper.utils import switch, first from twovyper.ast import ast_nodes as ast, names from twovyper.ast.nodes import VyperProgram, VyperFunction, VyperInterface from twovyper.ast.visitors import NodeVisitor from twovyper.exceptions import InvalidProgramException, UnsupportedException def _assert(cond: bool, node: ast.Node, error_code: str, msg: Optional[str] = None): if not cond: raise InvalidProgramException(node, error_code, msg) def check_structure(program: VyperProgram): StructureChecker().check(program) class _Context(Enum): CODE = 'code' INVARIANT = 'invariant' LOOP_INVARIANT = 'loop.invariant' CHECK = 'check' POSTCONDITION = 'postcondition' PRECONDITION = 'precondition' TRANSITIVE_POSTCONDITION = 'transitive.postcondition' CALLER_PRIVATE = 'caller.private' GHOST_CODE = 'ghost.code' GHOST_FUNCTION = 'ghost.function' LEMMA = 'lemma' GHOST_STATEMENT = 'ghost.statement' @property def is_specification(self): return self not in [_Context.CODE, _Context.GHOST_FUNCTION, _Context.LEMMA] @property def is_postcondition(self): return self in [_Context.POSTCONDITION, _Context.TRANSITIVE_POSTCONDITION] class StructureChecker(NodeVisitor): def __init__(self): self.not_allowed = { _Context.CODE: names.NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, _Context.INVARIANT: names.NOT_ALLOWED_IN_INVARIANT, _Context.LOOP_INVARIANT: names.NOT_ALLOWED_IN_LOOP_INVARIANT, _Context.CHECK: names.NOT_ALLOWED_IN_CHECK, _Context.POSTCONDITION: names.NOT_ALLOWED_IN_POSTCONDITION, _Context.PRECONDITION: names.NOT_ALLOWED_IN_PRECONDITION, _Context.TRANSITIVE_POSTCONDITION: names.NOT_ALLOWED_IN_TRANSITIVE_POSTCONDITION, _Context.CALLER_PRIVATE: names.NOT_ALLOWED_IN_CALLER_PRIVATE, _Context.GHOST_CODE: names.NOT_ALLOWED_IN_GHOST_CODE, _Context.GHOST_FUNCTION: names.NOT_ALLOWED_IN_GHOST_FUNCTION, _Context.GHOST_STATEMENT: names.NOT_ALLOWED_IN_GHOST_STATEMENT, _Context.LEMMA: names.NOT_ALLOWED_IN_LEMMAS } self._inside_old = False self._is_pure = False self._non_pure_parent_description: Union[str, None] = None self._visited_an_event = False self._visited_caller_spec = False self._num_visited_conditional = 0 self._only_one_event_allowed = False self._function_pure_checker = _FunctionPureChecker() self._inside_performs = False @contextmanager def _inside_old_scope(self): current_inside_old = self._inside_old self._inside_old = True yield self._inside_old = current_inside_old @contextmanager def _inside_performs_scope(self): current_inside_performs = self._inside_performs self._inside_performs = True yield self._inside_performs = current_inside_performs @contextmanager def _inside_pure_scope(self, node_description: str = None): is_pure = self._is_pure self._is_pure = True description = self._non_pure_parent_description self._non_pure_parent_description = node_description yield self._is_pure = is_pure self._non_pure_parent_description = description @contextmanager def _inside_one_event_scope(self): visited_an_event = self._visited_an_event self._visited_an_event = False only_one_event_allowed = self._only_one_event_allowed self._only_one_event_allowed = True yield self._visited_an_event = visited_an_event self._only_one_event_allowed = only_one_event_allowed def check(self, program: VyperProgram): if program.resources and not program.config.has_option(names.CONFIG_ALLOCATION): msg = "Resources require allocation config option." raise InvalidProgramException(first(program.node.stmts) or program.node, 'alloc.not.alloc', msg) seen_functions = set() for implements in program.real_implements: interface = program.interfaces.get(implements.name) if interface is not None: function_names = set(function.name for function in interface.functions.values()) else: contract = program.contracts[implements.name] function_names = set(contract.type.function_types) _assert(not seen_functions & function_names, program.node, 'invalid.implemented.interfaces', f'Implemented interfaces should not have a function that shares the name with another function of ' f'another implemented interface.\n' f'(Conflicting functions: {seen_functions & function_names})') seen_functions.update(function_names) for function in program.functions.values(): self.visit(function.node, _Context.CODE, program, function) if function.is_pure(): self._function_pure_checker.check_function(function, program) for postcondition in function.postconditions: self.visit(postcondition, _Context.POSTCONDITION, program, function) if function.preconditions: _assert(not function.is_public(), function.preconditions[0], 'invalid.preconditions', 'Public functions are not allowed to have preconditions.') for precondition in function.preconditions: self.visit(precondition, _Context.PRECONDITION, program, function) if function.checks: _assert(not program.is_interface(), function.checks[0], 'invalid.checks', 'No checks are allowed in interfaces.') for check in function.checks: self.visit(check, _Context.CHECK, program, function) if function.performs: _assert(function.name != names.INIT, function.performs[0], 'invalid.performs', '__init__ does not require and must not have performs clauses.') _assert(function.is_public(), function.performs[0], 'invalid.performs', 'Private functions are not allowed to have performs clauses.') for performs in function.performs: self._visit_performs(performs, program, function) for lemma in program.lemmas.values(): for default_val in lemma.defaults.values(): _assert(default_val is None, lemma.node, 'invalid.lemma') _assert(not lemma.postconditions, first(lemma.postconditions), 'invalid.lemma', 'No postconditions are allowed for lemmas.') _assert(not lemma.checks, first(lemma.checks), 'invalid.lemma', 'No checks are allowed for lemmas.') _assert(not lemma.performs, first(lemma.performs), 'invalid.lemma') self.visit(lemma.node, _Context.LEMMA, program, lemma) for stmt in lemma.node.body: _assert(isinstance(stmt, ast.ExprStmt), stmt, 'invalid.lemma', 'All steps of the lemma should be expressions') for precondition in lemma.preconditions: self.visit(precondition, _Context.LEMMA, program, lemma) for invariant in program.invariants: self.visit(invariant, _Context.INVARIANT, program, None) if program.general_checks: _assert(not program.is_interface(), program.general_checks[0], 'invalid.checks', 'No checks are allowed in interfaces.') for check in program.general_checks: self.visit(check, _Context.CHECK, program, None) for postcondition in program.general_postconditions: self.visit(postcondition, _Context.POSTCONDITION, program, None) if program.transitive_postconditions: _assert(not program.is_interface(), program.transitive_postconditions[0], 'invalid.transitive.postconditions', 'No transitive postconditions are allowed in interfaces') for postcondition in program.transitive_postconditions: self.visit(postcondition, _Context.TRANSITIVE_POSTCONDITION, program, None) for ghost_function in program.ghost_function_implementations.values(): self.visit(ghost_function.node, _Context.GHOST_FUNCTION, program, None) if isinstance(program, VyperInterface): for caller_private in program.caller_private: self._visited_caller_spec = False self._num_visited_conditional = 0 self.visit(caller_private, _Context.CALLER_PRIVATE, program, None) _assert(self._visited_caller_spec, caller_private, 'invalid.caller.private', 'A caller private expression must contain "caller()"') _assert(self._num_visited_conditional <= 1, caller_private, 'invalid.caller.private', 'A caller private expression can only contain at most one "conditional(...)"') def visit(self, node: ast.Node, *args): assert len(args) == 3 ctx, program, function = args _assert(ctx != _Context.GHOST_CODE or isinstance(node, ast.AllowedInGhostCode), node, 'invalid.ghost.code') super().visit(node, ctx, program, function) def _visit_performs(self, node: ast.Expr, program: VyperProgram, function: VyperFunction): with self._inside_performs_scope(): _assert(isinstance(node, ast.FunctionCall) and node.name in names.GHOST_STATEMENTS, node, 'invalid.performs') self.visit(node, _Context.CODE, program, function) def visit_BoolOp(self, node: ast.BoolOp, *args): with switch(node.op) as case: if case(ast.BoolOperator.OR): with self._inside_one_event_scope(): with self._inside_pure_scope('disjunctions'): self.generic_visit(node, *args) elif case(ast.BoolOperator.IMPLIES): with self._inside_pure_scope('(e ==> A) as the left hand side'): self.visit(node.left, *args) self.visit(node.right, *args) elif case(ast.BoolOperator.AND): self.generic_visit(node, *args) else: assert False def visit_Not(self, node: ast.Not, *args): with self._inside_pure_scope('not expressions'): self.generic_visit(node, *args) def visit_Containment(self, node: ast.Containment, *args): with self._inside_pure_scope(f"containment expressions like \"{node.op}\""): self.generic_visit(node, *args) def visit_Equality(self, node: ast.Equality, *args): with self._inside_pure_scope('== expressions'): self.generic_visit(node, *args) def visit_IfExpr(self, node: ast.IfExpr, *args): self.visit(node.body, *args) self.visit(node.orelse, *args) with self._inside_pure_scope('if expressions like (A1 if e else A2)'): self.visit(node.test, *args) def visit_Dict(self, node: ast.Dict, *args): with self._inside_pure_scope('dicts'): self.generic_visit(node, *args) def visit_List(self, node: ast.List, *args): with self._inside_pure_scope('lists'): self.generic_visit(node, *args) def visit_Tuple(self, node: ast.Tuple, *args): with self._inside_pure_scope('tuples'): self.generic_visit(node, *args) def visit_For(self, node: ast.For, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): self.generic_visit(node, ctx, program, function) if function: for loop_inv in function.loop_invariants.get(node, []): self.visit(loop_inv, _Context.LOOP_INVARIANT, program, function) def visit_FunctionDef(self, node: ast.FunctionDef, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): for stmt in node.body: if ctx == _Context.GHOST_FUNCTION or ctx == _Context.LEMMA: new_ctx = ctx elif ctx == _Context.CODE: new_ctx = _Context.GHOST_CODE if stmt.is_ghost_code else ctx else: assert False self.visit(stmt, new_ctx, program, function) @staticmethod def visit_Name(node: ast.Name, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): assert program if ctx == _Context.GHOST_FUNCTION and node.id in names.ENV_VARIABLES: _assert(False, node, 'invalid.ghost.function') elif ctx == _Context.CALLER_PRIVATE and node.id in names.ENV_VARIABLES: _assert(False, node, 'invalid.caller.private') elif ctx == _Context.INVARIANT: _assert(node.id != names.MSG, node, 'invariant.msg') _assert(node.id != names.BLOCK, node, 'invariant.block') elif ctx == _Context.TRANSITIVE_POSTCONDITION: _assert(node.id != names.MSG, node, 'postcondition.msg') elif ctx == _Context.LEMMA: _assert(function.node.is_lemma, node, 'invalid.lemma') _assert(node.id != names.SELF, node, 'invalid.lemma', 'Self cannot be used in lemmas') _assert(node.id != names.MSG, node, 'invalid.lemma', 'Msg cannot be used in lemmas') _assert(node.id != names.BLOCK, node, 'invalid.lemma', 'Block cannot be used in lemmas') _assert(node.id != names.TX, node, 'invalid.lemma', 'Tx cannot be used in lemmas') def visit_FunctionCall(self, node: ast.FunctionCall, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): _assert(node.name not in self.not_allowed[ctx], node, f'{ctx.value}.call') if ctx == _Context.POSTCONDITION and function and function.name == names.INIT: _assert(node.name != names.OLD, node, 'postcondition.init.old') if node.name == names.PUBLIC_OLD: if ctx == _Context.POSTCONDITION: _assert(function and function.is_private(), node, 'postcondition.public.old') elif ctx == _Context.PRECONDITION: _assert(function and function.is_private(), node, 'precondition.public.old') if function and node.name == names.EVENT: if ctx == _Context.POSTCONDITION: _assert(function.is_private(), node, 'postcondition.event') elif ctx == _Context.PRECONDITION: _assert(function.is_private(), node, 'precondition.event') if node.name in program.ghost_functions: _assert(ctx != _Context.LEMMA, node, 'invalid.lemma') if len(program.ghost_functions[node.name]) > 1: if isinstance(program, VyperInterface): cond = node.name in program.own_ghost_functions else: cond = node.name in program.ghost_function_implementations _assert(cond, node, 'duplicate.ghost', f'Multiple interfaces declare the ghost function "{node.name}".') if node.name == names.CALLER: self._visited_caller_spec = True elif node.name == names.CONDITIONAL: self._num_visited_conditional += 1 if node.name == names.LOCKED: _assert(not isinstance(program, VyperInterface), node, 'invalid.locked', 'Locked cannot be used in an interface.') if node.name == names.SENT or node.name == names.RECEIVED: _assert(not program.is_interface(), node, f'invalid.{node.name}', f'"{node.name}" cannot be used in interfaces') elif node.name == names.EVENT: if ctx == _Context.PRECONDITION \ or ctx == _Context.POSTCONDITION \ or ctx == _Context.LOOP_INVARIANT: _assert(not self._is_pure, node, 'spec.event', "Events are only in checks pure expressions. " f"They cannot be used in {self._non_pure_parent_description}.") if self._only_one_event_allowed: _assert(not self._visited_an_event, node, 'spec.event', 'In this context only one event expression is allowed.') self._visited_an_event = True elif node.name == names.IMPLIES: with self._inside_pure_scope('implies(e, A) as the expression "e"'): self.visit(node.args[0], ctx, program, function) self.visit(node.args[1], ctx, program, function) # Success is of the form success() or success(if_not=cond1 or cond2 or ...) elif node.name == names.SUCCESS: def check_success_args(arg: ast.Node): if isinstance(arg, ast.Name): _assert(arg.id in names.SUCCESS_CONDITIONS, arg, 'spec.success') elif isinstance(arg, ast.BoolOp) and arg.op == ast.BoolOperator.OR: check_success_args(arg.left) check_success_args(arg.right) else: raise InvalidProgramException(arg, 'spec.success') _assert(len(node.keywords) <= 1, node, 'spec.success') if node.keywords: _assert(node.keywords[0].name == names.SUCCESS_IF_NOT, node, 'spec.success') check_success_args(node.keywords[0].value) if len(node.keywords) == 0 and len(node.args) == 1: argument = node.args[0] _assert(isinstance(argument, ast.ReceiverCall), node, 'spec.success') assert isinstance(argument, ast.ReceiverCall) func = program.functions.get(argument.name) _assert(func is not None, argument, 'spec.success', 'Only functions defined in this contract can be called from the specification.') _assert(func.is_pure(), argument, 'spec.success', 'Only pure functions can be called from the specification.') self.generic_visit(argument, ctx, program, function) elif (ctx == _Context.INVARIANT or ctx == _Context.TRANSITIVE_POSTCONDITION or ctx == _Context.LOOP_INVARIANT or ctx == _Context.GHOST_CODE or ctx == _Context.GHOST_FUNCTION): _assert(False, node, f'{ctx.value}.call') return # Accessible is of the form accessible(to, amount, self.some_func(args...)) elif node.name == names.ACCESSIBLE: _assert(not program.is_interface(), node, 'invalid.accessible', 'Accessible cannot be used in interfaces') _assert(not self._inside_old, node, 'spec.old.accessible') _assert(len(node.args) == 2 or len(node.args) == 3, node, 'spec.accessible') self.visit(node.args[0], ctx, program, function) self.visit(node.args[1], ctx, program, function) if len(node.args) == 3: call = node.args[2] _assert(isinstance(call, ast.ReceiverCall), node, 'spec.accessible') assert isinstance(call, ast.ReceiverCall) _assert(isinstance(call.receiver, ast.Name), node, 'spec.accessible') assert isinstance(call.receiver, ast.Name) _assert(call.receiver.id == names.SELF, node, 'spec.accessible') _assert(call.name in program.functions, node, 'spec.accessible') _assert(program.functions[call.name].is_public(), node, 'spec.accessible', "Only public functions may be used in an accessible expression") _assert(call.name != names.INIT, node, 'spec.accessible') self.generic_visit(call, ctx, program, function) return elif node.name in [names.FORALL, names.FOREACH]: _assert(len(node.args) >= 2 and not node.keywords, node, 'invalid.no.args') first_arg = node.args[0] _assert(isinstance(first_arg, ast.Dict), node.args[0], f'invalid.{node.name}') assert isinstance(first_arg, ast.Dict) for name in first_arg.keys: _assert(isinstance(name, ast.Name), name, f'invalid.{node.name}') for trigger in node.args[1:len(node.args) - 1]: _assert(isinstance(trigger, ast.Set), trigger, f'invalid.{node.name}') self.visit(trigger, ctx, program, function) body = node.args[-1] if node.name == names.FOREACH: _assert(isinstance(body, ast.FunctionCall), body, 'invalid.foreach') assert isinstance(body, ast.FunctionCall) _assert(body.name in names.QUANTIFIED_GHOST_STATEMENTS, body, 'invalid.foreach') self.visit(body, ctx, program, function) return elif node.name in [names.OLD, names.PUBLIC_OLD]: with self._inside_old_scope(): self.generic_visit(node, ctx, program, function) return elif node.name in [names.RESOURCE_PAYABLE, names.RESOURCE_PAYOUT]: _assert(self._inside_performs, node, f'invalid.{node.name}', f'{node.name} is only allowed in perform clauses.') elif node.name == names.RESULT or node.name == names.REVERT: if len(node.args) == 1: argument = node.args[0] _assert(isinstance(argument, ast.ReceiverCall), node, f"spec.{node.name}") assert isinstance(argument, ast.ReceiverCall) func = program.functions.get(argument.name) _assert(func is not None, argument, f"spec.{node.name}", 'Only functions defined in this contract can be called from the specification.') _assert(func.is_pure(), argument, f"spec.{node.name}", 'Only pure functions can be called from the specification.') self.generic_visit(argument, ctx, program, function) if node.keywords: self.visit_nodes([kv.value for kv in node.keywords], ctx, program, function) if node.name == names.RESULT: _assert(func.type.return_type is not None, argument, f"spec.{node.name}", 'Only functions with a return type can be used in a result-expression.') return elif (ctx == _Context.CHECK or ctx == _Context.INVARIANT or ctx == _Context.TRANSITIVE_POSTCONDITION or ctx == _Context.LOOP_INVARIANT or ctx == _Context.GHOST_CODE or ctx == _Context.GHOST_FUNCTION): _assert(False, node, f'{ctx.value}.call') elif node.name == names.INDEPENDENT: with self._inside_pure_scope('independent expressions'): self.visit(node.args[0], ctx, program, function) def check_allowed(arg): if isinstance(arg, ast.FunctionCall): is_old = len(arg.args) == 1 and arg.name in [names.OLD, names.PUBLIC_OLD] _assert(is_old, node, 'spec.independent') return check_allowed(arg.args[0]) if isinstance(arg, ast.Attribute): return check_allowed(arg.value) elif isinstance(arg, ast.Name): allowed = [names.SELF, names.BLOCK, names.CHAIN, names.TX, *function.args] _assert(arg.id in allowed, node, 'spec.independent') else: _assert(False, node, 'spec.independent') check_allowed(node.args[1]) elif node.name == names.RAW_CALL: if names.RAW_CALL_DELEGATE_CALL in (kw.name for kw in node.keywords): raise UnsupportedException(node, "Delegate calls are not supported.") elif node.name == names.PREVIOUS or node.name == names.LOOP_ARRAY or node.name == names.LOOP_ITERATION: if len(node.args) > 0: _assert(isinstance(node.args[0], ast.Name), node.args[0], f"invalid.{node.name}") elif node.name == names.RANGE: if len(node.args) == 1: _assert(isinstance(node.args[0], ast.Num), node.args[0], 'invalid.range', 'The range operator should be of the form: range(const). ' '"const" must be a constant integer expression.') elif len(node.args) == 2: first_arg = node.args[0] second_arg = node.args[1] msg = 'The range operator should be of the form: range(const1, const2) or range(x, x + const1). '\ '"const1" and "const2" must be constant integer expressions.' if isinstance(second_arg, ast.ArithmeticOp) \ and second_arg.op == ast.ArithmeticOperator.ADD \ and ast.compare_nodes(first_arg, second_arg.left): _assert(isinstance(second_arg.right, ast.Num), second_arg.right, 'invalid.range', msg) else: _assert(isinstance(first_arg, ast.Num), first_arg, 'invalid.range', msg) _assert(isinstance(second_arg, ast.Num), second_arg, 'invalid.range', msg) assert isinstance(first_arg, ast.Num) and isinstance(second_arg, ast.Num) _assert(first_arg.n < second_arg.n, node, 'invalid.range', 'The range operator should be of the form: range(const1, const2). ' '"const2" must be greater than "const1".') if node.name in names.ALLOCATION_FUNCTIONS: msg = "Allocation statements require allocation config option." _assert(program.config.has_option(names.CONFIG_ALLOCATION), node, 'alloc.not.alloc', msg) if isinstance(program, VyperInterface): _assert(not program.config.has_option(names.CONFIG_NO_PERFORMS), node, 'alloc.not.alloc') if self._inside_performs: _assert(node.name not in names.ALLOCATION_SPECIFICATION_FUNCTIONS, node, 'alloc.in.alloc', 'Allocation functions are not allowed in arguments of other allocation ' 'functions in a performs clause') if node.name in names.GHOST_STATEMENTS: msg = "Allocation statements are not allowed in constant functions." _assert(not (function and function.is_constant()), node, 'alloc.in.constant', msg) arg_ctx = _Context.GHOST_STATEMENT if node.name in names.GHOST_STATEMENTS and not self._inside_performs else ctx if node.name == names.TRUST and node.keywords: _assert(not (function and function.name != names.INIT), node, 'invalid.trusted', f'Only the "{names.INIT}" function is allowed to have trust calls with keywords.') if node.resource: # Resources are only allowed in allocation functions. They can have the following structure: # - a simple name: r # - an exchange: r <-> s # - a creator: creator(r) _assert(node.name in names.ALLOCATION_FUNCTIONS, node, 'invalid.no.resources') # All allocation functions are allowed to have a resource with an address if the function is inside of a # performs clause. Outside of performs clauses ghost statements are not allowed to have resources with # addresses (They can only refer to their own resources). resources_with_address_allowed = self._inside_performs or node.name not in names.GHOST_STATEMENTS def check_resource_address(address): _assert(resources_with_address_allowed, address, 'invalid.resource.address') self.generic_visit(address, ctx, program, function) if isinstance(address, ast.Name): _assert(address.id == names.SELF, address, 'invalid.resource.address') elif isinstance(address, ast.Attribute): _assert(isinstance(address.value, ast.Name), address, 'invalid.resource.address') assert isinstance(address.value, ast.Name) _assert(address.value.id == names.SELF, address, 'invalid.resource.address') elif isinstance(address, ast.FunctionCall): if address.name in program.ghost_functions: f = program.ghost_functions.get(address.name) _assert(f is None or len(f) == 1, address, 'invalid.resource.address', 'The ghost function is not unique.') _assert(f is not None, address, 'invalid.resource.address') _assert(len(address.args) >= 1, address, 'invalid.resource.address') else: _assert(program.config.has_option(names.CONFIG_TRUST_CASTS), address, 'invalid.resource.address', 'Using casted addresses as resource address is only allowed' 'when the "trust_casts" config is set.') _assert(address.name in program.interfaces, address, 'invalid.resource.address') elif isinstance(address, ast.ReceiverCall): _assert(address.name in program.ghost_functions, address, 'invalid.resource.address') _assert(isinstance(address.receiver, ast.Name), address, 'invalid.resource.address') assert isinstance(address.receiver, ast.Name) f = program.interfaces[address.receiver.id].own_ghost_functions.get(address.name) _assert(f is not None, address, 'invalid.resource.address') _assert(len(address.args) >= 1, address, 'invalid.resource.address') else: _assert(False, address, 'invalid.resource.address') def check_resource(resource: ast.Node, top: bool, inside_subscript: bool = False): if isinstance(resource, ast.Name): return elif isinstance(resource, ast.Exchange) and top and not inside_subscript: check_resource(resource.left, False, inside_subscript) check_resource(resource.right, False, inside_subscript) elif isinstance(resource, ast.FunctionCall) and not inside_subscript: if resource.name == names.CREATOR: _assert(len(resource.args) == 1 and not resource.keywords, resource, 'invalid.resource') check_resource(resource.args[0], False, inside_subscript) else: if resource.resource is not None: check_resource_address(resource.resource) self.generic_visit(resource, arg_ctx, program, function) elif isinstance(resource, ast.Attribute): _assert(isinstance(resource.value, ast.Name), resource, 'invalid.resource') assert isinstance(resource.value, ast.Name) interface_name = resource.value.id interface = program.interfaces.get(interface_name) _assert(interface is not None, resource, 'invalid.resource') _assert(resource.attr in interface.own_resources, resource, 'invalid.resource') elif isinstance(resource, ast.ReceiverCall) and not inside_subscript: if isinstance(resource.receiver, ast.Name): interface_name = resource.receiver.id elif isinstance(resource.receiver, ast.Subscript): _assert(isinstance(resource.receiver.value, ast.Attribute), resource, 'invalid.resource') assert isinstance(resource.receiver.value, ast.Attribute) _assert(isinstance(resource.receiver.value.value, ast.Name), resource, 'invalid.resource') assert isinstance(resource.receiver.value.value, ast.Name) interface_name = resource.receiver.value.value.id address = resource.receiver.index check_resource_address(address) else: _assert(False, resource, 'invalid.resource') return interface = program.interfaces.get(interface_name) _assert(interface is not None, resource, 'invalid.resource') _assert(resource.name in interface.own_resources, resource, 'invalid.resource') self.generic_visit(resource, arg_ctx, program, function) elif isinstance(resource, ast.Subscript): address = resource.index check_resource(resource.value, False, True) check_resource_address(address) else: _assert(False, resource, 'invalid.resource') check_resource(node.resource, True) self.visit_nodes(chain(node.args, node.keywords), arg_ctx, program, function) def visit_ReceiverCall(self, node: ast.ReceiverCall, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): if ctx == _Context.CALLER_PRIVATE: _assert(False, node, 'spec.call') elif ctx.is_specification or self._inside_performs: receiver = node.receiver if isinstance(receiver, ast.Name): if receiver.id == names.LEMMA: other_lemma = program.lemmas.get(node.name) _assert(other_lemma is not None, node, 'invalid.lemma', f'Unknown lemma to call: {node.name}') elif receiver.id in program.interfaces: interface = program.interfaces[receiver.id] _assert(node.name in interface.own_ghost_functions, node, 'spec.call', f'Unknown ghost function to call "{node.name}" in the interface "{receiver.id}"') else: _assert(False, node, 'spec.call') elif ctx == _Context.GHOST_CODE: _assert(False, node, 'invalid.ghost.code') else: _assert(False, node, 'spec.call') elif ctx == _Context.GHOST_FUNCTION: _assert(False, node, 'invalid.ghost') elif ctx == _Context.LEMMA: receiver = node.receiver _assert(isinstance(receiver, ast.Name), node, 'invalid.lemma', 'Only calls to other lemmas are allowed in lemmas.') assert isinstance(receiver, ast.Name) _assert(receiver.id == names.LEMMA, node, 'invalid.lemma' 'Only calls to other lemmas are allowed in lemmas.') other_lemma = program.lemmas.get(node.name) _assert(other_lemma is not None, node, 'invalid.lemma', f'Unknown lemma to call: {node.name}') _assert(other_lemma.index < function.index, node, 'invalid.lemma', 'Can only use lemmas previously defined (No recursion is allowed).') self.generic_visit(node, ctx, program, function) def visit_Exchange(self, node: ast.Exchange, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): _assert(False, node, 'exchange.not.resource') self.generic_visit(node, ctx, program, function) @staticmethod def _visit_assertion(node: Union[ast.Assert, ast.Raise], ctx: _Context): if ctx == _Context.GHOST_CODE: if isinstance(node, ast.Assert) and node.is_lemma: return _assert(node.msg and isinstance(node.msg, ast.Name), node, 'invalid.ghost.code') assert isinstance(node.msg, ast.Name) _assert(node.msg.id == names.UNREACHABLE, node, 'invalid.ghost.code') def visit_Assert(self, node: ast.Assert, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): self._visit_assertion(node, ctx) self.generic_visit(node, ctx, program, function) def visit_Raise(self, node: ast.Raise, ctx: _Context, program: VyperProgram, function: Optional[VyperFunction]): self._visit_assertion(node, ctx) self.generic_visit(node, ctx, program, function) class _FunctionPureChecker(NodeVisitor): """ Checks if a given VyperFunction is pure """ def __init__(self): super().__init__() self._ghost_allowed = False self.max_allowed_function_index = -1 @contextmanager def _ghost_code_allowed(self): ghost_allowed = self._ghost_allowed self._ghost_allowed = True yield self._ghost_allowed = ghost_allowed def check_function(self, function: VyperFunction, program: VyperProgram): # A function must be constant, private and non-payable to be valid ghost_pure_cond = not (function.is_constant() and function.is_private() and (not function.is_payable())) pure_decorators = [decorator for decorator in function.decorators if decorator.name == names.PURE] if len(pure_decorators) > 1: _assert(False, pure_decorators[0], 'invalid.pure', 'A pure function can only have exactly one pure decorator') elif pure_decorators[0].is_ghost_code and ghost_pure_cond: _assert(False, function.node, 'invalid.pure', 'A pure function must be constant, private and non-payable') else: self.max_allowed_function_index = function.index - 1 # Check checks if function.checks: _assert(False, function.checks[0], 'invalid.pure', 'A pure function must not have checks') # Check performs if function.performs: _assert(False, function.performs[0], 'invalid.pure', 'A pure function must not have performs') # Check preconditions if function.preconditions: _assert(False, function.preconditions[0], 'invalid.pure', 'A pure function must not have preconditions') # Check postconditions if function.postconditions: _assert(False, function.postconditions[0], 'invalid.pure', 'A pure function must not have postconditions') # Check loop invariants with self._ghost_code_allowed(): for loop_invariants in function.loop_invariants.values(): self.visit_nodes(loop_invariants, program) # Check Code self.visit_nodes(function.node.body, program) def visit(self, node, *args): _assert(self._ghost_allowed or not node.is_ghost_code, node, 'invalid.pure', 'A pure function must not have ghost code statements') return super().visit(node, *args) def visit_Name(self, node: ast.Name, program: VyperProgram): with switch(node.id) as case: if case(names.MSG) \ or case(names.BLOCK) \ or case(names.TX): _assert(False, node, 'invalid.pure', 'Pure functions are not allowed to use "msg", "block" or "tx".') self.generic_visit(node, program) def visit_ExprStmt(self, node: ast.ExprStmt, program: VyperProgram): if isinstance(node.value, ast.FunctionCall) and node.value.name == names.CLEAR: # A call to clear is an assignment self.generic_visit(node, program) elif isinstance(node.value, ast.Str): # long string comment pass else: # all other expressions are not valid. _assert(False, node, 'invalid.pure', 'Pure functions are not allowed to have just an expression as a ' 'statement, since expressions must not have side effects.') def visit_FunctionCall(self, node: ast.FunctionCall, program: VyperProgram): with switch(node.name) as case: if ( # Vyper functions with side effects case(names.RAW_LOG) # Specification functions with side effects or case(names.ACCESSIBLE) or case(names.EVENT) or case(names.INDEPENDENT) or case(names.REORDER_INDEPENDENT) ): _assert(False, node, 'invalid.pure', f'Only functions without side effects may be used in pure functions ("{node.name}" is invalid)') elif ( # Not supported specification functions case(names.ALLOCATED) or case(names.FAILED) or case(names.IMPLEMENTS) or case(names.ISSUED) or case(names.LOCKED) or case(names.OFFERED) or case(names.OUT_OF_GAS) or case(names.OVERFLOW) or case(names.PUBLIC_OLD) or case(names.RECEIVED) or case(names.SENT) or case(names.STORAGE) or case(names.TRUSTED) ): _assert(False, node, 'invalid.pure', f'This function may not be used in pure functions ("{node.name}" is invalid)') elif case(names.SUCCESS): _assert(len(node.keywords) == 0, node, 'invalid.pure', f'Only success without keywords may be used in pure functions') self.generic_visit(node, program) def visit_ReceiverCall(self, node: ast.ReceiverCall, program: VyperProgram): if not isinstance(node.receiver, ast.Name): _assert(False, node, 'invalid.receiver') with switch(node.receiver.id) as case: if case(names.SELF): self.generic_visit(node, program) _assert(program.functions[node.name].is_pure(), node, 'invalid.pure', 'Pure function may only call other pure functions') _assert(program.functions[node.name].index <= self.max_allowed_function_index, node, 'invalid.pure', 'Only functions defined above this function can be called from here') elif case(names.LOG): _assert(False, node, 'invalid.pure', 'Pure function may not log events.') else: _assert(False, node, 'invalid.pure', 'Pure function must not call functions of another contract.') def visit_Log(self, node: ast.Log, program: VyperProgram): raise UnsupportedException(node, 'Pure functions that log events are not supported.')
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/analysis/structure_checker.py
structure_checker.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.nodes import VyperProgram, VyperFunction from twovyper.ast.visitors import NodeVisitor from twovyper.utils import first def compute(program: VyperProgram): _AccessibleHeuristics().compute(program) class _AccessibleHeuristics(NodeVisitor): def compute(self, program: VyperProgram): send_functions = [] for function in program.functions.values(): self.visit(function.node, function, send_functions) def is_canditate(f: VyperFunction) -> bool: if not f.is_public(): return False elif len(f.args) == 1: return first(f.args.values()).type == types.VYPER_WEI_VALUE else: return not f.args def val(f: VyperFunction): name = f.name.lower() if name == names.WITHDRAW: return 0 elif names.WITHDRAW in name: return 1 else: return 3 candidates = sorted((f for f in send_functions if is_canditate(f)), key=val) program.analysis.accessible_function = first(candidates) def visit_FunctionCall(self, node: ast.FunctionCall, function: VyperFunction, send_functions: List[VyperFunction]): is_send = node.name == names.SEND is_rawcall = node.name == names.RAW_CALL is_raw_send = names.RAW_CALL_VALUE in [kw.name for kw in node.keywords] if is_send or (is_rawcall and is_raw_send): send_functions.append(function) self.generic_visit(node, function, send_functions)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/analysis/heuristics.py
heuristics.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/analysis/__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 contextlib import contextmanager from typing import Set, Dict, List from twovyper.ast import ast_nodes as ast, names from twovyper.ast.nodes import VyperProgram, VyperInterface, VyperFunction from twovyper.ast.visitors import NodeVisitor from twovyper.analysis import heuristics from twovyper.analysis.structure_checker import check_structure from twovyper.analysis.symbol_checker import check_symbols from twovyper.analysis.type_annotator import TypeAnnotator from twovyper.exceptions import UnsupportedException from twovyper.utils import switch def analyze(program: VyperProgram): """ Checks the program for structural errors, adds type information to all program expressions and creates an analysis for each function. """ if isinstance(program, VyperInterface) and program.is_stub: return check_symbols(program) check_structure(program) TypeAnnotator(program).annotate_program() function_analyzer = _FunctionAnalyzer() program_analyzer = _ProgramAnalyzer() invariant_analyzer = _InvariantAnalyzer() program.analysis = ProgramAnalysis() for function in program.functions.values(): function.analysis = FunctionAnalysis() function_analyzer.analyze(program, function) # The heuristics are need for analysis, therefore do them first heuristics.compute(program) program_analyzer.analyze(program) invariant_analyzer.analyze(program) class ProgramAnalysis: def __init__(self): # True if and only if issued state is accessed in top-level specifications self.uses_issued = False # The function that is used to prove accessibility if none is given # Is set in the heuristics computation # May be 'None' if the heuristics is not able to determine a suitable function self.accessible_function = None # The invariant a tag belongs to # Each invariant has a tag that is used in accessible so we know which invariant fails # if we cannot prove the accessibility self.inv_tags = {} # Maps accessible ast.ReceiverCall nodes to their tag self.accessible_tags = {} # All invariants that contain allocated self.allocated_invariants = [] class FunctionAnalysis: def __init__(self): # True if and only if issued state is accessed in top-level or function specifications self.uses_issued = False # The set of tags for which accessibility needs to be proven in the function self.accessible_tags = set() # The set of variable names which get changed by a loop self.loop_used_names: Dict[str, List[str]] = {} # True if and only if "assert e, UNREACHABLE" or "raise UNREACHABLE" is used self.uses_unreachable = False class _ProgramAnalyzer(NodeVisitor): def __init__(self): super().__init__() def analyze(self, program: VyperProgram): self.visit_nodes(program.invariants, program) self.visit_nodes(program.general_postconditions, program) self.visit_nodes(program.transitive_postconditions, program) self.visit_nodes(program.general_checks, program) def visit_FunctionCall(self, node: ast.FunctionCall, program: VyperProgram): if node.name == names.ISSUED: program.analysis.uses_issued = True for function in program.functions.values(): function.analysis.uses_issued = True self.generic_visit(node, program) class _InvariantAnalyzer(NodeVisitor): def analyze(self, program: VyperProgram): for tag, inv in enumerate(program.invariants): program.analysis.inv_tags[tag] = inv self.visit(inv, program, inv, tag) def visit_FunctionCall(self, node: ast.FunctionCall, program: VyperProgram, inv: ast.Expr, tag: int): if node.name == names.ALLOCATED: program.analysis.allocated_invariants.append(inv) return elif node.name == names.ACCESSIBLE: program.analysis.accessible_tags[node] = tag if len(node.args) == 3: func_arg = node.args[2] assert isinstance(func_arg, ast.ReceiverCall) function_name = func_arg.name else: if not program.analysis.accessible_function: msg = "No matching function for accessible could be determined." raise UnsupportedException(node, msg) function_name = program.analysis.accessible_function.name program.functions[function_name].analysis.accessible_tags.add(tag) self.generic_visit(node, program, inv, tag) class _FunctionAnalyzer(NodeVisitor): def __init__(self): super().__init__() self.inside_loop = False self.inside_spec = False self.used_names: Set[str] = set() @contextmanager def _loop_scope(self): used_variables = self.used_names inside_loop = self.inside_loop self.used_names = set() self.inside_loop = True yield if inside_loop: for name in used_variables: self.used_names.add(name) else: self.used_names = used_variables self.inside_loop = inside_loop @contextmanager def _spec_scope(self): inside_spec = self.inside_spec self.inside_spec = True yield self.inside_spec = inside_spec def analyze(self, program: VyperProgram, function: VyperFunction): with self._spec_scope(): self.visit_nodes(function.postconditions, program, function) self.visit_nodes(function.preconditions, program, function) self.visit_nodes(function.checks, program, function) self.generic_visit(function.node, program, function) def visit_Assert(self, node: ast.Assert, program: VyperProgram, function: VyperFunction): if isinstance(node.msg, ast.Name) and node.msg.id == names.UNREACHABLE: function.analysis.uses_unreachable = True self.generic_visit(node, program, function) def visit_FunctionCall(self, node: ast.FunctionCall, program: VyperProgram, function: VyperFunction): if node.name == names.ISSUED: function.analysis.uses_issued = True self.generic_visit(node, program, function) def visit_For(self, node: ast.For, program: VyperProgram, function: VyperFunction): with self._loop_scope(): self.generic_visit(node, program, function) function.analysis.loop_used_names[node.target.id] = list(self.used_names) with self._spec_scope(): self.visit_nodes(function.loop_invariants.get(node, []), program, function) def visit_Name(self, node: ast.Name, program: VyperProgram, function: VyperFunction): if self.inside_loop: with switch(node.id) as case: if case(names.MSG)\ or case(names.BLOCK)\ or case(names.CHAIN)\ or case(names.TX): pass else: self.used_names.add(node.id) self.generic_visit(node, program, function) def visit_Raise(self, node: ast.Raise, program: VyperProgram, function: VyperFunction): if isinstance(node.msg, ast.Name) and node.msg.id == names.UNREACHABLE: function.analysis.uses_unreachable = True self.generic_visit(node, program, function)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/analysis/analyzer.py
analyzer.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.utils import Subscriptable def sign(a: int) -> int: if a > 0: return 1 elif a < 0: return -1 else: return 0 def div(a: int, b: int) -> int: """ Truncating division of two integers. """ return sign(a) * sign(b) * (abs(a) // abs(b)) def mod(a: int, b: int) -> int: """ Truncating modulo of two integers. """ return sign(a) * (abs(a) % abs(b)) class Decimal(object, metaclass=Subscriptable): def __init__(self): assert False _cache = {} def _subscript(number_of_digits: int): # This is the function that gets called when using dictionary lookup syntax. # For example, Decimal[10] returns a class of decimals with 10 digits. The class # is cached so that Decimal[10] always returns the same class, which means that # type(Decimal[10](1)) == type(Decimal[10](2)). cached_class = Decimal._cache.get(number_of_digits) if cached_class: return cached_class class _Decimal(Decimal): def __init__(self, value: int = None, scaled_value: int = None): assert (value is None) != (scaled_value is None) self.number_of_digits = number_of_digits self.scaling_factor = 10 ** number_of_digits self.scaled_value = scaled_value if value is None else value * self.scaling_factor def __eq__(self, other): if isinstance(other, _Decimal): return self.scaled_value == other.scaled_value else: return False def __hash__(self): return hash(self.scaled_value) def __str__(self): dv = div(self.scaled_value, self.scaling_factor) md = mod(self.scaled_value, self.scaling_factor) return f'{dv}.{str(md).zfill(self.number_of_digits)}' Decimal._cache[number_of_digits] = _Decimal return _Decimal
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/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/. """ import os from typing import Optional, List, Dict from twovyper.ast import ast_nodes as ast, names from twovyper.ast.visitors import NodeVisitor from twovyper.exceptions import InvalidProgramException class VyperType: def __init__(self, id: str): self.id = id def __str__(self) -> str: return self.id def __eq__(self, other) -> bool: if isinstance(other, VyperType): return self.id == other.id return NotImplemented def __hash__(self) -> int: return hash(self.id) class FunctionType(VyperType): def __init__(self, arg_types: List[VyperType], return_type: Optional[VyperType]): self.arg_types = arg_types self.return_type = return_type arg_type_names = [str(arg) for arg in arg_types] id = f'({", ".join(arg_type_names)}) -> {return_type}' super().__init__(id) class MapType(VyperType): def __init__(self, key_type: VyperType, value_type: VyperType): self.key_type = key_type self.value_type = value_type id = f'{names.MAP}({key_type}, {value_type})' super().__init__(id) class ArrayType(VyperType): def __init__(self, element_type: VyperType, size: int, is_strict: bool = True): self.element_type = element_type self.size = size self.is_strict = is_strict id = f'{element_type}[{"" if is_strict else "<="}{size}]' super().__init__(id) class TupleType(VyperType): def __init__(self, element_types: List[VyperType]): self.element_types = element_types id = f'({element_types})' super().__init__(id) class StructType(VyperType): def __init__(self, name: str, member_types: Dict[str, VyperType]): id = f'{self.kind} {name}' super().__init__(id) self.name = name self.member_types = member_types self.member_indices = {k: i for i, k in enumerate(member_types)} @property def kind(self) -> str: return 'struct' def add_member(self, name: str, type: VyperType): self.member_types[name] = type self.member_indices[name] = len(self.member_indices) class AnyStructType(VyperType): def __init__(self): super().__init__('$AnyStruct') class AnyAddressType(StructType): def __init__(self, name: str, member_types: Dict[str, VyperType]): assert names.ADDRESS_BALANCE not in member_types assert names.ADDRESS_CODESIZE not in member_types assert names.ADDRESS_IS_CONTRACT not in member_types member_types[names.ADDRESS_BALANCE] = VYPER_WEI_VALUE member_types[names.ADDRESS_CODESIZE] = VYPER_INT128 member_types[names.ADDRESS_IS_CONTRACT] = VYPER_BOOL super().__init__(name, member_types) class AddressType(AnyAddressType): def __init__(self): super().__init__(names.ADDRESS, {}) class SelfType(AnyAddressType): def __init__(self, member_types: Dict[str, VyperType]): super().__init__(names.SELF, member_types) class ResourceType(StructType): @property def kind(self) -> str: return 'resource' class UnknownResourceType(ResourceType): def __init__(self): super().__init__('$unknown', {}) class DerivedResourceType(ResourceType): def __init__(self, name: str, member_types: Dict[str, VyperType], underlying_resource: ResourceType): super().__init__(name, member_types) self.underlying_resource = underlying_resource class ContractType(VyperType): def __init__(self, name: str, function_types: Dict[str, FunctionType], function_modifiers: Dict[str, str]): id = f'contract {name}' super().__init__(id) self.name = name self.function_types = function_types self.function_modifiers = function_modifiers class InterfaceType(VyperType): def __init__(self, name: str): id = f'interface {name}' super().__init__(id) self.name = name class StringType(ArrayType): def __init__(self, size: int): super().__init__(VYPER_BYTE, size, False) self.id = f'{names.STRING}[{size}]' class PrimitiveType(VyperType): def __init__(self, name: str): super().__init__(name) self.name = name class BoundedType(PrimitiveType): def __init__(self, name: str, lower: int, upper: int): super().__init__(name) self.lower = lower self.upper = upper class DecimalType(BoundedType): def __init__(self, name: str, digits: int, lower: int, upper: int): self.number_of_digits = digits self.scaling_factor = 10 ** digits lower *= self.scaling_factor upper *= self.scaling_factor super().__init__(name, lower, upper) class EventType(VyperType): def __init__(self, arg_types: List[VyperType]): arg_type_names = [str(arg) for arg in arg_types] id = f'event({", ".join(arg_type_names)})' super().__init__(id) self.arg_types = arg_types VYPER_BOOL = PrimitiveType(names.BOOL) VYPER_INT128 = BoundedType(names.INT128, -2 ** 127, 2 ** 127 - 1) VYPER_UINT256 = BoundedType(names.UINT256, 0, 2 ** 256 - 1) VYPER_DECIMAL = DecimalType(names.DECIMAL, 10, -2 ** 127, 2 ** 127 - 1) VYPER_WEI_VALUE = VYPER_UINT256 VYPER_ADDRESS = BoundedType(names.ADDRESS, 0, 2 ** 160 - 1) VYPER_BYTE = PrimitiveType(names.BYTE) VYPER_BYTES32 = ArrayType(VYPER_BYTE, 32, True) NON_NEGATIVE_INT = PrimitiveType(names.NON_NEGATIVE_INTEGER) TYPES = { VYPER_BOOL.name: VYPER_BOOL, VYPER_WEI_VALUE.name: VYPER_WEI_VALUE, VYPER_INT128.name: VYPER_INT128, VYPER_UINT256.name: VYPER_UINT256, VYPER_DECIMAL.name: VYPER_DECIMAL, names.WEI_VALUE: VYPER_WEI_VALUE, VYPER_ADDRESS.name: VYPER_ADDRESS, VYPER_BYTE.name: VYPER_BYTE, names.BYTES32: VYPER_BYTES32, names.STRING: VYPER_BYTE, names.TIMESTAMP: VYPER_UINT256, names.TIMEDELTA: VYPER_UINT256 } MSG_TYPE = StructType(names.MSG, { names.MSG_SENDER: VYPER_ADDRESS, names.MSG_VALUE: VYPER_WEI_VALUE, names.MSG_GAS: VYPER_UINT256 }) BLOCK_TYPE = StructType(names.BLOCK, { names.BLOCK_COINBASE: VYPER_ADDRESS, names.BLOCK_DIFFICULTY: VYPER_UINT256, names.BLOCK_NUMBER: VYPER_UINT256, names.BLOCK_PREVHASH: VYPER_BYTES32, names.BLOCK_TIMESTAMP: VYPER_UINT256 }) CHAIN_TYPE = StructType(names.CHAIN, { names.CHAIN_ID: VYPER_UINT256 }) TX_TYPE = StructType(names.TX, { names.TX_ORIGIN: VYPER_ADDRESS }) def is_numeric(type: VyperType) -> bool: return type in [VYPER_INT128, VYPER_UINT256, VYPER_DECIMAL, NON_NEGATIVE_INT] def is_bounded(type: VyperType) -> bool: return type in [VYPER_INT128, VYPER_UINT256, VYPER_DECIMAL, VYPER_ADDRESS] def is_integer(type: VyperType) -> bool: return type in [VYPER_INT128, VYPER_UINT256, NON_NEGATIVE_INT] def is_unsigned(type: VyperType) -> bool: return type in [VYPER_UINT256, VYPER_ADDRESS, NON_NEGATIVE_INT] def has_strict_array_size(element_type: VyperType) -> bool: return element_type != VYPER_BYTE def is_bytes_array(type: VyperType): return isinstance(type, ArrayType) and type.element_type == VYPER_BYTE def matches(t: VyperType, m: VyperType): """ Determines whether a type t matches a required type m in the specifications. Usually the types have to be the same, except non-strict arrays which may be shorter than the expected length, and contract types which can be used as addresses. Also, all integer types are treated as mathematical integers. """ if isinstance(t, MapType) and isinstance(m, MapType) and t.key_type == m.key_type: return matches(t.value_type, m.value_type) elif (isinstance(t, ArrayType) and (isinstance(m, ArrayType) and not m.is_strict) and t.element_type == m.element_type): return t.size <= m.size elif is_integer(t) and is_integer(m): return True elif isinstance(t, ContractType) and m == VYPER_ADDRESS: return True elif isinstance(t, InterfaceType) and m == VYPER_ADDRESS: return True else: return t == m class TypeBuilder(NodeVisitor): def __init__(self, type_map: Dict[str, VyperType], is_stub: bool = False): self.type_map = type_map self.is_stub = is_stub def build(self, node) -> VyperType: if self.is_stub: return VyperType('$unknown') return self.visit(node) @property def method_name(self): return '_visit' def generic_visit(self, node): raise InvalidProgramException(node, 'invalid.type') def _visit_Name(self, node: ast.Name) -> VyperType: type = self.type_map.get(node.id) or TYPES.get(node.id) if type is None: raise InvalidProgramException(node, 'invalid.type') return type def _visit_StructDef(self, node: ast.StructDef) -> VyperType: members = {n.target.id: self.visit(n.annotation) for n in node.body} return StructType(node.name, members) def _visit_EventDef(self, node: ast.EventDef) -> VyperType: arg_types = [self.visit(n.annotation) for n in node.body] return EventType(arg_types) def _visit_FunctionStub(self, node: ast.FunctionStub) -> VyperType: from twovyper.ast.nodes import Resource name, is_derived = Resource.get_name_and_derived_flag(node) members = {n.name: self.visit(n.annotation) for n in node.args} contract_name = os.path.split(os.path.abspath(node.file))[1].split('.')[0] resource_name = f'{contract_name}${name}' if is_derived: return DerivedResourceType(resource_name, members, UnknownResourceType()) return ResourceType(resource_name, members) def _visit_ContractDef(self, node: ast.ContractDef) -> VyperType: functions = {} modifiers = {} for f in node.body: name = f.name arg_types = [self.visit(arg.annotation) for arg in f.args] return_type = None if f.returns is None else self.visit(f.returns) functions[name] = FunctionType(arg_types, return_type) modifiers[name] = f.body[0].value.id return ContractType(node.name, functions, modifiers) def _visit_FunctionCall(self, node: ast.FunctionCall) -> VyperType: # We allow # - public, indexed: not important for verification # - map: map type # - event: event type # Not allowed is # - constant: should already be replaced # Anything else is treated as a unit if node.name == names.PUBLICFIELD or node.name == names.INDEXED: return self.visit(node.args[0]) elif node.name == names.MAP: key_type = self.visit(node.args[0]) value_type = self.visit(node.args[1]) return MapType(key_type, value_type) elif node.name == names.EVENT: dict_literal = node.args[0] arg_types = [self.visit(arg) for arg in dict_literal.values] return EventType(arg_types) else: type = self.type_map.get(node.name) or TYPES.get(node.name) if type is None: raise InvalidProgramException(node, 'invalid.type') return type def _visit_Subscript(self, node: ast.Subscript) -> VyperType: element_type = self.visit(node.value) # Array size has to be an int or a constant # (which has already been replaced by an int) size = node.index.n return ArrayType(element_type, size, has_strict_array_size(element_type)) def _visit_Tuple(self, node: ast.Tuple) -> VyperType: element_types = [self.visit(n) for n in node.elements] return TupleType(element_types)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/types.py
types.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.vyper import select_version # Constants for names in the original AST # Decorators PUBLIC = select_version({'^0.2.0': 'external', '>=0.1.0-beta.16 <0.1.0': 'public'}) PRIVATE = select_version({'^0.2.0': 'internal', '>=0.1.0-beta.16 <0.1.0': 'private'}) PAYABLE = 'payable' CONSTANT = select_version({'^0.2.0': 'view', '>=0.1.0-beta.16 <0.1.0': 'constant'}) NONREENTRANT = 'nonreentrant' PURE = 'pure' INTERPRETED_DECORATOR = 'interpreted' # Modifiers assert CONSTANT == select_version({'^0.2.0': 'view', '>=0.1.0-beta.16 <0.1.0': 'constant'}) assert PURE == 'pure' MODIFYING = select_version({'^0.2.0': 'payable', '>=0.1.0-beta.16 <0.1.0': 'modifying'}) NONPAYABLE = select_version({'^0.2.0': 'nonpayable'}, default="") PUBLICFIELD = 'public' # Types BOOL = 'bool' INT128 = 'int128' UINT256 = 'uint256' DECIMAL = 'decimal' WEI_VALUE = 'wei_value' TIMESTAMP = 'timestamp' TIMEDELTA = 'timedelta' ADDRESS = 'address' BYTE = select_version({'^0.2.0': 'Bytes', '>=0.1.0-beta.16 <0.1.0': 'bytes'}) BYTES32 = 'bytes32' STRING = select_version({'^0.2.0': 'String', '>=0.1.0-beta.16 <0.1.0': 'string'}) MAP = select_version({'^0.2.0': 'HashMap', '>=0.1.0-beta.16 <0.1.0': 'map'}) EVENT = 'event' NON_NEGATIVE_INTEGER = "non_negative_integer" # Functions INIT = '__init__' # Variables ADDRESS_BALANCE = 'balance' ADDRESS_CODESIZE = 'codesize' ADDRESS_IS_CONTRACT = 'is_contract' SELF = 'self' MSG = 'msg' MSG_SENDER = 'sender' MSG_VALUE = 'value' MSG_GAS = 'gas' BLOCK = 'block' BLOCK_COINBASE = 'coinbase' BLOCK_DIFFICULTY = 'difficulty' BLOCK_NUMBER = 'number' BLOCK_PREVHASH = 'prevhash' BLOCK_TIMESTAMP = 'timestamp' CHAIN = 'chain' CHAIN_ID = 'id' TX = 'tx' TX_ORIGIN = 'origin' LOG = 'log' LEMMA = 'lemma' ENV_VARIABLES = [MSG, BLOCK, CHAIN, TX] # Constants EMPTY_BYTES32 = 'EMPTY_BYTES32' ZERO_ADDRESS = 'ZERO_ADDRESS' ZERO_WEI = 'ZERO_WEI' MIN_INT128 = 'MIN_INT128' MAX_INT128 = 'MAX_INT128' MAX_UINT256 = 'MAX_UINT256' MIN_DECIMAL = 'MIN_DECIMAL' MAX_DECIMAL = 'MAX_DECIMAL' CONSTANT_VALUES = { EMPTY_BYTES32: 'b"' + '\\x00' * 32 + '"', ZERO_ADDRESS: '0', ZERO_WEI: '0', MIN_INT128: f'-{2 ** 127}', MAX_INT128: f'{2 ** 127 - 1}', MAX_UINT256: f'{2 ** 256 - 1}', MIN_DECIMAL: f'-{2 ** 127}.0', MAX_DECIMAL: f'{2 ** 127 - 1}.0' } # Special UNITS = 'units' IMPLEMENTS = 'implements' INDEXED = 'indexed' UNREACHABLE = 'UNREACHABLE' # Ether units ETHER_UNITS = { 'wei': 1, ('femtoether', 'kwei', 'babbage'): 10 ** 3, ('picoether', 'mwei', 'lovelace'): 10 ** 6, ('nanoether', 'gwei', 'shannon'): 10 ** 9, ('microether', 'szabo'): 10 ** 12, ('milliether', 'finney'): 10 ** 15, 'ether': 10 ** 18, ('kether', 'grand'): 10 ** 21 } # Built-in functions MIN = 'min' MAX = 'max' ADDMOD = 'uint256_addmod' MULMOD = 'uint256_mulmod' SQRT = 'sqrt' FLOOR = 'floor' CEIL = 'ceil' SHIFT = 'shift' BITWISE_NOT = 'bitwise_not' BITWISE_AND = 'bitwise_and' BITWISE_OR = 'bitwise_or' BITWISE_XOR = 'bitwise_xor' AS_WEI_VALUE = 'as_wei_value' AS_UNITLESS_NUMBER = 'as_unitless_number' CONVERT = 'convert' EXTRACT32 = 'extract32' EXTRACT32_TYPE = select_version({'^0.2.0': 'output_type', '>=0.1.0-beta.16 <0.1.0': 'type'}) RANGE = 'range' LEN = 'len' CONCAT = 'concat' KECCAK256 = 'keccak256' SHA256 = 'sha256' ECRECOVER = 'ecrecover' ECADD = 'ecadd' ECMUL = 'ecmul' BLOCKHASH = 'blockhash' METHOD_ID = 'method_id' METHOD_ID_OUTPUT_TYPE = select_version({'^0.2.0': 'output_type'}, default="") EMPTY = select_version({'^0.2.0': 'empty'}, default="") ASSERT_MODIFIABLE = select_version({'>=0.1.0-beta.16 <0.1.0': 'assert_modifiable'}, default="") CLEAR = 'clear' SELFDESTRUCT = 'selfdestruct' SEND = 'send' RAW_CALL = 'raw_call' RAW_CALL_OUTSIZE = select_version({'^0.2.0': 'max_outsize', '>=0.1.0-beta.16 <0.1.0': 'outsize'}) RAW_CALL_VALUE = 'value' RAW_CALL_GAS = 'gas' RAW_CALL_DELEGATE_CALL = 'delegate_call' RAW_CALL_IS_STATIC_CALL = select_version({'^0.2.0': 'is_static_call'}, default="") RAW_LOG = 'raw_log' CREATE_FORWARDER_TO = 'create_forwarder_to' CREATE_FORWARDER_TO_VALUE = 'value' # Verification INVARIANT = 'invariant' INTER_CONTRACT_INVARIANTS = 'inter_contract_invariant' GENERAL_POSTCONDITION = 'always_ensures' GENERAL_CHECK = 'always_check' POSTCONDITION = 'ensures' PRECONDITION = 'requires' CHECK = 'check' CALLER_PRIVATE = 'caller_private' PERFORMS = 'performs' CONFIG = 'config' CONFIG_ALLOCATION = 'allocation' CONFIG_NO_GAS = 'no_gas' CONFIG_NO_OVERFLOWS = 'no_overflows' CONFIG_NO_PERFORMS = 'no_performs' CONFIG_NO_DERIVED_WEI = 'no_derived_wei_resource' CONFIG_TRUST_CASTS = 'trust_casts' CONFIG_OPTIONS = [CONFIG_ALLOCATION, CONFIG_NO_GAS, CONFIG_NO_OVERFLOWS, CONFIG_NO_PERFORMS, CONFIG_NO_DERIVED_WEI, CONFIG_TRUST_CASTS] INTERFACE = 'internal_interface' IMPLIES = 'implies' FORALL = 'forall' SUM = 'sum' TUPLE = 'tuple' RESULT = 'result' RESULT_DEFAULT = 'default' STORAGE = 'storage' OLD = 'old' PUBLIC_OLD = 'public_old' ISSUED = 'issued' SENT = 'sent' RECEIVED = 'received' ACCESSIBLE = 'accessible' INDEPENDENT = 'independent' REORDER_INDEPENDENT = 'reorder_independent' assert EVENT == 'event' # EVENT = 'event' assert SELFDESTRUCT == 'selfdestruct' # SELFDESTRUCT = 'selfdestruct' assert IMPLEMENTS == 'implements' # IMPLEMENTS = 'implements' LOCKED = 'locked' REVERT = 'revert' PREVIOUS = 'previous' LOOP_ARRAY = 'loop_array' LOOP_ITERATION = 'loop_iteration' INTERPRETED = 'interpreted' CONDITIONAL = 'conditional' OVERFLOW = 'overflow' OUT_OF_GAS = 'out_of_gas' FAILED = 'failed' CALLER = 'caller' SUCCESS = 'success' SUCCESS_IF_NOT = 'if_not' SUCCESS_OVERFLOW = 'overflow' SUCCESS_OUT_OF_GAS = 'out_of_gas' SUCCESS_SENDER_FAILED = 'sender_failed' SUCCESS_CONDITIONS = [SUCCESS_OVERFLOW, SUCCESS_OUT_OF_GAS, SUCCESS_SENDER_FAILED] WEI = 'wei' UNDERLYING_WEI = 'Wei' ALLOCATED = 'allocated' OFFERED = 'offered' NO_OFFERS = 'no_offers' TRUST_NO_ONE = 'trust_no_one' TRUSTED = 'trusted' TRUSTED_BY = 'by' TRUSTED_WHERE = 'where' REALLOCATE = 'reallocate' REALLOCATE_TO = 'to' REALLOCATE_ACTOR = 'actor' RESOURCE_PAYOUT = 'payout' RESOURCE_PAYOUT_ACTOR = 'actor' RESOURCE_PAYABLE = 'payable' RESOURCE_PAYABLE_ACTOR = 'actor' FOREACH = 'foreach' OFFER = 'offer' OFFER_TO = 'to' OFFER_ACTOR = 'actor' OFFER_TIMES = 'times' ALLOW_TO_DECOMPOSE = 'allow_to_decompose' ALLOWED_TO_DECOMPOSE = 'allowed_to_decompose' REVOKE = 'revoke' REVOKE_TO = 'to' REVOKE_ACTOR = 'actor' EXCHANGE = 'exchange' EXCHANGE_TIMES = 'times' CREATE = 'create' CREATE_TO = 'to' CREATE_ACTOR = 'actor' DESTROY = 'destroy' DESTROY_ACTOR = 'actor' TRUST = 'trust' TRUST_ACTOR = 'actor' ALLOCATE_UNTRACKED = 'allocate_untracked_wei' CREATOR = 'creator' RESOURCE_PREFIX = "r_" DERIVED_RESOURCE_PREFIX = "d_" GHOST_STATEMENTS = [REALLOCATE, FOREACH, OFFER, REVOKE, EXCHANGE, CREATE, DESTROY, TRUST, ALLOCATE_UNTRACKED, ALLOW_TO_DECOMPOSE, RESOURCE_PAYABLE, RESOURCE_PAYOUT] QUANTIFIED_GHOST_STATEMENTS = [OFFER, REVOKE, CREATE, DESTROY, TRUST] SPECIAL_RESOURCES = [WEI, CREATOR] ALLOCATION_SPECIFICATION_FUNCTIONS = [ALLOCATED, OFFERED, NO_OFFERS, TRUSTED, TRUST_NO_ONE, ALLOWED_TO_DECOMPOSE] ALLOCATION_FUNCTIONS = [*ALLOCATION_SPECIFICATION_FUNCTIONS, *GHOST_STATEMENTS] NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS = [PREVIOUS, LOOP_ARRAY, LOOP_ITERATION] NOT_ALLOWED_IN_SPEC = [ASSERT_MODIFIABLE, CLEAR, SEND, RAW_CALL, RAW_LOG, CREATE_FORWARDER_TO] NOT_ALLOWED_IN_INVARIANT = [*NOT_ALLOWED_IN_SPEC, CALLER, OVERFLOW, OUT_OF_GAS, FAILED, ISSUED, BLOCKHASH, INDEPENDENT, REORDER_INDEPENDENT, EVENT, PUBLIC_OLD, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, *GHOST_STATEMENTS] NOT_ALLOWED_IN_LOOP_INVARIANT = [*NOT_ALLOWED_IN_SPEC, CALLER, ACCESSIBLE, OVERFLOW, OUT_OF_GAS, FAILED, ACCESSIBLE, INDEPENDENT, REORDER_INDEPENDENT, INTERPRETED, CONDITIONAL, *GHOST_STATEMENTS] NOT_ALLOWED_IN_CHECK = [*NOT_ALLOWED_IN_SPEC, CALLER, INDEPENDENT, ACCESSIBLE, PUBLIC_OLD, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, *GHOST_STATEMENTS] NOT_ALLOWED_IN_POSTCONDITION = [*NOT_ALLOWED_IN_SPEC, CALLER, ACCESSIBLE, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, *GHOST_STATEMENTS] NOT_ALLOWED_IN_PRECONDITION = [*NOT_ALLOWED_IN_SPEC, CALLER, ACCESSIBLE, SUCCESS, REVERT, OVERFLOW, OUT_OF_GAS, FAILED, RESULT, ACCESSIBLE, OLD, INDEPENDENT, REORDER_INDEPENDENT, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, *GHOST_STATEMENTS] NOT_ALLOWED_IN_TRANSITIVE_POSTCONDITION = [*NOT_ALLOWED_IN_SPEC, CALLER, OVERFLOW, OUT_OF_GAS, FAILED, INDEPENDENT, REORDER_INDEPENDENT, EVENT, ACCESSIBLE, PUBLIC_OLD, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, *GHOST_STATEMENTS] NOT_ALLOWED_IN_CALLER_PRIVATE = [*NOT_ALLOWED_IN_SPEC, IMPLIES, FORALL, SUM, RESULT, STORAGE, OLD, PUBLIC_OLD, ISSUED, SENT, RECEIVED, ACCESSIBLE, INDEPENDENT, REORDER_INDEPENDENT, EVENT, SELFDESTRUCT, IMPLEMENTS, LOCKED, REVERT, OVERFLOW, OUT_OF_GAS, FAILED, SUCCESS, BLOCKHASH, *ALLOCATION_FUNCTIONS, INTERPRETED, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS] NOT_ALLOWED_IN_GHOST_CODE = [*NOT_ALLOWED_IN_SPEC, CALLER, OVERFLOW, OUT_OF_GAS, FAILED, INDEPENDENT, REORDER_INDEPENDENT, ACCESSIBLE, PUBLIC_OLD, SELFDESTRUCT, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS] NOT_ALLOWED_IN_GHOST_FUNCTION = [*NOT_ALLOWED_IN_SPEC, CALLER, OVERFLOW, OUT_OF_GAS, FAILED, STORAGE, OLD, PUBLIC_OLD, ISSUED, BLOCKHASH, SENT, RECEIVED, ACCESSIBLE, INDEPENDENT, REORDER_INDEPENDENT, SELFDESTRUCT, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, *GHOST_STATEMENTS] NOT_ALLOWED_IN_GHOST_STATEMENT = [*NOT_ALLOWED_IN_SPEC, CALLER, SUCCESS, REVERT, OVERFLOW, OUT_OF_GAS, FAILED, RESULT, ACCESSIBLE, INDEPENDENT, REORDER_INDEPENDENT, PUBLIC_OLD, SELFDESTRUCT, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS] NOT_ALLOWED_IN_LEMMAS = [*NOT_ALLOWED_IN_SPEC, RESULT, STORAGE, OLD, PUBLIC_OLD, ISSUED, SENT, RECEIVED, ACCESSIBLE, INDEPENDENT, REORDER_INDEPENDENT, EVENT, SELFDESTRUCT, IMPLEMENTS, LOCKED, REVERT, INTERPRETED, CONDITIONAL, *NOT_ALLOWED_BUT_IN_LOOP_INVARIANTS, OVERFLOW, OUT_OF_GAS, FAILED, CALLER, SUCCESS, *ALLOCATION_FUNCTIONS] # Heuristics WITHDRAW = 'withdraw'
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/names.py
names.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 from twovyper.ast import types from twovyper.ast.types import ContractType, FunctionType, ArrayType VYPER_INTERFACES = ['vyper', 'interfaces'] ERC20 = 'ERC20' ERC721 = 'ERC721' ERC20_FUNCTIONS = { 'totalSupply': FunctionType([], types.VYPER_UINT256), 'balanceOf': FunctionType([types.VYPER_ADDRESS], types.VYPER_UINT256), 'allowance': FunctionType([types.VYPER_ADDRESS, types.VYPER_ADDRESS], types.VYPER_UINT256), 'transfer': FunctionType([types.VYPER_ADDRESS, types.VYPER_UINT256], types.VYPER_BOOL), 'transferFrom': FunctionType([types.VYPER_ADDRESS, types.VYPER_ADDRESS, types.VYPER_UINT256], types.VYPER_BOOL), 'approve': FunctionType([types.VYPER_ADDRESS, types.VYPER_UINT256], types.VYPER_BOOL) } ERC20_MODIFIERS = { 'totalSupply': names.CONSTANT, 'balanceOf': names.CONSTANT, 'allowance': names.MODIFYING, 'transfer': names.MODIFYING, 'transferFrom': names.MODIFYING, 'approve': names.MODIFYING } _BYTES1024 = ArrayType(types.VYPER_BYTE, 1024, False) ERC721_FUNCTIONS = { 'supportsInterfaces': FunctionType([types.VYPER_BYTES32], types.VYPER_BOOL), 'balanceOf': FunctionType([types.VYPER_ADDRESS], types.VYPER_UINT256), 'ownerOf': FunctionType([types.VYPER_UINT256], types.VYPER_ADDRESS), 'getApproved': FunctionType([types.VYPER_UINT256], types.VYPER_ADDRESS), 'isApprovedForAll': FunctionType([types.VYPER_ADDRESS, types.VYPER_ADDRESS], types.VYPER_BOOL), 'transferFrom': FunctionType([types.VYPER_ADDRESS, types.VYPER_ADDRESS, types.VYPER_UINT256], types.VYPER_BOOL), 'safeTransferFrom': FunctionType([types.VYPER_ADDRESS, types.VYPER_ADDRESS, types.VYPER_UINT256, _BYTES1024], None), 'approve': FunctionType([types.VYPER_ADDRESS, types.VYPER_UINT256], None), 'setApprovalForAll': FunctionType([types.VYPER_ADDRESS, types.VYPER_BOOL], None) } ERC721_MODIFIERS = { 'supportsInterfaces': names.CONSTANT, 'balanceOf': names.CONSTANT, 'ownerOf': names.CONSTANT, 'getApproved': names.CONSTANT, 'isApprovedForAll': names.CONSTANT, 'transferFrom': names.MODIFYING, 'safeTransferFrom': names.MODIFYING, 'approve': names.MODIFYING, 'setApprovalForAll': names.MODIFYING } ERC20_TYPE = ContractType(ERC20, ERC20_FUNCTIONS, ERC20_MODIFIERS) ERC721_TYPE = ContractType(ERC721, ERC721_FUNCTIONS, ERC721_MODIFIERS)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/interfaces.py
interfaces.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 os from collections import defaultdict from itertools import chain from typing import Dict, Iterable, List, Optional, Set, Tuple, TYPE_CHECKING from twovyper.ast import ast_nodes as ast, names from twovyper.ast.types import ( VyperType, FunctionType, StructType, ResourceType, ContractType, EventType, InterfaceType, DerivedResourceType ) if TYPE_CHECKING: from twovyper.analysis.analyzer import FunctionAnalysis, ProgramAnalysis class Config: def __init__(self, options: List[str]): self.options = options def has_option(self, option: str) -> bool: return option in self.options class VyperVar: def __init__(self, name: str, type: VyperType, node): self.name = name self.type = type self.node = node class VyperFunction: def __init__(self, name: str, index: int, args: Dict[str, VyperVar], defaults: Dict[str, Optional[ast.Expr]], type: FunctionType, postconditions: List[ast.Expr], preconditions: List[ast.Expr], checks: List[ast.Expr], loop_invariants: Dict[ast.For, List[ast.Expr]], performs: List[ast.FunctionCall], decorators: List[ast.Decorator], node: Optional[ast.FunctionDef]): self.name = name self.index = index self.args = args self.defaults = defaults self.type = type self.postconditions = postconditions self.preconditions = preconditions self.checks = checks self.loop_invariants = loop_invariants self.performs = performs self.decorators = decorators self.node = node # Gets set in the analyzer self.analysis: Optional[FunctionAnalysis] = None @property def _decorator_names(self) -> Iterable[str]: for dec in self.decorators: yield dec.name def is_public(self) -> bool: return names.PUBLIC in self._decorator_names def is_private(self) -> bool: return names.PRIVATE in self._decorator_names def is_payable(self) -> bool: return names.PAYABLE in self._decorator_names def is_constant(self) -> bool: return names.CONSTANT in self._decorator_names def is_pure(self) -> bool: return names.PURE in self._decorator_names def is_interpreted(self) -> bool: return names.INTERPRETED_DECORATOR in self._decorator_names def nonreentrant_keys(self) -> Iterable[str]: for dec in self.decorators: if dec.name == names.NONREENTRANT: yield dec.args[0].s class GhostFunction: def __init__(self, name: str, args: Dict[str, VyperVar], type: FunctionType, node: ast.FunctionDef, file: str): self.name = name self.args = args self.type = type self.node = node self.file = file @property def interface(self): return os.path.split(self.file)[1].split('.')[0] if self.file else '' class VyperStruct: def __init__(self, name: str, type: StructType, node: Optional[ast.Node]): self.name = name self.type = type self.node = node class Resource(VyperStruct): def __init__(self, rtype: ResourceType, node: Optional[ast.Node], file: Optional[str], underlying_resource_node: Optional[ast.Expr] = None): super().__init__(rtype.name, rtype, node) self.file = file self.analysed = False self._own_address = None self.underlying_resource = underlying_resource_node self.underlying_address = None self.derived_resources = [] @property def interface(self): return os.path.split(self.file)[1].split('.')[0] if self.file else '' @property def underlying_resource_name(self): return self.type.underlying_resource.name if isinstance(self.type, DerivedResourceType) else None @property def own_address(self): if self.analysed: raise AssertionError("The own address attribute is only available during the analysing phase.") return self._own_address @own_address.setter def own_address(self, expr: ast.Expr): self._own_address = expr def is_derived_resource(self): return self.underlying_resource_name is not None @staticmethod def get_name_and_derived_flag(node) -> Tuple[str, bool]: if node.name.startswith(names.DERIVED_RESOURCE_PREFIX): return node.name[len(names.DERIVED_RESOURCE_PREFIX):], True assert node.name.startswith(names.RESOURCE_PREFIX) return node.name[len(names.RESOURCE_PREFIX):], False class VyperContract: def __init__(self, name: str, type: ContractType, node: Optional[ast.ContractDef]): self.name = name self.type = type self.node = node class VyperEvent: def __init__(self, name: str, type: EventType): self.name = name self.type = type class VyperProgram: def __init__(self, node: ast.Module, file: str, config: Config, fields: VyperStruct, functions: Dict[str, VyperFunction], interfaces: Dict[str, 'VyperInterface'], structs: Dict[str, VyperStruct], contracts: Dict[str, VyperContract], events: Dict[str, VyperEvent], resources: Dict[str, Resource], local_state_invariants: List[ast.Expr], inter_contract_invariants: List[ast.Expr], general_postconditions: List[ast.Expr], transitive_postconditions: List[ast.Expr], general_checks: List[ast.Expr], lemmas: Dict[str, VyperFunction], implements: List[InterfaceType], real_implements: List[InterfaceType], ghost_function_implementations: Dict[str, GhostFunction]): self.node = node self.file = file self.config = config self.fields = fields self.functions = functions self.interfaces = interfaces self.structs = structs self.contracts = contracts self.events = events self.imported_resources: Dict[str, List[Resource]] = defaultdict(list) for key, value in self._resources(): self.imported_resources[key].append(value) self.own_resources = resources self.declared_resources = dict((name, resource) for name, resource in self.own_resources.items() if name != names.WEI and name != names.UNDERLYING_WEI) self.resources: Dict[str, List[Resource]] = defaultdict(list, self.imported_resources) for key, value in resources.items(): self.resources[key].append(value) self.local_state_invariants = local_state_invariants self.inter_contract_invariants = inter_contract_invariants self.general_postconditions = general_postconditions self.transitive_postconditions = transitive_postconditions self.general_checks = general_checks self.lemmas = lemmas self.implements = implements self.real_implements = real_implements self.ghost_functions: Dict[str, List[GhostFunction]] = defaultdict(list) for key, value in self._ghost_functions(): self.ghost_functions[key].append(value) self.ghost_function_implementations = ghost_function_implementations self.type = fields.type # Is set in the analyzer self.analysis: Optional[ProgramAnalysis] = None def is_interface(self) -> bool: return False def nonreentrant_keys(self) -> Set[str]: s = set() for func in self.functions.values(): for key in func.nonreentrant_keys(): s.add(key) return s def _ghost_functions(self) -> Iterable[Tuple[str, GhostFunction]]: for interface in self.interfaces.values(): for name, func in interface.own_ghost_functions.items(): yield name, func def _resources(self) -> Iterable[Tuple[str, Resource]]: for interface in self.interfaces.values(): for name, resource in interface.declared_resources.items(): yield name, resource @property def invariants(self): return chain(self.local_state_invariants, self.inter_contract_invariants) class VyperInterface(VyperProgram): def __init__(self, node: ast.Module, file: str, name: Optional[str], config: Config, functions: Dict[str, VyperFunction], interfaces: Dict[str, 'VyperInterface'], resources: Dict[str, Resource], local_state_invariants: List[ast.Expr], inter_contract_invariants: List[ast.Expr], general_postconditions: List[ast.Expr], transitive_postconditions: List[ast.Expr], general_checks: List[ast.Expr], caller_private: List[ast.Expr], ghost_functions: Dict[str, GhostFunction], type: InterfaceType, is_stub=False): struct_name = f'{name}$self' empty_struct_type = StructType(struct_name, {}) empty_struct = VyperStruct(struct_name, empty_struct_type, None) super().__init__(node, file, config, empty_struct, functions, interfaces, {}, {}, {}, resources, local_state_invariants, inter_contract_invariants, general_postconditions, transitive_postconditions, general_checks, {}, [], [], {}) self.name = name self.imported_ghost_functions: Dict[str, List[GhostFunction]] = defaultdict(list) for key, value in self._ghost_functions(): self.imported_ghost_functions[key].append(value) self.own_ghost_functions = ghost_functions self.ghost_functions: Dict[str, List[GhostFunction]] = defaultdict(list, self.imported_ghost_functions) for key, value in ghost_functions.items(): self.ghost_functions[key].append(value) self.type = type self.caller_private = caller_private self.is_stub = is_stub def is_interface(self) -> bool: return True
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/nodes.py
nodes.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 Iterable, List, Optional, Tuple, Union from twovyper.ast import ast_nodes as ast def children(node: ast.Node) -> Iterable[Tuple[str, Union[Optional[ast.Node], List[ast.Node]]]]: for child in node.children: yield child, getattr(node, child) # TODO: improve def descendants(node: ast.Node) -> Iterable[ast.Node]: for _, child in children(node): if child is None: continue elif isinstance(child, ast.Node): yield child for child_child in descendants(child): yield child_child elif isinstance(child, List): for child_child in child: yield child_child for child_child_child in descendants(child_child): yield child_child_child class NodeVisitor: @property def method_name(self) -> str: return 'visit' def visit(self, node, *args): method = f'{self.method_name}_{node.__class__.__name__}' visitor = getattr(self, method, self.generic_visit) return visitor(node, *args) def visit_nodes(self, nodes: Iterable[ast.Node], *args): for node in nodes: self.visit(node, *args) return None def generic_visit(self, node, *args): for _, value in children(node): if value is None: continue elif isinstance(value, ast.Node): self.visit(value, *args) elif isinstance(value, list): for item in value: self.visit(item, *args) else: assert False return None class NodeTransformer(NodeVisitor): def generic_visit(self, node, *args): for field, old_value in children(node): if old_value is None: continue elif isinstance(old_value, ast.Node): new_node = self.visit(old_value, *args) if new_node is None: delattr(node, field) else: setattr(node, field, new_node) elif isinstance(old_value, list): new_values = [] for value in old_value: new_value = self.visit(value) if new_value is None: continue else: new_values.append(new_value) old_value[:] = new_values else: assert False return node
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/visitors.py
visitors.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 enum import Enum from typing import List as ListT, Optional as OptionalT class Node: _children: ListT[str] = [] def __init__(self): self.file = None self.lineno = None self.col_offset = None self.end_lineno = None self.end_col_offset = None self.is_ghost_code = False @property def children(self): return self._children class AllowedInGhostCode: pass class Stmt(Node): pass class Expr(Node, AllowedInGhostCode): def __init__(self): super().__init__() self.type = None class Operator(AllowedInGhostCode): pass class BoolOperator(Operator, Enum): AND = 'and' OR = 'or' IMPLIES = 'implies' class BoolOp(Expr): _children = ['left', 'right'] def __init__(self, left: Expr, op: BoolOperator, right: Expr): super().__init__() self.left = left self.op = op self.right = right class Not(Expr): _children = ['operand'] def __init__(self, operand: Expr): super().__init__() self.operand = operand class ArithmeticOperator(Operator, Enum): ADD = '+' SUB = '-' MUL = '*' DIV = '/' MOD = '%' POW = '**' class ArithmeticOp(Expr): _children = ['left', 'right'] def __init__(self, left: Expr, op: ArithmeticOperator, right: Expr): super().__init__() self.left = left self.op = op self.right = right class UnaryArithmeticOperator(Operator, Enum): ADD = '+' SUB = '-' class UnaryArithmeticOp(Expr): _children = ['operand'] def __init__(self, op: UnaryArithmeticOperator, operand: Expr): super().__init__() self.op = op self.operand = operand class ComparisonOperator(Operator, Enum): LT = '<' LTE = '<=' GTE = '>=' GT = '>' class Comparison(Expr): _children = ['left', 'right'] def __init__(self, left: Expr, op: ComparisonOperator, right: Expr): super().__init__() self.left = left self.op = op self.right = right class ContainmentOperator(Operator, Enum): IN = 'in' NOT_IN = 'not in' class Containment(Expr): _children = ['value', 'list'] def __init__(self, value: Expr, op: ContainmentOperator, list_expr: Expr): super().__init__() self.value = value self.op = op self.list = list_expr class EqualityOperator(Operator, Enum): EQ = '==' NEQ = '!=' class Equality(Expr): _children = ['left', 'right'] def __init__(self, left: Expr, op: EqualityOperator, right: Expr): super().__init__() self.left = left self.op = op self.right = right class IfExpr(Expr): _children = ['test', 'body', 'orelse'] def __init__(self, test: Expr, body: Expr, orelse: Expr): super().__init__() self.test = test self.body = body self.orelse = orelse class Set(Expr): _children = ['elements'] def __init__(self, elements: ListT[Expr]): super().__init__() self.elements = elements class Keyword(Node, AllowedInGhostCode): _children = ['value'] def __init__(self, name: str, value: Expr): super().__init__() self.name = name self.value = value class FunctionCall(Expr): _children = ['args', 'keywords', 'resource'] def __init__(self, name: str, args: ListT[Expr], keywords: ListT[Keyword], resource: OptionalT[Expr] = None): super().__init__() self.name = name self.args = args self.keywords = keywords self.resource = resource self.underlying_resource = None class ReceiverCall(Expr): _children = ['receiver', 'args', 'keywords'] def __init__(self, name: str, receiver: Expr, args: ListT[Expr], keywords: ListT[Keyword]): super().__init__() self.name = name self.receiver = receiver self.args = args self.keywords = keywords class Num(Expr): def __init__(self, n): super().__init__() self.n = n class Str(Expr): def __init__(self, s: str): super().__init__() self.s = s class Bytes(Expr): def __init__(self, s: bytes): super().__init__() self.s = s class Bool(Expr): def __init__(self, value): super().__init__() self.value = value class Ellipsis(Expr): pass class Exchange(Expr): _children = ['left', 'right'] def __init__(self, left: Expr, right: Expr): super().__init__() self.left = left self.right = right class Attribute(Expr): _children = ['value'] def __init__(self, value: Expr, attr: str): super().__init__() self.value = value self.attr = attr class Subscript(Expr): _children = ['value', 'index'] def __init__(self, value: Expr, index: Expr): super().__init__() self.value = value self.index = index class Name(Expr): def __init__(self, id_str: str): super().__init__() self.id = id_str class Dict(Expr): _children = ['keys', 'values'] def __init__(self, keys: ListT[Name], values: ListT[Expr]): super().__init__() self.keys = keys self.values = values class List(Expr): _children = ['elements'] def __init__(self, elements: ListT[Expr]): super().__init__() self.elements = elements class Tuple(Expr): _children = ['elements'] def __init__(self, elements: ListT[Expr]): super().__init__() self.elements = elements class Module(Node): _children = ['stmts'] def __init__(self, stmts: ListT[Stmt]): super().__init__() self.stmts = stmts class StructDef(Node): _children = ['body'] def __init__(self, name: str, body: ListT[Stmt]): super().__init__() self.name = name self.body = body class ContractDef(Node): _children = ['body'] def __init__(self, name: str, body: ListT[Stmt]): super().__init__() self.name = name self.body = body class EventDef(Node): """ Struct like event declaration """ _children = ['body'] def __init__(self, name: str, body: ListT[Stmt]): super().__init__() self.name = name self.body = body class Arg(Node, AllowedInGhostCode): _children = ['annotation', 'default'] def __init__(self, name: str, annotation: Expr, default: OptionalT[Expr]): super().__init__() self.name = name self.annotation = annotation self.default = default class Decorator(Node, AllowedInGhostCode): _children = ['args'] def __init__(self, name: str, args: ListT[Expr]): super().__init__() self.name = name self.args = args class FunctionDef(Stmt, AllowedInGhostCode): _children = ['args', 'body', 'decorators', 'returns'] def __init__(self, name: str, args: ListT[Arg], body: ListT[Stmt], decorators: ListT[Decorator], returns: OptionalT[Expr]): super().__init__() self.name = name self.args = args self.body = body self.decorators = decorators self.returns = returns self.is_lemma = False class FunctionStub(Stmt, AllowedInGhostCode): _children = ['args'] def __init__(self, name: str, args: ListT[Arg], returns: OptionalT[Expr]): super().__init__() self.name = name self.args = args self.returns = returns class Return(Stmt): _children = ['value'] def __init__(self, value: OptionalT[Expr]): super().__init__() self.value = value class Assign(Stmt): _children = ['target', 'value'] def __init__(self, target: Expr, value: Expr): super().__init__() self.target = target self.value = value class AugAssign(Stmt): _children = ['target', 'value'] def __init__(self, target: Expr, op: ArithmeticOperator, value: Expr): super().__init__() self.target = target self.op = op self.value = value class AnnAssign(Stmt): _children = ['target', 'annotation', 'value'] def __init__(self, target: Name, annotation: Expr, value: Expr): super().__init__() self.target = target self.annotation = annotation self.value = value class For(Stmt): _children = ['target', 'iter', 'body'] def __init__(self, target: Name, iter_expr: Expr, body: ListT[Stmt]): super().__init__() self.target = target self.iter = iter_expr self.body = body class If(Stmt, AllowedInGhostCode): _children = ['test', 'body', 'orelse'] def __init__(self, test: Expr, body: ListT[Stmt], orelse: ListT[Stmt]): super().__init__() self.test = test self.body = body self.orelse = orelse class Log(Stmt, AllowedInGhostCode): _children = ['body'] def __init__(self, body: Expr): super().__init__() self.body = body class Ghost(Stmt, AllowedInGhostCode): _children = ['body'] def __init__(self, body: ListT[Stmt]): super().__init__() self.body = body class Raise(Stmt, AllowedInGhostCode): _children = ['msg'] def __init__(self, msg: Expr): super().__init__() self.msg = msg class Assert(Stmt, AllowedInGhostCode): _children = ['test', 'msg'] def __init__(self, test: Expr, msg: OptionalT[Expr]): super().__init__() self.test = test self.msg = msg self.is_lemma = False class Alias(Node): def __init__(self, name: str, asname: OptionalT[str]): super().__init__() self.name = name self.asname = asname class Import(Stmt): _children = ['names'] def __init__(self, names: ListT[Alias]): super().__init__() self.names = names class ImportFrom(Stmt): _children = ['names'] def __init__(self, module: OptionalT[str], names: ListT[Alias], level: int): super().__init__() self.module = module self.names = names self.level = level class ExprStmt(Stmt, AllowedInGhostCode): _children = ['value'] def __init__(self, value: Expr): super().__init__() self.value = value class Pass(Stmt, AllowedInGhostCode): pass class Break(Stmt): pass class Continue(Stmt): pass def compare_nodes(first_node: Node, second_node: Node) -> bool: """ Similar as vyper/ast/nodes.py:compare_nodes """ if not isinstance(first_node, type(second_node)): return False for field_name in (i for i in first_node.children): left_value = getattr(first_node, field_name, None) right_value = getattr(second_node, field_name, None) # compare types instead of isinstance() in case one node class inherits the other if type(left_value) is not type(right_value): return False if isinstance(left_value, list): if next((i for i in zip(left_value, right_value) if not compare_nodes(*i)), None): return False elif isinstance(left_value, Node): if not compare_nodes(left_value, right_value): return False elif left_value != right_value: return False return True
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/ast_nodes.py
ast_nodes.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 twovyper.ast import ast_nodes as ast def _split_lines(source): idx = 0 lines = [] next_line = '' while idx < len(source): c = source[idx] idx += 1 if c == '\r' and idx < len(source) and source[idx] == '\n': idx += 1 if c in '\r\n': lines.append(next_line) next_line = '' else: next_line += c if next_line: lines.append(next_line) return lines def pprint(node: ast.Node, preserve_newlines: bool = False) -> str: with open(node.file, 'r') as file: source = file.read() lines = _split_lines(source) lineno = node.lineno - 1 end_lineno = node.end_lineno - 1 col_offset = node.col_offset - 1 end_col_offset = node.end_col_offset - 1 if end_lineno == lineno: text = lines[lineno].encode()[col_offset:end_col_offset].decode() else: first = lines[lineno].encode()[col_offset:].decode() middle = lines[lineno + 1:end_lineno] last = lines[min(end_lineno, len(lines) - 1)].encode()[:end_col_offset].decode() sep = '\n' if preserve_newlines else ' ' text = sep.join(chain([first], middle, [last])) stripped = text.strip() return stripped if preserve_newlines else f'({stripped})'
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/text.py
text.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/ast/__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/. """ import re from twovyper.ast.names import RESOURCE_PREFIX, DERIVED_RESOURCE_PREFIX def preprocess(program: str) -> str: # Make specifications valid python statements. We use assignments instead of variable # declarations because we could have contract variables called 'ensures'. # Padding with spaces is used to keep the column numbers correct in the preprocessed program. def padding(old_length: int, match_length: int) -> str: return (match_length - old_length) * ' ' def replacement(start: str, end: str): old_length = len(start) + len(end) return lambda m: f'{start}{padding(old_length, len(m.group(0)))}{end}' def replace(regex, repl): nonlocal program program = re.sub(regex, repl, program, flags=re.MULTILINE) replace(r'#@\s*config\s*:', replacement('config', '=')) replace(r'#@\s*interface', replacement('internal_interface', '=True')) replace(r'#@\s*ghost\s*:', replacement('with(g)', ':')) replace(r'#@\s*resource\s*:\s*', replacement('def ', RESOURCE_PREFIX)) replace(r'#@\s*derived\s*resource\s*:\s*', replacement('def ', DERIVED_RESOURCE_PREFIX)) replace(r'#@\s*ensures\s*:', replacement('ensures', '=')) replace(r'#@\s*requires\s*:', replacement('requires', '=')) replace(r'#@\s*check\s*:', replacement('check', '=')) replace(r'#@\s*performs\s*:', replacement('performs', '=')) replace(r'#@\s*invariant\s*:', replacement('invariant', '=')) replace(r'#@\s*inter\s*contract\s*invariant\s*:', replacement('inter_contract_invariant', '=')) replace(r'#@\s*always\s*ensures\s*:', replacement('always_ensures', '=')) replace(r'#@\s*always\s*check\s*:', replacement('always_check', '=')) replace(r'#@\s*caller\s*private\s*:', replacement('caller_private', '=')) replace(r'#@\s*preserves\s*:', replacement('if False', ':')) replace(r'#@\s*pure', replacement('@pure', '')) replace(r'#@\s*interpreted', replacement('@interpreted', '')) replace(r'#@\s*lemma_def', replacement('def', '')) replace(r'#@\s*lemma_assert', replacement('assert', '')) return program
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/preprocessor.py
preprocessor.py
""" 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 Any, Dict, List import re from lark import Lark from lark.exceptions import ParseError, UnexpectedInput, VisitError from lark.indenter import Indenter from lark.tree import Meta from lark.visitors import Transformer, v_args from twovyper.ast import ast_nodes as ast, names from twovyper.ast.arithmetic import Decimal from twovyper.ast.visitors import NodeVisitor from twovyper.exceptions import ParseException, InvalidProgramException from twovyper.vyper import select_version class PythonIndenter(Indenter): NL_type = '_NEWLINE' OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE'] CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE'] INDENT_type = '_INDENT' DEDENT_type = '_DEDENT' tab_len = 8 _kwargs = dict(postlex=PythonIndenter(), parser='lalr', propagate_positions=True, maybe_placeholders=False) _lark_file = select_version({'^0.2.0': 'vyper_0_2.lark', '>=0.1.0-beta.16 <0.1.0': 'vyper_0_1.lark'}) _vyper_module_parser = Lark.open(_lark_file, rel_to=__file__, start='file_input', **_kwargs) _vyper_expr_parser = Lark.open(_lark_file, rel_to=__file__, start='test', **_kwargs) def copy_pos(function): def with_pos(self, children: List[Any], meta: Meta): node = function(self, children, meta) node.file = self.file node.lineno = meta.line node.col_offset = meta.column node.end_lineno = meta.end_line node.end_col_offset = meta.end_column return node return with_pos def copy_pos_from(node: ast.Node, to: ast.Node): to.file = node.file to.lineno = node.lineno to.col_offset = node.col_offset to.end_lineno = node.end_lineno to.end_col_offset = node.end_col_offset def copy_pos_between(node: ast.Node, left: ast.Node, right: ast.Node) -> ast.Node: assert left.file == right.file assert left.lineno <= right.lineno assert left.lineno != right.lineno or left.col_offset < right.col_offset node.file = left.file node.lineno = left.lineno node.col_offset = left.col_offset node.end_lineno = right.end_lineno node.end_col_offset = right.end_col_offset return node # noinspection PyUnusedLocal @v_args(meta=True) class _PythonTransformer(Transformer): def transform_tree(self, tree, file): self.file = file transformed = self.transform(tree) self.file = None return transformed @copy_pos def file_input(self, children, meta): return ast.Module(children) @copy_pos def contractdef(self, children, meta): name = str(children[0]) body = children[1] return ast.ContractDef(name, body) @copy_pos def structdef(self, children, meta): name = str(children[0]) body = children[1] return ast.StructDef(name, body) @copy_pos def eventdef(self, children, meta): name = str(children[0]) body = children[1] return ast.EventDef(name, body) @copy_pos def mapdef(self, children, meta): assert len(children) == 1 return ast.FunctionCall(names.MAP, children[0], []) @copy_pos def funcdef(self, children, meta): decorators = children[0] name = str(children[1]) args = children[2] if len(children) == 3: # This is a function stub without a return value if decorators: raise InvalidProgramException(decorators[0], 'invalid.function.stub') return ast.FunctionStub(name, args, None) elif len(children) == 4: if isinstance(children[3], list): # This is a function definition without a return value body = children[3] return ast.FunctionDef(name, args, body, decorators, None) else: # This is a function stub with a return value ret = children[3].children ret = ret[0] if len(ret) == 1 else self._tuple(ret, meta) return ast.FunctionStub(name, args, ret) elif len(children) == 5: # This is a function definition with a return value ret = children[3].children ret = ret[0] if len(ret) == 1 else self._tuple(ret, meta) body = children[4] return ast.FunctionDef(name, args, body, decorators, ret) def decorators(self, children, meta): return children @copy_pos def decorator(self, children, meta): name = str(children[0]) if len(children) == 1: args = [] else: args, kwargs = children[1] if kwargs: raise InvalidProgramException(kwargs[0], 'invalid.decorator') return ast.Decorator(name, args) def parameter_list(self, children, meta): return children @copy_pos def parameter(self, children, meta): name = str(children[0]) annotation = children[1] default = children[2] if len(children) == 3 else None return ast.Arg(name, annotation, default) @copy_pos def expr_stmt(self, children, meta): target = children[0] if isinstance(target, list): target = self._tuple(target, meta) if len(children) == 2: assign_builder = children[1] return assign_builder(target) else: return ast.ExprStmt(target) def assign(self, children, meta): if len(children[0]) > 1: # Used for config value = self._tuple(children[0], meta) else: value = children[0][0] return lambda target: ast.Assign(target, value) @copy_pos def _tuple(self, children, meta): return ast.Tuple(children) def annassign(self, children, meta): annotation = children[0] value = children[1] if len(children) == 2 else None return lambda target: ast.AnnAssign(target, annotation, value) def augassign(self, children, meta): op = children[0] value = children[1] return lambda target: ast.AugAssign(target, op, value) def aug_op(self, children, meta): # The actual operation is the first character of augment operator op = children[0][0] return ast.ArithmeticOperator(op) @copy_pos def pass_stmt(self, children, meta): return ast.Pass() @copy_pos def break_stmt(self, children, meta): return ast.Break() @copy_pos def continue_stmt(self, children, meta): return ast.Continue() @copy_pos def return_stmt(self, children, meta): if not children: return ast.Return(None) value = children[0][0] if len(children[0]) == 1 else self._tuple(children[0], meta) return ast.Return(value) @copy_pos def raise_stmt(self, children, meta): exc = children[0] if children else None return ast.Raise(exc) @copy_pos def import_name(self, children, meta): names = children[0] return ast.Import(names) @copy_pos def import_from(self, children, meta): level, module = children[0] names = children[1] return ast.ImportFrom(module, names, level) def relative_name(self, children, meta): if len(children) == 2: level = children[0] name = children[1] elif isinstance(children[0], str): level = 0 name = children[0] else: level = children[0] name = None return level, name def dots(self, children, meta): return len(children[0]) def alias_list(self, children, meta): return children @copy_pos def alias(self, children, meta): name = children[0] asname = children[1] if len(children) == 2 else None return ast.Alias(name, asname) def dotted_name_list(self, children, meta): return children def dotted_name(self, children, meta): return '.'.join(children) @copy_pos def assert_stmt(self, children, meta): test = children[0] msg = children[1] if len(children) == 2 else None return ast.Assert(test, msg) @copy_pos def if_stmt(self, children, meta): if len(children) % 2 == 0: # We have no else branch orelse = [] else: orelse = children.pop() while children: body = children.pop() test = children.pop() orelse = [self._if_stmt([test, body, orelse], meta)] return orelse[0] @copy_pos def log_stmt(self, children, meta): assert len(children) == 1 assert len(children[0]) == 1 assert isinstance(children[0][0], ast.ExprStmt) return ast.Log(children[0][0].value) @copy_pos def _if_stmt(self, children, meta): test = children[0] body = children[1] orelse = children[2] return ast.If(test, body, orelse) @copy_pos def for_stmt(self, children, meta): target = children[0] iter = children[1] body = children[2] return ast.For(target, iter, body) @copy_pos def with_stmt(self, children, meta): body = children[1] # We ignore the items, as we don't need them return ast.Ghost(body) def suite(self, children, meta): return children @copy_pos def test(self, children, meta): body = children[0] cond = children[1] orelse = children[2] return ast.IfExpr(cond, body, orelse) def _left_associative_bool_op(self, children, op): return reduce(lambda l, r: copy_pos_between(ast.BoolOp(l, op, r), l, r), children) def _right_associative_bool_op(self, children, op): return reduce(lambda r, l: copy_pos_between(ast.BoolOp(l, op, r), l, r), reversed(children)) @copy_pos def impl_test(self, children, meta): return self._right_associative_bool_op(children, ast.BoolOperator.IMPLIES) @copy_pos def or_test(self, children, meta): return self._left_associative_bool_op(children, ast.BoolOperator.OR) @copy_pos def and_test(self, children, meta): return self._left_associative_bool_op(children, ast.BoolOperator.AND) @copy_pos def unot(self, children, meta): operand = children[0] return ast.Not(operand) @copy_pos def comparison(self, children, meta): left = children[0] op = children[1] right = children[2] if isinstance(op, ast.ComparisonOperator): return ast.Comparison(left, op, right) elif isinstance(op, ast.ContainmentOperator): return ast.Containment(left, op, right) elif isinstance(op, ast.EqualityOperator): return ast.Equality(left, op, right) else: assert False @copy_pos def arith_expr(self, children, meta): return self._bin_op(children) @copy_pos def term(self, children, meta): return self._bin_op(children) @copy_pos def factor(self, children, meta): op = children[0] operand = children[1] return ast.UnaryArithmeticOp(op, operand) def _bin_op(self, children): operand = children.pop() def bop(right): if children: op = children.pop() left = bop(children.pop()) ret = ast.ArithmeticOp(left, op, right) copy_pos_between(ret, left, right) return ret else: return right return bop(operand) def factor_op(self, children, meta): return ast.UnaryArithmeticOperator(children[0]) def add_op(self, children, meta): return ast.ArithmeticOperator(children[0]) def mul_op(self, children, meta): return ast.ArithmeticOperator(children[0]) def comp_op(self, children, meta): return ast.ComparisonOperator(children[0]) def cont_op(self, children, meta): if len(children) == 1: return ast.ContainmentOperator.IN else: return ast.ContainmentOperator.NOT_IN def eq_op(self, children, meta): return ast.EqualityOperator(children[0]) @copy_pos def power(self, children, meta): left = children[0] right = children[1] return ast.ArithmeticOp(left, ast.ArithmeticOperator.POW, right) @copy_pos def funccall(self, children, meta): func = children[0] args, kwargs = children[1] if isinstance(func, ast.Name): return ast.FunctionCall(func.id, args, kwargs) elif isinstance(func, ast.Subscript) and isinstance(func.value, ast.Name): return ast.FunctionCall(func.value.id, args, kwargs, func.index) elif isinstance(func, ast.Attribute): return ast.ReceiverCall(func.attr, func.value, args, kwargs) elif isinstance(func, ast.Subscript) and isinstance(func.value, ast.Attribute): return ast.ReceiverCall(func.value.attr, func, args, kwargs) else: raise InvalidProgramException(func, 'invalid.receiver') @copy_pos def getitem(self, children, meta): if isinstance(children[0], ast.Name): if children[0].id == names.MAP: assert len(children) == 3 return ast.FunctionCall(names.MAP, children[1:], []) if children[0].id in (names.EXCHANGE, names.OFFER, names.OFFERED, names.REVOKE): if len(children) == 3: value = children[0] index = ast.Exchange(children[1], children[2]) copy_pos_from(children[1], index) return ast.Subscript(value, index) value = children[0] index = children[1] return ast.Subscript(value, index) @copy_pos def getattr(self, children, meta): value = children[0] attr = str(children[1]) return ast.Attribute(value, attr) @copy_pos def exchange(self, children, meta): value1 = children[0] value2 = children[1] return ast.Exchange(value1, value2) @copy_pos def list(self, children, meta): return ast.List(children[0]) @copy_pos def dictset(self, children, meta): if not children: return ast.Dict([], []) elif isinstance(children[0], tuple): keys, values = children[0] return ast.Dict(keys, values) else: return ast.Set(children[0]) @copy_pos def var(self, children, meta): return ast.Name(str(children[0])) @copy_pos def strings(self, children, meta): if isinstance(children[0], ast.Str): conc = ''.join(c.s for c in children) return ast.Str(conc) else: conc = b''.join(c.s for c in children) return ast.Bytes(conc) @copy_pos def ellipsis(self, children, meta): return ast.Ellipsis() @copy_pos def const_true(self, children, meta): return ast.Bool(True) @copy_pos def const_false(self, children, meta): return ast.Bool(False) def testlist(self, children, meta): return children def dictlist(self, children, meta): keys = [] values = [] it = iter(children) for c in it: keys.append(c) values.append(next(it)) return keys, values def arguments(self, children, meta): args = [] kwargs = [] for c in children: if isinstance(c, ast.Keyword): kwargs.append(c) else: # kwargs cannot come before normal args if kwargs: raise InvalidProgramException(kwargs[0], 'invalid.kwargs') args.append(c) return args, kwargs @copy_pos def argvalue(self, children, meta): identifier = str(children[0]) value = children[1] return ast.Keyword(identifier, value) @copy_pos def number(self, children, meta): n = eval(children[0]) return ast.Num(n) @copy_pos def float(self, children, meta): assert 'e' not in children[0] numd = 10 first, second = children[0].split('.') if len(second) > numd: node = self.number(children, meta) raise InvalidProgramException(node, 'invalid.decimal.literal') int_value = int(first) * 10 ** numd + int(second.ljust(numd, '0')) return ast.Num(Decimal[numd](scaled_value=int_value)) @copy_pos def string(self, children, meta): s = eval(children[0]) if isinstance(s, str): return ast.Str(s) elif isinstance(s, bytes): return ast.Bytes(s) else: assert False def parse(parser, text, file): try: tree = parser.parse(text) except (ParseError, UnexpectedInput) as e: raise ParseException(str(e)) try: return _PythonTransformer().transform_tree(tree, file) except VisitError as e: raise e.orig_exc class CodeVisitor(NodeVisitor): def find_lost_code_information(self, text: str, node: ast.Node): lines = text.splitlines() ghost = {} lemmas = {} pattern = re.compile(r'#@\s*lemma_(def|assert).*') for idx, line in enumerate(lines): line_strip = line.strip() ghost[idx + 1] = line_strip.startswith('#@') match = pattern.match(line_strip) lemmas[idx + 1] = match is not None self.visit(node, ghost, lemmas) def generic_visit(self, node: ast.Node, *args): ghost: Dict[int, bool] = args[0] node.is_ghost_code = ghost[node.lineno] super().generic_visit(node, *args) def visit_FunctionDef(self, node: ast.FunctionDef, *args): lemmas: Dict[int, bool] = args[1] node.is_lemma = lemmas[node.lineno] or lemmas[node.lineno + len(node.decorators)] self.generic_visit(node, *args) def visit_Assert(self, node: ast.Assert, *args): lemmas: Dict[int, bool] = args[1] node.is_lemma = lemmas[node.lineno] self.generic_visit(node, *args) def parse_module(text, original, file) -> ast.Module: node = parse(_vyper_module_parser, text + '\n', file) CodeVisitor().find_lost_code_information(original, node) return node def parse_expr(text, file) -> ast.Expr: return parse(_vyper_expr_parser, text, file)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/lark.py
lark.py
""" 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, Dict, Any, Tuple from twovyper.ast import ast_nodes as ast, names from twovyper.ast.arithmetic import div, mod, Decimal from twovyper.ast.visitors import NodeVisitor, NodeTransformer, descendants from twovyper.exceptions import UnsupportedException from twovyper.parsing import lark from twovyper.utils import switch def transform(vyper_ast: ast.Module) -> ast.Module: constants_decls, new_ast = ConstantCollector().collect_constants(vyper_ast) constant_values, constant_nodes = _interpret_constants(constants_decls) transformed_ast = ConstantTransformer(constant_values, constant_nodes).visit(new_ast) return transformed_ast def _parse_value(val) -> ast.Expr: """ Returns a new ast.Node containing the value. """ return lark.parse_expr(f'{val}', None) def _builtin_constants(): values = {name: value for name, value in names.CONSTANT_VALUES.items()} constants = {name: _parse_value(value) for name, value in names.CONSTANT_VALUES.items()} return values, constants def _interpret_constants(nodes: List[ast.AnnAssign]) -> Tuple[Dict[str, Any], Dict[str, ast.Node]]: env, constants = _builtin_constants() interpreter = ConstantInterpreter(env) for node in nodes: name = node.target.id value = interpreter.visit(node.value) env[name] = value constants[name] = _parse_value(value) return env, constants class ConstantInterpreter(NodeVisitor): """ Determines the value of all constants in the AST. """ def __init__(self, constants: Dict[str, Any]): self.constants = constants def generic_visit(self, node: ast.Node, *args): raise UnsupportedException(node) def visit_BoolOp(self, node: ast.BoolOp): left = self.visit(node.left) right = self.visit(node.right) if node.op == ast.BoolOperator.AND: return left and right elif node.op == ast.BoolOperator.OR: return left or right else: assert False def visit_Not(self, node: ast.Not): operand = self.visit(node.operand) return not operand def visit_ArithmeticOp(self, node: ast.ArithmeticOp): lhs = self.visit(node.left) rhs = self.visit(node.right) op = node.op if op == ast.ArithmeticOperator.ADD: return lhs + rhs elif op == ast.ArithmeticOperator.SUB: return lhs - rhs elif op == ast.ArithmeticOperator.MUL: return lhs * rhs elif op == ast.ArithmeticOperator.DIV: return div(lhs, rhs) elif op == ast.ArithmeticOperator.MOD: return mod(lhs, rhs) elif op == ast.ArithmeticOperator.POW: return lhs ** rhs else: assert False def visit_UnaryArithmeticOp(self, node: ast.UnaryArithmeticOp): operand = self.visit(node.operand) if node.op == ast.UnaryArithmeticOperator.ADD: return operand elif node.op == ast.UnaryArithmeticOperator.SUB: return -operand else: assert False def visit_Comparison(self, node: ast.Comparison): lhs = self.visit(node.left) rhs = self.visit(node.right) with switch(node.op) as case: if case(ast.ComparisonOperator.LT): return lhs < rhs elif case(ast.ComparisonOperator.LTE): return lhs <= rhs elif case(ast.ComparisonOperator.GT): return lhs > rhs elif case(ast.ComparisonOperator.GTE): return lhs >= rhs else: assert False def visit_Equality(self, node: ast.Equality): lhs = self.visit(node.left) rhs = self.visit(node.right) if node.op == ast.EqualityOperator.EQ: return lhs == rhs elif node.op == ast.EqualityOperator.NEQ: return lhs != rhs else: assert False def visit_FunctionCall(self, node: ast.FunctionCall): args = [self.visit(arg) for arg in node.args] if node.name == names.MIN: return min(args) elif node.name == names.MAX: return max(args) elif node.name == names.CONVERT: arg = args[0] second_arg = node.args[1] assert isinstance(second_arg, ast.Name) type_name = second_arg.id if isinstance(arg, int): with switch(type_name) as case: if case(names.BOOL): return bool(arg) elif case(names.DECIMAL): return Decimal[10](value=arg) elif (case(names.INT128) or case(names.UINT256) or case(names.BYTES32)): return arg elif isinstance(arg, Decimal): with switch(type_name) as case: if case(names.BOOL): # noinspection PyUnresolvedReferences return bool(arg.scaled_value) elif case(names.DECIMAL): return arg elif (case(names.INT128) or case(names.UINT256) or case(names.BYTES32)): # noinspection PyUnresolvedReferences return div(arg.scaled_value, arg.scaling_factor) elif isinstance(arg, bool): with switch(type_name) as case: if case(names.BOOL): return arg elif (case(names.DECIMAL) or case(names.INT128) or case(names.UINT256) or case(names.BYTES32)): return int(arg) raise UnsupportedException(node) @staticmethod def visit_Num(node: ast.Num): if isinstance(node.n, int) or isinstance(node.n, Decimal): return node.n else: assert False @staticmethod def visit_Bool(node: ast.Bool): return node.value def visit_Str(self, node: ast.Str): return '"{}"'.format(node.s) def visit_Name(self, node: ast.Name): return self.constants.get(node.id) def visit_List(self, node: ast.List): return [self.visit(element) for element in node.elements] class ConstantCollector(NodeTransformer): """ Collects constants and deletes their declarations from the AST. """ def __init__(self): self.constants = [] @staticmethod def _is_constant(node: ast.Node): return isinstance(node, ast.FunctionCall) and node.name == 'constant' def collect_constants(self, node): new_node = self.visit(node) return self.constants, new_node def visit_AnnAssign(self, node: ast.AnnAssign): if self._is_constant(node.annotation): self.constants.append(node) return None else: return node @staticmethod def visit_FunctionDef(node: ast.FunctionDef): return node class ConstantTransformer(NodeTransformer): """ Replaces all constants in the AST by their value. """ def __init__(self, constant_values: Dict[str, Any], constant_nodes: Dict[str, ast.Node]): self.constants = constant_nodes self.interpreter = ConstantInterpreter(constant_values) def _copy_pos(self, to: ast.Node, node: ast.Node) -> ast.Node: to.file = node.file to.lineno = node.lineno to.col_offset = node.col_offset to.end_lineno = node.end_lineno to.end_col_offset = node.end_col_offset to.is_ghost_code = node.is_ghost_code for child in descendants(to): self._copy_pos(child, node) return to def visit_Name(self, node: ast.Name): return self._copy_pos(self.constants.get(node.id) or node, node) # noinspection PyBroadException def visit_FunctionCall(self, node: ast.FunctionCall): if node.name == names.RANGE: if len(node.args) == 1: try: val = self.interpreter.visit(node.args[0]) new_node = _parse_value(val) new_node = self._copy_pos(new_node, node.args[0]) assert isinstance(new_node, ast.Expr) node.args[0] = new_node except Exception: pass elif len(node.args) == 2: first_arg = node.args[0] second_arg = node.args[1] if isinstance(second_arg, ast.ArithmeticOp) \ and second_arg.op == ast.ArithmeticOperator.ADD \ and ast.compare_nodes(first_arg, second_arg.left): try: val = self.interpreter.visit(second_arg.right) new_node = _parse_value(val) second_arg.right = self._copy_pos(new_node, second_arg.right) except Exception: pass else: try: first_val = self.interpreter.visit(first_arg) first_new_node = _parse_value(first_val) first_new_node = self._copy_pos(first_new_node, first_arg) assert isinstance(first_new_node, ast.Expr) second_val = self.interpreter.visit(second_arg) second_new_node = _parse_value(second_val) second_new_node = self._copy_pos(second_new_node, first_arg) assert isinstance(second_new_node, ast.Expr) node.args[0] = first_new_node node.args[1] = second_new_node except Exception: pass else: self.generic_visit(node) return node
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/transformer.py
transformer.py
""" 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 os from contextlib import contextmanager from typing import Optional, Dict, Union, List from twovyper.parsing.lark import copy_pos_from from twovyper.utils import switch, first from twovyper.parsing import lark from twovyper.parsing.preprocessor import preprocess from twovyper.parsing.transformer import transform from twovyper.ast import ast_nodes as ast, interfaces, names from twovyper.ast.visitors import NodeVisitor, NodeTransformer from twovyper.ast.nodes import ( VyperProgram, VyperFunction, VyperStruct, VyperContract, VyperEvent, VyperVar, Config, VyperInterface, GhostFunction, Resource ) from twovyper.ast.types import ( TypeBuilder, FunctionType, EventType, SelfType, InterfaceType, ResourceType, StructType, ContractType, DerivedResourceType ) from twovyper.exceptions import InvalidProgramException, UnsupportedException def parse(path: str, root: Optional[str], as_interface=False, name=None, parse_level=0) -> VyperProgram: with open(path, 'r') as file: contract = file.read() preprocessed_contract = preprocess(contract) contract_ast = lark.parse_module(preprocessed_contract, contract, path) contract_ast = transform(contract_ast) program_builder = ProgramBuilder(path, root, as_interface, name, parse_level) return program_builder.build(contract_ast) class ProgramBuilder(NodeVisitor): """ The program builder creates a Vyper program out of the AST. It collects contract state variables and functions. It should only be used by calling the build method once. """ # Pre and postconditions are only allowed before a function. As we walk through all # top-level statements we gather pre and postconditions until we reach a function # definition. def __init__(self, path: str, root: Optional[str], is_interface: bool, name: str, parse_level: int): self.path = os.path.abspath(path) self.root = root self.is_interface = is_interface self.name = name self.parse_further_interfaces = parse_level <= 3 self.parse_level = parse_level self.config = None self.field_types = {} self.functions = {} self.lemmas = {} self.function_counter = 0 self.interfaces = {} self.structs = {} self.contracts = {} self.events = {} self.resources = {} self.local_state_invariants = [] self.inter_contract_invariants = [] self.general_postconditions = [] self.transitive_postconditions = [] self.general_checks = [] self.implements = [] self.additional_implements = [] self.ghost_functions = {} self.ghost_function_implementations = {} self.postconditions = [] self.preconditions = [] self.checks = [] self.caller_private = [] self.performs = [] self.is_preserves = False @property def type_builder(self): type_map = {} for name, struct in self.structs.items(): type_map[name] = struct.type for name, contract in self.contracts.items(): type_map[name] = contract.type for name, interface in self.interfaces.items(): type_map[name] = interface.type return TypeBuilder(type_map, not self.parse_further_interfaces) def build(self, node) -> VyperProgram: self.visit(node) # No trailing local specs allowed self._check_no_local_spec() self.config = self.config or Config([]) if self.config.has_option(names.CONFIG_ALLOCATION): # Add wei underlying resource underlying_wei_type = ResourceType(names.UNDERLYING_WEI, {}) underlying_wei_resource = Resource(underlying_wei_type, None, None) self.resources[names.UNDERLYING_WEI] = underlying_wei_resource # Create a fake node for the underlying wei resource fake_node = ast.Name(names.UNDERLYING_WEI) copy_pos_from(node, fake_node) fake_node.is_ghost_code = True if not self.config.has_option(names.CONFIG_NO_DERIVED_WEI): # Add wei derived resource wei_type = DerivedResourceType(names.WEI, {}, underlying_wei_type) wei_resource = Resource(wei_type, None, None, fake_node) self.resources[names.WEI] = wei_resource if self.is_interface: interface_type = InterfaceType(self.name) if self.parse_level <= 2: return VyperInterface(node, self.path, self.name, self.config, self.functions, self.interfaces, self.resources, self.local_state_invariants, self.inter_contract_invariants, self.general_postconditions, self.transitive_postconditions, self.general_checks, self.caller_private, self.ghost_functions, interface_type) else: return VyperInterface(node, self.path, self.name, self.config, {}, {}, self.resources, [], [], [], [], [], [], self.ghost_functions, interface_type, is_stub=True) else: if self.caller_private: node = first(self.caller_private) raise InvalidProgramException(node, 'invalid.caller.private', 'Caller private is only allowed in interfaces') # Create the self-type self_type = SelfType(self.field_types) self_struct = VyperStruct(names.SELF, self_type, None) return VyperProgram(node, self.path, self.config, self_struct, self.functions, self.interfaces, self.structs, self.contracts, self.events, self.resources, self.local_state_invariants, self.inter_contract_invariants, self.general_postconditions, self.transitive_postconditions, self.general_checks, self.lemmas, self.implements, self.implements + self.additional_implements, self.ghost_function_implementations) def _check_no_local_spec(self): """ Checks that there are no specifications for functions pending, i.e. there are no local specifications followed by either global specifications or eof. """ if self.postconditions: cond = "Postcondition" node = self.postconditions[0] elif self.checks: cond = "Check" node = self.checks[0] elif self.performs: cond = "Performs" node = self.performs[0] else: return raise InvalidProgramException(node, 'local.spec', f"{cond} only allowed before function") def _check_no_ghost_function(self): if self.ghost_functions: cond = "Ghost function declaration" node = first(self.ghost_functions.values()).node elif self.ghost_function_implementations: cond = "Ghost function definition" node = first(self.ghost_function_implementations.values()).node else: return raise InvalidProgramException(node, 'invalid.ghost', f'{cond} only allowed after "#@ interface"') def _check_no_lemmas(self): if self.lemmas: raise InvalidProgramException(first(self.lemmas.values()).node, 'invalid.lemma', 'Lemmas are not allowed in interfaces') def generic_visit(self, node: ast.Node, *args): raise InvalidProgramException(node, 'invalid.spec') def visit_Module(self, node: ast.Module): for stmt in node.stmts: self.visit(stmt) def visit_ExprStmt(self, node: ast.ExprStmt): if not isinstance(node.value, ast.Str): # Long string comment, ignore. self.generic_visit(node) def visit_Import(self, node: ast.Import): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') if not self.parse_further_interfaces: return files = {} for alias in node.names: components = alias.name.split('.') components[-1] = f'{components[-1]}.vy' path = os.path.join(self.root or '', *components) files[path] = alias.asname.value if hasattr(alias.asname, 'value') else alias.asname for file, name in files.items(): if name in [names.SELF, names.LOG, names.LEMMA, *names.ENV_VARIABLES]: raise UnsupportedException(node, 'Invalid file name.') interface = parse(file, self.root, True, name, self.parse_level + 1) self.interfaces[name] = interface def visit_ImportFrom(self, node: ast.ImportFrom): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') module = node.module or '' components = module.split('.') if not self.parse_further_interfaces: return if components == interfaces.VYPER_INTERFACES: for alias in node.names: name = alias.name if name == interfaces.ERC20: self.contracts[name] = VyperContract(name, interfaces.ERC20_TYPE, None) elif name == interfaces.ERC721: self.contracts[name] = VyperContract(name, interfaces.ERC721_TYPE, None) else: assert False return if node.level == 0: path = os.path.join(self.root or '', *components) else: path = self.path for _ in range(node.level): path = os.path.dirname(path) path = os.path.join(path, *components) files = {} for alias in node.names: name = alias.name interface_path = os.path.join(path, f'{name}.vy') files[interface_path] = name for file, name in files.items(): if name in [names.SELF, names.LOG, names.LEMMA, *names.ENV_VARIABLES]: raise UnsupportedException(node, 'Invalid file name.') interface = parse(file, self.root, True, name, self.parse_level + 1) self.interfaces[name] = interface def visit_StructDef(self, node: ast.StructDef): vyper_type = self.type_builder.build(node) assert isinstance(vyper_type, StructType) struct = VyperStruct(node.name, vyper_type, node) self.structs[struct.name] = struct def visit_EventDef(self, node: ast.EventDef): vyper_type = self.type_builder.build(node) if isinstance(vyper_type, EventType): event = VyperEvent(node.name, vyper_type) self.events[node.name] = event def visit_FunctionStub(self, node: ast.FunctionStub): # A function stub on the top-level is a resource declaration self._check_no_local_spec() name, is_derived = Resource.get_name_and_derived_flag(node) if name in self.resources or name in names.SPECIAL_RESOURCES: raise InvalidProgramException(node, 'duplicate.resource') vyper_type = self.type_builder.build(node) if isinstance(vyper_type, ResourceType): if is_derived: resource = Resource(vyper_type, node, self.path, node.returns) else: resource = Resource(vyper_type, node, self.path) self.resources[name] = resource def visit_ContractDef(self, node: ast.ContractDef): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') vyper_type = self.type_builder.build(node) if isinstance(vyper_type, ContractType): contract = VyperContract(node.name, vyper_type, node) self.contracts[contract.name] = contract def visit_AnnAssign(self, node: ast.AnnAssign): if node.is_ghost_code: raise InvalidProgramException(node, 'invalid.ghost.code') # No local specs are allowed before contract state variables self._check_no_local_spec() variable_name = node.target.id if variable_name == names.IMPLEMENTS: interface_name = node.annotation.id if interface_name not in [interfaces.ERC20, interfaces.ERC721] or interface_name in self.interfaces: interface_type = InterfaceType(interface_name) self.implements.append(interface_type) elif interface_name in [interfaces.ERC20, interfaces.ERC721]: interface_type = InterfaceType(interface_name) self.additional_implements.append(interface_type) # We ignore the units declarations elif variable_name != names.UNITS: variable_type = self.type_builder.build(node.annotation) if isinstance(variable_type, EventType): event = VyperEvent(variable_name, variable_type) self.events[variable_name] = event else: self.field_types[variable_name] = variable_type def visit_Assign(self, node: ast.Assign): # This is for invariants and postconditions which get translated to # assignments during preprocessing. name = node.target.id if name != names.GENERAL_POSTCONDITION and self.is_preserves: msg = f"Only general postconditions are allowed in preserves. ({name} is not allowed)" raise InvalidProgramException(node, 'invalid.preserves', msg) with switch(name) as case: if case(names.CONFIG): if isinstance(node.value, ast.Name): options = [node.value.id] elif isinstance(node.value, ast.Tuple): options = [n.id for n in node.value.elements] for option in options: if option not in names.CONFIG_OPTIONS: msg = f"Option {option} is invalid." raise InvalidProgramException(node, 'invalid.config.option', msg) if self.config is not None: raise InvalidProgramException(node, 'invalid.config', 'The "config" is specified multiple times.') self.config = Config(options) elif case(names.INTERFACE): self._check_no_local_spec() self._check_no_ghost_function() self._check_no_lemmas() self.is_interface = True elif case(names.INVARIANT): # No local specifications allowed before invariants self._check_no_local_spec() self.local_state_invariants.append(node.value) elif case(names.INTER_CONTRACT_INVARIANTS): # No local specifications allowed before inter contract invariants self._check_no_local_spec() self.inter_contract_invariants.append(node.value) elif case(names.GENERAL_POSTCONDITION): # No local specifications allowed before general postconditions self._check_no_local_spec() if self.is_preserves: self.transitive_postconditions.append(node.value) else: self.general_postconditions.append(node.value) elif case(names.GENERAL_CHECK): # No local specifications allowed before general check self._check_no_local_spec() self.general_checks.append(node.value) elif case(names.POSTCONDITION): self.postconditions.append(node.value) elif case(names.PRECONDITION): self.preconditions.append(node.value) elif case(names.CHECK): self.checks.append(node.value) elif case(names.CALLER_PRIVATE): # No local specifications allowed before caller private self._check_no_local_spec() self.caller_private.append(node.value) elif case(names.PERFORMS): self.performs.append(node.value) else: assert False def visit_If(self, node: ast.If): # This is a preserves clause, since we replace all preserves clauses with if statements # when preprocessing if self.is_preserves: raise InvalidProgramException(node, 'preserves.in.preserves') self.is_preserves = True for stmt in node.body: self.visit(stmt) self.is_preserves = False def _arg(self, node: ast.Arg) -> VyperVar: arg_name = node.name arg_type = self.type_builder.build(node.annotation) return VyperVar(arg_name, arg_type, node) def visit_Ghost(self, node: ast.Ghost): for func in node.body: def check_ghost(cond): if not cond: raise InvalidProgramException(func, 'invalid.ghost') check_ghost(isinstance(func, ast.FunctionDef)) assert isinstance(func, ast.FunctionDef) check_ghost(len(func.body) == 1) func_body = func.body[0] check_ghost(isinstance(func_body, ast.ExprStmt)) assert isinstance(func_body, ast.ExprStmt) check_ghost(func.returns) decorators = [dec.name for dec in func.decorators] check_ghost(len(decorators) == len(func.decorators)) name = func.name args = {arg.name: self._arg(arg) for arg in func.args} arg_types = [arg.type for arg in args.values()] return_type = None if func.returns is None else self.type_builder.build(func.returns) vyper_type = FunctionType(arg_types, return_type) if names.IMPLEMENTS in decorators: check_ghost(not self.is_interface) check_ghost(len(decorators) == 1) ghost_functions = self.ghost_function_implementations else: check_ghost(self.is_interface) check_ghost(not decorators) check_ghost(isinstance(func_body.value, ast.Ellipsis)) ghost_functions = self.ghost_functions if name in ghost_functions: raise InvalidProgramException(func, 'duplicate.ghost') ghost_functions[name] = GhostFunction(name, args, vyper_type, func, self.path) def visit_FunctionDef(self, node: ast.FunctionDef): args = {arg.name: self._arg(arg) for arg in node.args} defaults = {arg.name: arg.default for arg in node.args} arg_types = [arg.type for arg in args.values()] return_type = None if node.returns is None else self.type_builder.build(node.returns) vyper_type = FunctionType(arg_types, return_type) decs = node.decorators loop_invariant_transformer = LoopInvariantTransformer() loop_invariant_transformer.visit(node) function = VyperFunction(node.name, self.function_counter, args, defaults, vyper_type, self.postconditions, self.preconditions, self.checks, loop_invariant_transformer.loop_invariants, self.performs, decs, node) if node.is_lemma: if node.decorators: decorator = node.decorators[0] if len(node.decorators) > 1 or decorator.name != names.INTERPRETED_DECORATOR: raise InvalidProgramException(decorator, 'invalid.lemma', f'A lemma can have only one decorator: {names.INTERPRETED_DECORATOR}') if not decorator.is_ghost_code: raise InvalidProgramException(decorator, 'invalid.lemma', 'The decorator of a lemma must be ghost code') if vyper_type.return_type is not None: raise InvalidProgramException(node, 'invalid.lemma', 'A lemma cannot have a return type') if node.name in self.lemmas: raise InvalidProgramException(node, 'duplicate.lemma') if self.is_interface: raise InvalidProgramException(node, 'invalid.lemma', 'Lemmas are not allowed in interfaces') self.lemmas[node.name] = function else: for decorator in node.decorators: if decorator.is_ghost_code and decorator.name != names.PURE: raise InvalidProgramException(decorator, 'invalid.ghost.code') self.functions[node.name] = function self.function_counter += 1 # Reset local specs self.postconditions = [] self.preconditions = [] self.checks = [] self.performs = [] class LoopInvariantTransformer(NodeTransformer): """ Replaces all constants in the AST by their value. """ def __init__(self): self._last_loop: Union[ast.For, None] = None self._possible_loop_invariant_nodes: List[ast.Assign] = [] self.loop_invariants: Dict[ast.For, List[ast.Expr]] = {} @contextmanager def _in_loop_scope(self, node: ast.For): possible_loop_invariant_nodes = self._possible_loop_invariant_nodes last_loop = self._last_loop self._last_loop = node yield self._possible_loop_invariant_nodes = possible_loop_invariant_nodes self._last_loop = last_loop def visit_Assign(self, node: ast.Assign): if node.is_ghost_code: if isinstance(node.target, ast.Name) and node.target.id == names.INVARIANT: if self._last_loop and node in self._possible_loop_invariant_nodes: self.loop_invariants.setdefault(self._last_loop, []).append(node.value) else: raise InvalidProgramException(node, 'invalid.loop.invariant', 'You may only write loop invariants at beginning in loops') return None return node def visit_For(self, node: ast.For): with self._in_loop_scope(node): self._possible_loop_invariant_nodes = [] for n in node.body: if isinstance(n, ast.Assign) and n.is_ghost_code and n.target.id == names.INVARIANT: self._possible_loop_invariant_nodes.append(n) else: break return self.generic_visit(node)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/parsing/parser.py
parser.py
""" 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/parsing/__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 Dict, Tuple """Conversion rules from Silver level errors to 2vyper errors.""" Rule = Dict[Tuple[str, str], Tuple[str, str]] def combine(first: Rule, second: Rule) -> Rule: """ Combines `first` and `second` to produce a rule as if we first apply `first` and then apply `second` to its result. """ res = first.copy() for k, v in first.items(): # If the result of the first mapping is an input to the second mapping, # do the mapping if v in second: res[k] = second[v] # For all keys which are not mentioned in the first mapping, add the second # mapping for k, v in second.items(): if k not in res: res[k] = v return res INVARIANT_FAIL = { ('assert.failed', 'assertion.false'): ('invariant.violated', 'assertion.false'), ('assert.failed', 'division.by.zero'): ('invariant.not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('invariant.not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('invariant.not.wellformed', 'seq.index.negative') } LOOP_INVARIANT_BASE_FAIL = { ('assert.failed', 'assertion.false'): ('loop.invariant.not.established', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('loop.invariant.not.established', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('loop.invariant.not.established', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative') } LOOP_INVARIANT_STEP_FAIL = { ('assert.failed', 'assertion.false'): ('loop.invariant.not.preserved', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('loop.invariant.not.preserved', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('loop.invariant.not.preserved', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative') } POSTCONDITION_FAIL = { ('assert.failed', 'assertion.false'): ('postcondition.violated', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('postcondition.violated', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('postcondition.violated', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative') } PRECONDITION_FAIL = { ('assert.failed', 'assertion.false'): ('precondition.violated', 'assertion.false'), ('exhale.failed', 'assertion.false'): ('precondition.violated', 'assertion.false'), ('exhale.failed', 'insufficient.permission'): ('precondition.violated', 'insufficient.permission'), ('assert.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative'), ('exhale.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('exhale.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('exhale.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative') } INTERFACE_POSTCONDITION_FAIL = { ('assert.failed', 'assertion.false'): ('postcondition.not.implemented', 'assertion.false') } LEMMA_FAIL = { ('postcondition.violated', 'assertion.false'): ('lemma.step.invalid', 'assertion.false'), ('application.precondition', 'assertion.false'): ('lemma.application.invalid', 'assertion.false') } CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('check.violated', 'assertion.false'), ('assert.failed', 'division.by.zero'): ('not.wellformed', 'division.by.zero'), ('assert.failed', 'seq.index.length'): ('not.wellformed', 'seq.index.length'), ('assert.failed', 'seq.index.negative'): ('not.wellformed', 'seq.index.negative') } CALL_INVARIANT_FAIL = { ('assert.failed', 'assertion.false'): ('call.invariant', 'assertion.false') } DURING_CALL_INVARIANT_FAIL = { ('assert.failed', 'assertion.false'): ('during.call.invariant', 'assertion.false') } CALL_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('call.check', 'assertion.false') } CALLER_PRIVATE_FAIL = { ('assert.failed', 'assertion.false'): ('caller.private.violated', 'assertion.false') } PRIVATE_CALL_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('private.call.check', 'assertion.false') } CALL_LEAK_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('call.leakcheck', 'allocation.leaked') } INHALE_INVARIANT_FAIL = { ('inhale.failed', 'division.by.zero'): ('invariant.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('invariant.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('invariant.not.wellformed', 'seq.index.negative') } INHALE_CALLER_PRIVATE_FAIL = { ('inhale.failed', 'division.by.zero'): ('caller.private.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('caller.private.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('caller.private.not.wellformed', 'seq.index.negative') } INHALE_LOOP_INVARIANT_FAIL = { ('inhale.failed', 'division.by.zero'): ('loop.invariant.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('loop.invariant.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('loop.invariant.not.wellformed', 'seq.index.negative') } INHALE_POSTCONDITION_FAIL = { ('inhale.failed', 'division.by.zero'): ('postcondition.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('postcondition.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('postcondition.not.wellformed', 'seq.index.negative') } INHALE_PRECONDITION_FAIL = { ('inhale.failed', 'division.by.zero'): ('precondition.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('precondition.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('precondition.not.wellformed', 'seq.index.negative') } INHALE_INTERFACE_FAIL = { ('inhale.failed', 'division.by.zero'): ('interface.postcondition.not.wellformed', 'division.by.zero'), ('inhale.failed', 'seq.index.length'): ('interface.postcondition.not.wellformed', 'seq.index.length'), ('inhale.failed', 'seq.index.negative'): ('interface.postcondition.not.wellformed', 'seq.index.negative') } INVARIANT_TRANSITIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('invariant.not.wellformed', 'transitivity.violated') } INVARIANT_REFLEXIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('invariant.not.wellformed', 'reflexivity.violated') } POSTCONDITION_TRANSITIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('postcondition.not.wellformed', 'transitivity.violated') } POSTCONDITION_REFLEXIVITY_VIOLATED = { ('assert.failed', 'assertion.false'): ('postcondition.not.wellformed', 'reflexivity.violated') } POSTCONDITION_CONSTANT_BALANCE = { ('assert.failed', 'assertion.false'): ('postcondition.not.wellformed', 'constant.balance') } PRECONDITION_IMPLEMENTS_INTERFACE = { ('application.precondition', 'assertion.false'): ('application.precondition', 'not.implements.interface') } INTERFACE_RESOURCE_PERFORMS = { ('assert.failed', 'assertion.false'): ('interface.resource', 'resource.address.self') } REALLOCATE_FAIL_INSUFFICIENT_FUNDS = { ('assert.failed', 'assertion.false'): ('reallocate.failed', 'insufficient.funds') } CREATE_FAIL_NOT_A_CREATOR = { ('assert.failed', 'assertion.false'): ('create.failed', 'not.a.creator') } DESTROY_FAIL_INSUFFICIENT_FUNDS = { ('assert.failed', 'assertion.false'): ('destroy.failed', 'insufficient.funds') } EXCHANGE_FAIL_NO_OFFER = { ('assert.failed', 'assertion.false'): ('exchange.failed', 'no.offer') } EXCHANGE_FAIL_INSUFFICIENT_FUNDS = { ('assert.failed', 'assertion.false'): ('exchange.failed', 'insufficient.funds') } INJECTIVITY_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('$operation.failed', 'offer.not.injective') } NO_PERFORMS_FAIL = { ('exhale.failed', 'insufficient.permission'): ('$operation.failed', 'no.performs') } NOT_TRUSTED_FAIL = { ('assert.failed', 'assertion.false'): ('$operation.failed', 'not.trusted') } REALLOCATE_FAIL = { ('$operation.failed', 'no.performs'): ('reallocate.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('reallocate.failed', 'not.trusted') } CREATE_FAIL = { ('$operation.failed', 'offer.not.injective'): ('create.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('create.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('create.failed', 'not.trusted') } DESTROY_FAIL = { ('$operation.failed', 'offer.not.injective'): ('destroy.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('destroy.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('destroy.failed', 'not.trusted') } EXCHANGE_FAIL = { ('$operation.failed', 'no.performs'): ('exchange.failed', 'no.performs') } PAYABLE_FAIL = { ('$operation.failed', 'no.performs'): ('payable.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('payable.failed', 'not.trusted') } PAYOUT_FAIL = { ('$operation.failed', 'no.performs'): ('payout.failed', 'no.performs') } OFFER_FAIL = { ('$operation.failed', 'offer.not.injective'): ('offer.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('offer.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('offer.failed', 'not.trusted') } REVOKE_FAIL = { ('$operation.failed', 'offer.not.injective'): ('revoke.failed', 'offer.not.injective'), ('$operation.failed', 'no.performs'): ('revoke.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('revoke.failed', 'not.trusted') } TRUST_FAIL = { ('$operation.failed', 'offer.not.injective'): ('trust.failed', 'trust.not.injective'), ('$operation.failed', 'no.performs'): ('trust.failed', 'no.performs'), ('$operation.failed', 'not.trusted'): ('trust.failed', 'not.trusted') } ALLOCATE_UNTRACKED_FAIL = { ('$operation.failed', 'no.performs'): ('allocate.untracked.failed', 'no.performs') } ALLOCATION_LEAK_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('leakcheck.failed', 'allocation.leaked') } PERFORMS_LEAK_CHECK_FAIL = { ('assert.failed', 'assertion.false'): ('performs.leakcheck.failed', 'performs.leaked') } UNDERLYING_ADDRESS_SELF_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.address.self') } UNDERLYING_ADDRESS_CONSTANT_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.address.constant') } UNDERLYING_ADDRESS_TRUST_NO_ONE_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.address.trust') } UNDERLYING_RESOURCE_NO_OFFERS_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.resource.offers') } UNDERLYING_RESOURCE_NEQ_FAIL = { ('assert.failed', 'assertion.false'): ('derived.resource.invariant.failed', 'underlying.resource.eq') } PURE_FUNCTION_FAIL = { ('application.precondition', 'assertion.false'): ('function.failed', 'function.revert') }
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/rules.py
rules.py
""" 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, Optional from twovyper.ast import ast_nodes as ast from twovyper.viper.typedefs import Node, AbstractSourcePosition from twovyper.viper.typedefs import AbstractVerificationError, AbstractErrorReason from twovyper.verification.messages import ERRORS, REASONS from twovyper.verification.model import Model, ModelTransformation from twovyper.verification.rules import Rule """Wrappers for Scala error objects.""" class Position: """Wrapper around ``AbstractSourcePosition``.""" def __init__(self, position: AbstractSourcePosition): self._position = position if hasattr(position, 'id'): self.node_id = position.id() else: self.node_id = None @property def file_name(self) -> str: """Return ``file``.""" return str(self._position.file()) @property def line(self) -> int: """Return ``start.line``.""" return self._position.line() @property def column(self) -> int: """Return ``start.column``.""" return self._position.column() def __str__(self) -> str: return str(self._position) class Via: def __init__(self, origin: str, position: AbstractSourcePosition): self.origin = origin self.position = position class ErrorInfo: def __init__(self, node: ast.Node, vias: List[Via], model_transformation: Optional[ModelTransformation], values: Dict[str, Any]): self.node = node self.vias = vias self.model_transformation = model_transformation self.values = values def __getattribute__(self, name: str) -> Any: try: return super().__getattribute__(name) except AttributeError: try: return self.values.get(name) except KeyError: raise AttributeError(f"'ErrorInfo' object has no attribute '{name}'") class Reason: """Wrapper around ``AbstractErrorReason``.""" def __init__(self, reason_id: str, reason: AbstractErrorReason, reason_info: ErrorInfo): self._reason = reason self.identifier = reason_id self._reason_info = reason_info self.offending_node = reason.offendingNode() self.position = Position(self.offending_node.pos()) def __str__(self) -> str: """ Creates a string representation of this reason including a reference to the Python AST node that caused it. """ return REASONS[self.identifier](self._reason_info) class Error: """Wrapper around ``AbstractVerificationError``.""" def __init__(self, error: AbstractVerificationError, rules: Rule, reason_item: ErrorInfo, error_item: ErrorInfo, jvm) -> None: # Translate error id. viper_reason = error.reason() error_id = error.id() reason_id = viper_reason.id() # This error might come from a precondition fail of the Viper function "$pure$return_get" which has no position. # if the reason_item could not be found due to this, use the error_item instead. if error_id == 'application.precondition' and reason_item is None: reason_item = error_item key = error_id, reason_id if key in rules: error_id, reason_id = rules[key] # Construct object. self._error = error self.identifier = error_id self._error_info = error_item self.reason = Reason(reason_id, viper_reason, reason_item) if error.counterexample().isDefined(): self.model = Model(error, jvm, error_item.model_transformation) else: self._model = None self.position = Position(error.pos()) def pos(self) -> AbstractSourcePosition: """ Get position. """ return self._error.pos() @property def full_id(self) -> str: """ Full error identifier. """ return f"{self.identifier}:{self.reason.identifier}" @property def offending_node(self) -> Node: """ AST node where the error occurred. """ return self._error.offendingNode() @property def readable_message(self) -> str: """ Readable error message. """ return self._error.readableMessage() @property def position_string(self) -> str: """ Full error position as a string. """ vias = self._error_info.vias or self.reason._reason_info.vias or [] vias_string = "".join(f", via {via.origin} at {via.position}" for via in vias) return f"{self.position}{vias_string}" @property def message(self) -> str: """ Human readable error message. """ return ERRORS[self.identifier](self._error_info) def __str__(self) -> str: return self.string(False, False) def string(self, ide_mode: bool, include_model: bool = False) -> str: """ Format error. Creates an appropriate error message (referring to the responsible Python code) for the given Viper error. The error format is either optimized for human readability or uses the same format as IDE-mode Viper error messages, depending on the first parameter. The second parameter determines if the message may show Viper-level error explanations if no Python-level explanation is available. """ assert not (ide_mode and include_model) if ide_mode: file_name = self.position.file_name line = self.position.line col = self.position.column msg = self.message reason = self.reason return f"{file_name}:{line}:{col}: error: {msg} {reason}" else: msg = self.message reason = self.reason pos = self.position_string error_msg = f"{msg} {reason} ({pos})" if include_model and self.model: return f"{error_msg}\nCounterexample:\n{self.model}" else: return error_msg
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/error.py
error.py
""" 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 uuid import uuid1 from typing import Any, Dict, List, Optional from twovyper.utils import unique from twovyper.viper.jvmaccess import JVM from twovyper.viper.typedefs import Node, AbstractSourcePosition from twovyper.viper.typedefs import AbstractVerificationError from twovyper.verification.error import Error, ErrorInfo from twovyper.verification.rules import Rule """Error handling state is stored in singleton ``manager``.""" class ErrorManager: """A singleton object that stores the state needed for error handling.""" def __init__(self) -> None: self._items: Dict[str, ErrorInfo] = {} self._conversion_rules: Dict[str, Rule] = {} def add_error_information(self, error_info: ErrorInfo, conversion_rules: Rule) -> str: """Add error information to state.""" item_id = str(uuid1()) assert item_id not in self._items self._items[item_id] = error_info if conversion_rules is not None: self._conversion_rules[item_id] = conversion_rules return item_id def clear(self) -> None: """Clear all state.""" self._items.clear() self._conversion_rules.clear() def convert( self, errors: List[AbstractVerificationError], jvm: Optional[JVM]) -> List[Error]: """Convert Viper errors into 2vyper errors. It does that by wrapping in ``Error`` subclasses. """ def eq(e1: Error, e2: Error) -> bool: ide = e1.string(True, False) == e2.string(True, False) normal = e1.string(False, False) == e2.string(False, False) return ide and normal return unique(eq, [self._convert_error(error, jvm) for error in errors]) def get_vias(self, node_id: str) -> List[Any]: """Get via information for the given ``node_id``.""" item = self._items[node_id] return item.vias def _get_error_info(self, pos: AbstractSourcePosition) -> Optional[ErrorInfo]: if hasattr(pos, 'id'): node_id = pos.id() return self._items[node_id] return None def _get_conversion_rules( self, position: AbstractSourcePosition) -> Optional[Rule]: if hasattr(position, 'id'): node_id = position.id() return self._conversion_rules.get(node_id) else: return None def _try_get_rules_workaround( self, node: Node, jvm: Optional[JVM]) -> Optional[Rule]: """Try to extract rules out of ``node``. Due to optimizations, Silicon sometimes returns not the correct offending node, but an And that contains it. This method tries to work around this problem. .. todo:: In the long term we should discuss with Malte how to solve this problem properly. """ rules = self._get_conversion_rules(node.pos()) if rules or not jvm: return rules if (isinstance(node, jvm.viper.silver.ast.And) or isinstance(node, jvm.viper.silver.ast.Implies)): return (self._get_conversion_rules(node.left().pos()) or self._get_conversion_rules(node.right().pos()) or self._try_get_rules_workaround(node.left(), jvm) or self._try_get_rules_workaround(node.right(), jvm)) return def transformError(self, error: AbstractVerificationError) -> AbstractVerificationError: """ Transform silver error to a fixpoint. """ old_error = None while old_error != error: old_error = error error = error.transformedError() return error def _convert_error( self, error: AbstractVerificationError, jvm: Optional[JVM]) -> Error: error = self.transformError(error) reason_pos = error.reason().offendingNode().pos() reason_item = self._get_error_info(reason_pos) position = error.pos() rules = self._try_get_rules_workaround( error.offendingNode(), jvm) if rules is None: rules = self._try_get_rules_workaround( error.reason().offendingNode(), jvm) if rules is None: rules = {} error_item = self._get_error_info(position) return Error(error, rules, reason_item, error_item, jvm) manager = ErrorManager()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/manager.py
manager.py
""" 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 OrderedDict from typing import Any, Dict, List, Optional, Tuple from twovyper.utils import seq_to_list from twovyper.ast import types from twovyper.ast.arithmetic import Decimal from twovyper.ast.types import ArrayType, DecimalType, MapType, PrimitiveType, StructType, VyperType from twovyper.viper.jvmaccess import JVM from twovyper.viper.typedefs import AbstractVerificationError, ModelEntry, Sort, Term ModelTransformation = Tuple[Dict[str, str], Dict[str, VyperType]] class Model: def __init__(self, error: AbstractVerificationError, jvm: JVM, transform: Optional[ModelTransformation]): ce = error.counterexample().get() scala_model = ce.model() self._store = ce.internalStore() self._names = transform and transform[0] self._types = transform and transform[1] self._jvm = jvm model = OrderedDict() for entry in ScalaIterableWrapper(scala_model.entries()): self.extract_model_entry(entry, model) self._model = model self.values() def extract_model_entry(self, entry: ModelEntry, target: Dict[str, Any]): name = str(entry._1()) value = entry._2() if isinstance(value, self._jvm.viper.silver.verifier.SingleEntry): target[name] = str(value.value()) else: entry_val = OrderedDict() for option in ScalaIterableWrapper(value.options()): option_value = option._2() option_key = () for option_key_entry in ScalaIterableWrapper(option._1()): option_key += (str(option_key_entry),) entry_val[option_key] = str(option_value) entry_val['else'] = str(value.els()) target[name] = entry_val def values(self) -> Dict[str, str]: res = {} if self._model and self._store and self._names: store_map = self._store.values() keys = seq_to_list(store_map.keys()) for name_entry in keys: name = str(name_entry) term = store_map.get(name_entry).get() try: value = evaluate_term(self._jvm, term, self._model) except NoFittingValueException: continue transformation = self.transform_variable(name, value, term.sort()) if transformation: name, value = transformation res[name] = value return res def transform_variable(self, name: str, value: str, sort: Sort) -> Optional[Tuple[str, str]]: if name in self._names and name in self._types: vy_name = self._names[name] vy_type = self._types[name] value = str(value) return vy_name, self.transform_value(value, vy_type, sort) return None def parse_int(self, val: str) -> int: if val.startswith('(-') and val.endswith(')'): return - int(val[2:-1]) return int(val) def transform_value(self, value: str, vy_type: VyperType, sort: Sort) -> str: if isinstance(sort, self._jvm.viper.silicon.state.terms.sorts.UserSort) and str(sort.id()) == '$Int': value = get_func_value(self._model, '$unwrap<Int>', (value,)) if isinstance(vy_type, PrimitiveType) and vy_type.name == 'bool': return value.capitalize() if isinstance(vy_type, DecimalType): value = self.parse_int(value) return str(Decimal[vy_type.number_of_digits](scaled_value=value)) elif vy_type == types.VYPER_ADDRESS: value = self.parse_int(value) return f'{value:#0{40}x}' elif isinstance(vy_type, PrimitiveType): # assume int value = self.parse_int(value) return str(value) elif isinstance(vy_type, ArrayType): res = OrderedDict() length = get_func_value(self._model, SEQ_LENGTH, (value,)) parsed_length = self.parse_int(length) if parsed_length > 0: index_func_name = SEQ_INDEX + "<{}>".format(translate_sort(self._jvm, sort.elementsSort())) indices, els_index = get_func_values(self._model, index_func_name, (value,)) int_type = PrimitiveType('int') for ((index,), val) in indices: converted_index = self.transform_value(index, int_type, self.translate_type_sort(int_type)) converted_value = self.transform_value(val, vy_type.element_type, sort.elementsSort()) res[str(converted_index)] = converted_value if els_index is not None: converted_value = self.transform_value(els_index, vy_type.element_type, sort.elementsSort()) res['_'] = converted_value return "[ {} ]: {}".format(', '.join(['{} -> {}'.format(k, v) for k, v in res.items()]), parsed_length) elif isinstance(vy_type, MapType): res = {} fname = '$map_get<{}>'.format(self.translate_type_name(vy_type.value_type)) keys, els_val = get_func_values(self._model, fname, (value,)) for ((key,), val) in keys: converted_key = self.transform_value(key, vy_type.key_type, self.translate_type_sort(vy_type.key_type)) converted_value = self.transform_value(val, vy_type.value_type, self.translate_type_sort(vy_type.value_type)) res[converted_key] = converted_value if els_val is not None: converted_value = self.transform_value(els_val, vy_type.value_type, self.translate_type_sort(vy_type.value_type)) res['_'] = converted_value return "{{ {} }}".format(', '.join(['{} -> {}'.format(k, v) for k, v in res.items()])) else: return value def translate_type_name(self, vy_type: VyperType) -> str: if isinstance(vy_type, MapType): return '$Map<{}~_{}>'.format(self.translate_type_name(vy_type.key_type), self.translate_type_name(vy_type.value_type)) if isinstance(vy_type, PrimitiveType) and vy_type.name == 'bool': return 'Bool' if isinstance(vy_type, PrimitiveType): return 'Int' if isinstance(vy_type, StructType): return '$Struct' if isinstance(vy_type, ArrayType): return 'Seq<{}>'.format(self.translate_type_name(vy_type.element_type)) raise Exception(vy_type) def translate_type_sort(self, vy_type: VyperType) -> Sort: terms = self._jvm.viper.silicon.state.terms Identifier = self._jvm.viper.silicon.state.SimpleIdentifier def get_sort_object(name): return getattr(getattr(terms, 'sorts$' + name + '$'), "MODULE$") def get_sort_class(name): return getattr(terms, 'sorts$' + name) if isinstance(vy_type, MapType): name = '$Map<{}~_>'.format(self.translate_type_name(vy_type.key_type), self.translate_type_name(vy_type.value_type)) return get_sort_class('UserSort')(Identifier(name)) if isinstance(vy_type, PrimitiveType) and vy_type.name == 'bool': return get_sort_object('Bool') if isinstance(vy_type, PrimitiveType): return get_sort_object('Int') if isinstance(vy_type, StructType): return get_sort_class('UserSort')(Identifier('$Struct')) if isinstance(vy_type, ArrayType): return get_sort_class('Seq')(self.translate_type_sort(vy_type.element_type)) raise Exception(vy_type) def __str__(self): return "\n".join(f" {name} = {value}" for name, value in sorted(self.values().items())) # The following code is mostly lifted from Nagini SNAP_TO = '$SortWrappers.' SEQ_LENGTH = 'seq_t_length<Int>' SEQ_INDEX = 'seq_t_index' class ScalaIteratorWrapper: def __init__(self, iterator): self.iterator = iterator def __next__(self): if self.iterator.hasNext(): return self.iterator.next() else: raise StopIteration class ScalaIterableWrapper: def __init__(self, iterable): self.iterable = iterable def __iter__(self): return ScalaIteratorWrapper(self.iterable.toIterator()) class NoFittingValueException(Exception): pass def get_func_value(model: Dict[str, Any], name: str, args: Tuple[str, ...]) -> str: args = tuple([' '.join(a.split()) for a in args]) entry = model[name] if args == () and isinstance(entry, str): return entry res = entry.get(args) if res is not None: return res return model[name].get('else') def get_func_values(model: Dict[str, Any], name: str, args: Tuple[str, ...]) -> Tuple[List[Tuple[List[str], str]], str]: args = tuple([' '.join(a.split()) for a in args]) options = [(k[len(args):], v) for k, v in model[name].items() if k != 'else' and k[:len(args)] == args] els= model[name].get('else') return options, els def get_parts(jvm: JVM, val: str) -> List[str]: parser = getattr(getattr(jvm.viper.silver.verifier, 'ModelParser$'), 'MODULE$') res = [] for part in ScalaIterableWrapper(parser.getApplication(val)): res.append(part) return res def translate_sort(jvm: JVM, s: Sort) -> str: terms = jvm.viper.silicon.state.terms def get_sort_object(name): return getattr(terms, 'sorts$' + name + '$') def get_sort_class(name): return getattr(terms, 'sorts$' + name) if isinstance(s, get_sort_class('Set')): return 'Set<{}>'.format(translate_sort(jvm, s.elementsSort())) if isinstance(s, get_sort_class('UserSort')): return '{}'.format(s.id()) elif isinstance(s, get_sort_object('Ref')): return '$Ref' elif isinstance(s, get_sort_object('Snap')): return '$Snap' elif isinstance(s, get_sort_object('Perm')): return '$Perm' elif isinstance(s, get_sort_class('Seq')): return 'Seq<{}>'.format(translate_sort(jvm, s.elementsSort())) else: return str(s) def evaluate_term(jvm: JVM, term: Term, model: Dict[str, Any]) -> str: if isinstance(term, getattr(jvm.viper.silicon.state.terms, 'Unit$')): return '$Snap.unit' if isinstance(term, jvm.viper.silicon.state.terms.IntLiteral): return str(term) if isinstance(term, jvm.viper.silicon.state.terms.BooleanLiteral): return str(term) if isinstance(term, jvm.viper.silicon.state.terms.Null): return model['$Ref.null'] if isinstance(term, jvm.viper.silicon.state.terms.Var): key = str(term) if key not in model: raise NoFittingValueException return model[key] elif isinstance(term, jvm.viper.silicon.state.terms.App): fname = str(term.applicable().id()) + '%limited' if fname not in model: fname = str(term.applicable().id()) if fname not in model: fname = fname.replace('[', '<').replace(']', '>') args = [] for arg in ScalaIterableWrapper(term.args()): args.append(evaluate_term(jvm, arg, model)) res = get_func_value(model, fname, tuple(args)) return res if isinstance(term, jvm.viper.silicon.state.terms.Combine): p0_val = evaluate_term(jvm, term.p0(), model) p1_val = evaluate_term(jvm, term.p1(), model) return '($Snap.combine ' + p0_val + ' ' + p1_val + ')' if isinstance(term, jvm.viper.silicon.state.terms.First): sub = evaluate_term(jvm, term.p(), model) if sub.startswith('($Snap.combine '): return get_parts(jvm, sub)[1] elif isinstance(term, jvm.viper.silicon.state.terms.Second): sub = evaluate_term(jvm, term.p(), model) if sub.startswith('($Snap.combine '): return get_parts(jvm, sub)[2] elif isinstance(term, jvm.viper.silicon.state.terms.SortWrapper): sub = evaluate_term(jvm, term.t(), model) from_sort_name = translate_sort(jvm, term.t().sort()) to_sort_name = translate_sort(jvm, term.to()) return get_func_value(model, SNAP_TO + from_sort_name + 'To' + to_sort_name, (sub,)) elif isinstance(term, jvm.viper.silicon.state.terms.PredicateLookup): lookup_func_name = '$PSF.lookup_' + term.predname() toSnapTree = getattr(jvm.viper.silicon.state.terms, 'toSnapTree$') obj = getattr(toSnapTree, 'MODULE$') snap = obj.apply(term.args()) psf_value = evaluate_term(jvm, term.psf(), model) snap_value = evaluate_term(jvm, snap, model) return get_func_value(model, lookup_func_name, (psf_value, snap_value)) raise Exception(str(term))
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/model.py
model.py
""" 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.verification.manager import manager as error_manager from twovyper.verification.error import Error as TwoVyperError
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/__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/. """ import abc import logging from enum import Enum from typing import Optional, Any from jpype import JPackage from twovyper import config from twovyper.utils import list_to_seq from twovyper.viper.typedefs import Program from twovyper.viper.jvmaccess import JVM from twovyper.verification.result import VerificationResult, Success, Failure class AbstractVerifier(abc.ABC): def __init__(self): self.jvm: Optional[JVM] = None self.silver: Optional[JPackage] = None @abc.abstractmethod def _initialize(self, jvm: JVM, file: str, get_model: bool = False): pass @abc.abstractmethod def verify(self, program: Program, jvm: JVM, filename: str, get_model: bool = False) -> VerificationResult: pass class Silicon(AbstractVerifier): """ Provides access to the Silicon verifier """ def __init__(self): super().__init__() self.silicon: Optional[Any] = None def _initialize(self, jvm: JVM, filename: str, get_model: bool = False): self.jvm = jvm self.silver = jvm.viper.silver if not jvm.is_known_class(jvm.viper.silicon.Silicon): raise Exception('Silicon backend not found on classpath.') self.silicon = jvm.viper.silicon.Silicon() args = [ '--z3Exe', config.z3_path, '--disableCatchingExceptions', *(['--counterexample=native'] if get_model else []), filename ] self.silicon.parseCommandLine(list_to_seq(args, jvm)) self.silicon.start() logging.info("Initialized Silicon.") def verify(self, program: Program, jvm: JVM, filename: str, get_model: bool = False) -> VerificationResult: """ Verifies the given program using Silicon """ if self.silicon is None: self._initialize(jvm, filename, get_model) assert self.silicon is not None result = self.silicon.verify(program) if isinstance(result, self.silver.verifier.Failure): logging.info("Silicon returned with: Failure.") it = result.errors().toIterator() errors = [] while it.hasNext(): errors += [it.next()] return Failure(errors, self.jvm) else: logging.info("Silicon returned with: Success.") return Success() def __del__(self): if self.silicon is not None: self.silicon.stop() class Carbon(AbstractVerifier): """ Provides access to the Carbon verifier """ def __init__(self): super().__init__() self.carbon: Optional[Any] = None def _initialize(self, jvm: JVM, filename: str, get_model: bool = False): self.silver = jvm.viper.silver if not jvm.is_known_class(jvm.viper.carbon.CarbonVerifier): raise Exception('Carbon backend not found on classpath.') if config.boogie_path is None: raise Exception('Boogie not found.') self.carbon = jvm.viper.carbon.CarbonVerifier() args = [ '--boogieExe', config.boogie_path, '--z3Exe', config.z3_path, *(['--counterexample=variables'] if get_model else []), filename ] self.carbon.parseCommandLine(list_to_seq(args, jvm)) self.carbon.start() self.jvm = jvm logging.info("Initialized Carbon.") def verify(self, program: Program, jvm: JVM, filename: str, get_model: bool = False) -> VerificationResult: """ Verifies the given program using Carbon """ if self.carbon is None: self._initialize(jvm, filename, get_model) assert self.carbon is not None result = self.carbon.verify(program) if isinstance(result, self.silver.verifier.Failure): logging.info("Carbon returned with: Failure.") it = result.errors().toIterator() errors = [] while it.hasNext(): errors += [it.next()] return Failure(errors) else: logging.info("Carbon returned with: Success.") return Success() def __del__(self): if self.carbon is not None: self.carbon.stop() class ViperVerifier(Enum): silicon = Silicon() carbon = Carbon()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/verifier.py
verifier.py
""" 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 abc import ABCMeta from typing import List, Optional from twovyper.viper.jvmaccess import JVM from twovyper.viper.typedefs import AbstractVerificationError from twovyper.verification import error_manager class VerificationResult(metaclass=ABCMeta): pass class Success(VerificationResult): """ Encodes a verification success """ def __bool__(self): return True def string(self, ide_mode: bool, include_model: bool = False) -> str: return "Verification successful" class Failure(VerificationResult): """ Encodes a verification failure and provides access to the errors """ def __init__( self, errors: List[AbstractVerificationError], jvm: Optional[JVM] = None): self.errors = error_manager.convert(errors, jvm) def __bool__(self): return False def string(self, ide_mode: bool, include_model: bool = False) -> str: errors = [error.string(ide_mode, include_model) for error in self.errors] return "Verification failed\nErrors:\n" + '\n'.join(errors)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/result.py
result.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/. """ # Conversion of errors to human readable messages. from twovyper.ast.text import pprint ERRORS = { 'assignment.failed': lambda i: "Assignment might fail.", 'call.failed': lambda i: "Method call might fail.", 'not.wellformed': lambda i: f"Function {i.function.name} might not be well-formed.", 'call.invariant': lambda i: f"An invariant might not hold before the call {pprint(i.node)}.", 'during.call.invariant': lambda i: f"An invariant might not hold during the call {pprint(i.node)}.", 'call.check': lambda i: f"A check might not hold before the call {pprint(i.node)}.", 'private.call.check': lambda i: f"A check might not hold in the private function.", 'call.precondition': lambda i: f"The precondition of function {pprint(i.node)} might not hold.", 'call.leakcheck': lambda i: f"The leak check for call {pprint(i.node)} might not hold.", 'application.precondition': lambda i: f"The precondition of function {pprint(i.node)} might not hold.", 'exhale.failed': lambda i: "Exhale might fail.", 'inhale.failed': lambda i: "Inhale might fail.", 'if.failed': lambda i: "Conditional statement might fail.", 'while.failed': lambda i: "While statement might fail.", 'assert.failed': lambda i: "Assert might fail.", 'postcondition.violated': lambda i: f"Postcondition of {i.function.name} might not hold.", 'postcondition.not.implemented': lambda i: f"Function {i.function.name} might not correctly implement an interface.", 'precondition.violated': lambda i: f"Precondition of {i.function.name} might not hold.", 'invariant.violated': lambda i: f"Invariant not preserved by {i.function.name}.", 'loop.invariant.not.established': lambda i: f"Loop invariant not established.", 'loop.invariant.not.preserved': lambda i: f"Loop invariant not preserved.", 'check.violated': lambda i: f"A check might not hold after the body of {i.function.name}.", 'caller.private.violated': lambda i: f"A caller private expression might got changed for another caller.", 'caller.private.not.wellformed': lambda i: f"Caller private {pprint(i.node)} might not be well-formed.", 'invariant.not.wellformed': lambda i: f"Invariant {pprint(i.node)} might not be well-formed.", 'loop.invariant.not.wellformed': lambda i: f"Loop invariant {pprint(i.node)} might not be well-formed.", 'postcondition.not.wellformed': lambda i: f"(General) Postcondition {pprint(i.node)} might not be well-formed.", 'precondition.not.wellformed': lambda i: f"Precondition {pprint(i.node)} might not be well-formed.", 'interface.postcondition.not.wellformed': lambda i: f"Postcondition of {pprint(i.node)} might not be well-formed.", 'reallocate.failed': lambda i: f"Reallocate might fail.", 'create.failed': lambda i: f"Create might fail.", 'destroy.failed': lambda i: f"Destroy might fail.", 'payable.failed': lambda i: f"The function {i.function.name} is payable and must be granted to allocate resources.", 'payout.failed': lambda i: f"Resource payout might fail.", 'offer.failed': lambda i: f"Offer might fail.", 'revoke.failed': lambda i: f"Revoke might fail.", 'exchange.failed': lambda i: f"Exchange {pprint(i.node)} might fail.", 'trust.failed': lambda i: f"Trust might fail.", 'allocate.untracked.failed': lambda i: f"The allocation of untracked resources might fail.", 'leakcheck.failed': lambda i: f"Leak check for resource {i.resource.name} might fail in {i.function.name}.", 'performs.leakcheck.failed': lambda i: f"Leak check for performs clauses might fail.", 'interface.resource': lambda i: f"The resource {i.resource.name} comes from an interface " f"and therefore its address must not be 'self'.", 'fold.failed': lambda i: "Fold might fail.", 'unfold.failed': lambda i: "Unfold might fail.", 'invariant.not.preserved': lambda i: "Loop invariant might not be preserved.", 'invariant.not.established': lambda i: "Loop invariant might not hold on entry.", 'function.not.wellformed': lambda i: "Function might not be well-formed.", 'predicate.not.wellformed': lambda i: "Predicate might not be well-formed.", 'function.failed': lambda i: f"The function call {pprint(i.node)} might not succeed.", 'lemma.step.invalid': lambda i: f"A step in the lemma {i.function.name} might not hold.", 'lemma.application.invalid': lambda i: f"Cannot apply lemma {i.function.name}.", 'derived.resource.invariant.failed': lambda i: f"A property of the derived resource {i.resource.name} might not hold.", } REASONS = { 'assertion.false': lambda i: f"Assertion {pprint(i.node)} might not hold.", 'transitivity.violated': lambda i: f"It might not be transitive.", 'reflexivity.violated': lambda i: f"It might not be reflexive.", 'constant.balance': lambda i: f"It might assume constant balance.", 'division.by.zero': lambda i: f"Divisor {pprint(i.node)} might be zero.", 'seq.index.length': lambda i: f"Index {pprint(i.node)} might exceed array length.", 'seq.index.negative': lambda i: f"Index {pprint(i.node)} might be negative.", 'not.implements.interface': lambda i: f"Receiver might not implement the interface.", 'insufficient.funds': lambda i: f"There might be insufficient allocated funds.", 'not.a.creator': lambda i: f"There might not be an appropriate creator resource.", 'not.trusted': lambda i: f"Message sender might not be trusted.", 'no.offer': lambda i: f"There might not be an appropriate offer.", 'no.performs': lambda i: f"The function might not be allowed to perform this operation.", 'offer.not.injective': lambda i: f"The offer might not be injective.", 'trust.not.injective': lambda i: f"Trust might not be injective.", 'allocation.leaked': lambda i: f"Some allocation might be leaked.", 'performs.leaked': lambda i: f"The function might not perform all required operations.", 'receiver.not.injective': lambda i: f"Receiver of {pprint(i.node)} might not be injective.", 'receiver.null': lambda i: f"Receiver of {pprint(i.node)} might be null.", 'negative.permission': lambda i: f"Fraction {pprint(i.node)} might be negative.", 'insufficient.permission': lambda i: f"There might be insufficient permission to access {pprint(i.node)}.", 'function.revert': lambda i: f"The function {i.function.name} might revert.", 'resource.address.self': lambda i: f"The address of the resource might be equal to 'self'.", 'underlying.address.self': lambda i: f"The address of the underlying resource might be equal to 'self'.", 'underlying.address.constant': lambda i: f"The address of the underlying resource might got changed after initially setting it.", 'underlying.address.trust': lambda i: f"The contract might trust others in the contract of the underlying resource.", 'underlying.resource.offers': lambda i: f"The contract might have open offers using the underlying resource.", 'underlying.resource.eq': lambda i: f"The derived resource {i.resource.name} and {i.other_resource.name} " f"might have the same underlying resource.", }
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/verification/messages.py
messages.py
""" 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 jpype class JVM: """ Encapsulates access to a JVM """ def __init__(self, classpath: str): jvm_path = jpype.getDefaultJVMPath() path_arg = f'-Djava.class.path={classpath}' jpype.startJVM(jvm_path, path_arg, '-Xss48m', convertStrings=False) self.java = jpype.JPackage('java') self.scala = jpype.JPackage('scala') self.viper = jpype.JPackage('viper') self.fastparse = jpype.JPackage('fastparse') def is_known_class(self, class_object) -> bool: return not isinstance(class_object, jpype.JPackage)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/jvmaccess.py
jvmaccess.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 # AST abstract Node = Any # 'silver.ast.Node' Stmt = Any # 'silver.ast.Stmt' Expr = Any # 'silver.ast.Exp' # AST Program = Any # 'silver.ast.Program' Field = Any # 'silver.ast.Field' Method = Any # 'silver.ast.Method' Function = Any # 'silver.ast.Function' Domain = Any # 'silver.ast.Domain' DomainAxiom = Any # 'silver.ast.DomainAxiom' DomainFunc = Any # 'silver.ast.DomainFunc' DomainFuncApp = Any # 'silver.ast.DomainFuncApp' DomainType = Any # 'silver.ast.DomainType' TypeVar = Any # 'silver.ast.TypeVar' Type = Any # 'silver.ast.Type' Seqn = Any # 'silver.ast.Seqn' Trigger = Any # 'silver.ast.Trigger' Var = Any # 'silver.ast.LocalVar' VarDecl = Any # 'silver.ast.LocalVarDecl' VarAssign = Any # 'silver.ast.LocalVarAssign' # Error handling AbstractSourcePosition = Any # 'silver.ast.AbstractSourcePosition' Position = Any # 'silver.ast.Position' Info = Any # 'silver.ast.Info' # Verification AbstractVerificationError = Any # 'silver.verifier.AbstractVerificationError' AbstractErrorReason = Any # 'silver.verifier.AbstractErrorReason' # Counterexamples ModelEntry = Any # 'silver.verifier.ModelEntry' Sort = Any # 'silicon.state.terms.Sort' Term = Any # 'silicon.state.terms.Term'
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/typedefs.py
typedefs.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 jpype import JImplements, JOverride class ViperAST: """ Provides convenient access to the classes which constitute the Viper AST. All constructors convert Python lists to Scala sequences, Python ints to Scala BigInts, and wrap Scala Option types where necessary. """ def __init__(self, jvm): self.jvm = jvm self.java = jvm.java self.scala = jvm.scala self.ast = jvm.viper.silver.ast self.ast_extensions = jvm.viper.silver.sif def getobject(package, name): return getattr(getattr(package, name + '$'), 'MODULE$') def getconst(name): return getobject(self.ast, name) self.QPs = getobject(self.ast.utility, 'QuantifiedPermissions') self.AddOp = getconst('AddOp') self.AndOp = getconst('AndOp') self.DivOp = getconst('DivOp') self.FracOp = getconst('FracOp') self.GeOp = getconst('GeOp') self.GtOp = getconst('GtOp') self.ImpliesOp = getconst('ImpliesOp') self.IntPermMulOp = getconst('IntPermMulOp') self.LeOp = getconst('LeOp') self.LtOp = getconst('LtOp') self.ModOp = getconst('ModOp') self.MulOp = getconst('MulOp') self.NegOp = getconst('NegOp') self.NotOp = getconst('NotOp') self.OrOp = getconst('OrOp') self.PermAddOp = getconst('PermAddOp') self.PermDivOp = getconst('PermDivOp') self.SubOp = getconst('SubOp') self.NoPosition = getconst('NoPosition') self.NoInfo = getconst('NoInfo') self.NoTrafos = getconst('NoTrafos') self.Int = getconst('Int') self.Bool = getconst('Bool') self.Ref = getconst('Ref') self.Perm = getconst('Perm') self.MethodWithLabelsInScope = getobject(self.ast, 'MethodWithLabelsInScope') self.BigInt = getobject(self.scala.math, 'BigInt') self.None_ = getobject(self.scala, 'None') self.seq_types = set() def is_available(self) -> bool: """ Checks if the Viper AST is available, i.e., silver is on the Java classpath. """ return self.jvm.is_known_class(self.ast.Program) def is_extension_available(self) -> bool: """ Checks if the extended AST is available, i.e., the SIF AST extension is on the Java classpath. """ return self.jvm.is_known_class(self.ast_extensions.SIFReturnStmt) def empty_seq(self): return self.scala.collection.mutable.ListBuffer() def singleton_seq(self, element): result = self.scala.collection.mutable.ArraySeq(1) result.update(0, element) return result def append(self, list, to_append): if to_append is not None: lsttoappend = self.singleton_seq(to_append) list.append(lsttoappend) def to_seq(self, py_iterable): result = self.scala.collection.mutable.ArraySeq(len(py_iterable)) for index, value in enumerate(py_iterable): result.update(index, value) return result.toList() def to_list(self, seq): result = [] iterator = seq.toIterator() while iterator.hasNext(): result.append(iterator.next()) return result def to_map(self, dict): result = self.scala.collection.immutable.HashMap() for k, v in dict.items(): result = result.updated(k, v) return result def to_big_int(self, num: int): # Python ints might not fit into a C int, therefore we use a String num_str = str(num) return self.BigInt.apply(num_str) def Program(self, domains, fields, functions, predicates, methods, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Program(self.to_seq(domains), self.to_seq(fields), self.to_seq(functions), self.to_seq(predicates), self.to_seq(methods), self.to_seq([]), position, info, self.NoTrafos) def Function(self, name, args, type, pres, posts, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo body = self.scala.Some(body) if body is not None else self.None_ return self.ast.Function(name, self.to_seq(args), type, self.to_seq(pres), self.to_seq(posts), body, position, info, self.NoTrafos) def Method(self, name, args, returns, pres, posts, locals, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo if body is None: body_with_locals = self.None_ else: body_with_locals = self.scala.Some(self.Seqn(body, position, info, locals)) method = self.MethodWithLabelsInScope return method.apply(name, self.to_seq(args), self.to_seq(returns), self.to_seq(pres), self.to_seq(posts), body_with_locals, position, info, self.NoTrafos) def Field(self, name, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Field(name, type, position, info, self.NoTrafos) def Predicate(self, name, args, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo body = self.scala.Some(body) if body is not None else self.None_ return self.ast.Predicate(name, self.to_seq(args), body, position, info, self.NoTrafos) def PredicateAccess(self, args, pred_name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PredicateAccess(self.to_seq(args), pred_name, position, info, self.NoTrafos) def PredicateAccessPredicate(self, loc, perm, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PredicateAccessPredicate(loc, perm, position, info, self.NoTrafos) def Fold(self, predicate, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Fold(predicate, position, info, self.NoTrafos) def Unfold(self, predicate, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Unfold(predicate, position, info, self.NoTrafos) def Unfolding(self, predicate, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Unfolding(predicate, expr, position, info, self.NoTrafos) def SeqType(self, element_type): self.seq_types.add(element_type) return self.ast.SeqType(element_type) def SetType(self, element_type): return self.ast.SetType(element_type) def MultisetType(self, element_type): return self.ast.MultisetType(element_type) def Domain(self, name, functions, axioms, typevars, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Domain(name, self.to_seq(functions), self.to_seq(axioms), self.to_seq(typevars), position, info, self.NoTrafos) def DomainFunc(self, name, args, type, unique, domain_name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.DomainFunc(name, self.to_seq(args), type, unique, position, info, domain_name, self.NoTrafos) def DomainAxiom(self, name, expr, domain_name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NamedDomainAxiom(name, expr, position, info, domain_name, self.NoTrafos) def DomainType(self, name, type_vars_map, type_vars): map = self.to_map(type_vars_map) seq = self.to_seq(type_vars) return self.ast.DomainType(name, map, seq) def DomainFuncApp(self, func_name, args, type_passed, position, info, domain_name, type_var_map={}): position = position or self.NoPosition info = info or self.NoInfo type_passed_func = self.to_function0(type_passed) result = self.ast.DomainFuncApp(func_name, self.to_seq(args), self.to_map(type_var_map), position, info, type_passed_func, domain_name, self.NoTrafos) return result def TypeVar(self, name): return self.ast.TypeVar(name) def MethodCall(self, method_name, args, targets, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.MethodCall(method_name, self.to_seq(args), self.to_seq(targets), position, info, self.NoTrafos) def NewStmt(self, lhs, fields, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NewStmt(lhs, self.to_seq(fields), position, info, self.NoTrafos) def Label(self, name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Label(name, self.to_seq([]), position, info, self.NoTrafos) def Goto(self, name, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Goto(name, position, info, self.NoTrafos) def Seqn(self, body, position=None, info=None, locals=[]): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Seqn(self.to_seq(body), self.to_seq(locals), position, info, self.NoTrafos) def LocalVarAssign(self, lhs, rhs, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LocalVarAssign(lhs, rhs, position, info, self.NoTrafos) def FieldAssign(self, lhs, rhs, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FieldAssign(lhs, rhs, position, info, self.NoTrafos) def FieldAccess(self, receiver, field, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FieldAccess(receiver, field, position, info, self.NoTrafos) def FieldAccessPredicate(self, fieldacc, perm, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FieldAccessPredicate(fieldacc, perm, position, info, self.NoTrafos) def Old(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Old(expr, position, info, self.NoTrafos) def LabelledOld(self, expr, label, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LabelledOld(expr, label, position, info, self.NoTrafos) def Inhale(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Inhale(expr, position, info, self.NoTrafos) def Exhale(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Exhale(expr, position, info, self.NoTrafos) def InhaleExhaleExp(self, inhale, exhale, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.InhaleExhaleExp(inhale, exhale, position, info, self.NoTrafos) def Assert(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Assert(expr, position, info, self.NoTrafos) def FullPerm(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FullPerm(position, info, self.NoTrafos) def NoPerm(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NoPerm(position, info, self.NoTrafos) def WildcardPerm(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.WildcardPerm(position, info, self.NoTrafos) def FractionalPerm(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FractionalPerm(left, right, position, info, self.NoTrafos) def CurrentPerm(self, location, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.CurrentPerm(location, position, info, self.NoTrafos) def ForPerm(self, variables, access, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ForPerm(self.to_seq(variables), access, body, position, info, self.NoTrafos) def PermMinus(self, exp, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermMinus(exp, position, info, self.NoTrafos) def PermAdd(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermAdd(left, right, position, info, self.NoTrafos) def PermSub(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermSub(left, right, position, info, self.NoTrafos) def PermMul(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermMul(left, right, position, info, self.NoTrafos) def IntPermMul(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.IntPermMul(left, right, position, info, self.NoTrafos) def PermDiv(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermDiv(left, right, position, info, self.NoTrafos) def PermLtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermLtCmp(left, right, position, info, self.NoTrafos) def PermLeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermLeCmp(left, right, position, info, self.NoTrafos) def PermGtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermGtCmp(left, right, position, info, self.NoTrafos) def PermGeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.PermGeCmp(left, right, position, info, self.NoTrafos) def Not(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Not(expr, position, info, self.NoTrafos) def Minus(self, expr, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Minus(expr, position, info, self.NoTrafos) def CondExp(self, cond, then, els, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.CondExp(cond, then, els, position, info, self.NoTrafos) def EqCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EqCmp(left, right, position, info, self.NoTrafos) def NeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NeCmp(left, right, position, info, self.NoTrafos) def GtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.GtCmp(left, right, position, info, self.NoTrafos) def GeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.GeCmp(left, right, position, info, self.NoTrafos) def LtCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LtCmp(left, right, position, info, self.NoTrafos) def LeCmp(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LeCmp(left, right, position, info, self.NoTrafos) def IntLit(self, num, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.IntLit(self.to_big_int(num), position, info, self.NoTrafos) def Implies(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Implies(left, right, position, info, self.NoTrafos) def FuncApp(self, name, args, position=None, info=None, type=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FuncApp(name, self.to_seq(args), position, info, type, self.NoTrafos) def ExplicitSeq(self, elems, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ExplicitSeq(self.to_seq(elems), position, info, self.NoTrafos) def ExplicitSet(self, elems, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ExplicitSet(self.to_seq(elems), position, info, self.NoTrafos) def ExplicitMultiset(self, elems, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.ExplicitMultiset(self.to_seq(elems), position, info, self.NoTrafos) def EmptySeq(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EmptySeq(type, position, info, self.NoTrafos) def EmptySet(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EmptySet(type, position, info, self.NoTrafos) def EmptyMultiset(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.EmptyMultiset(type, position, info, self.NoTrafos) def LocalVarDecl(self, name, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LocalVarDecl(name, type, position, info, self.NoTrafos) def LocalVar(self, name, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.LocalVar(name, type, position, info, self.NoTrafos) def Result(self, type, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Result(type, position, info, self.NoTrafos) def AnySetContains(self, elem, s, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.AnySetContains(elem, s, position, info, self.NoTrafos) def AnySetUnion(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.AnySetUnion(left, right, position, info, self.NoTrafos) def AnySetSubset(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.AnySetSubset(left, right, position, info, self.NoTrafos) def SeqAppend(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqAppend(left, right, position, info, self.NoTrafos) def SeqContains(self, elem, s, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqContains(elem, s, position, info, self.NoTrafos) def SeqLength(self, s, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqLength(s, position, info, self.NoTrafos) def SeqIndex(self, s, ind, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqIndex(s, ind, position, info, self.NoTrafos) def SeqTake(self, s, end, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqTake(s, end, position, info, self.NoTrafos) def SeqDrop(self, s, end, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqDrop(s, end, position, info, self.NoTrafos) def SeqUpdate(self, s, ind, elem, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.SeqUpdate(s, ind, elem, position, info, self.NoTrafos) def Add(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Add(left, right, position, info, self.NoTrafos) def Sub(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Sub(left, right, position, info, self.NoTrafos) def Mul(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Mul(left, right, position, info, self.NoTrafos) def Div(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Div(left, right, position, info, self.NoTrafos) def Mod(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Mod(left, right, position, info, self.NoTrafos) def And(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.And(left, right, position, info, self.NoTrafos) def Or(self, left, right, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Or(left, right, position, info, self.NoTrafos) def If(self, cond, thn, els, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo thn_seqn = self.Seqn(thn, position) els_seqn = self.Seqn(els, position) return self.ast.If(cond, thn_seqn, els_seqn, position, info, self.NoTrafos) def TrueLit(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.TrueLit(position, info, self.NoTrafos) def FalseLit(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.FalseLit(position, info, self.NoTrafos) def NullLit(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.NullLit(position, info, self.NoTrafos) def Forall(self, variables, triggers, exp, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo if not variables: return exp res = self.ast.Forall(self.to_seq(variables), self.to_seq(triggers), exp, position, info, self.NoTrafos) if res.isPure(): return res else: desugared = self.to_list(self.QPs.desugarSourceQuantifiedPermissionSyntax(res)) result = self.TrueLit(position, info) for qp in desugared: result = self.And(result, qp, position, info) return result def Exists(self, variables, triggers, exp, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo res = self.ast.Exists(self.to_seq(variables), self.to_seq(triggers), exp, position, info, self.NoTrafos) return res def Trigger(self, exps, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Trigger(self.to_seq(exps), position, info, self.NoTrafos) def While(self, cond, invariants, locals, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo body_with_locals = self.Seqn(body, position, info, locals) return self.ast.While(cond, self.to_seq(invariants), body_with_locals, position, info, self.NoTrafos) def Let(self, variable, exp, body, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast.Let(variable, exp, body, position, info, self.NoTrafos) def from_option(self, option): if option == self.None_: return None else: return option.get() def to_function0(self, value): @JImplements(self.jvm.scala.Function0) class Function0: @JOverride def apply(self): return value return Function0() def SimpleInfo(self, comments): return self.ast.SimpleInfo(self.to_seq(comments)) def ConsInfo(self, head, tail): return self.ast.ConsInfo(head, tail) def to_position(self, expr, id: str): path = self.java.nio.file.Paths.get(expr.file, []) start = self.ast.LineColumnPosition(expr.lineno, expr.col_offset) end = self.ast.LineColumnPosition(expr.end_lineno, expr.end_col_offset) end = self.scala.Some(end) return self.ast.IdentifierPosition(path, start, end, id) def is_heap_dependent(self, expr) -> bool: """ Checks if the given expression contains an access to a heap location. Does NOT check for calls to heap-dependent functions. """ for n in [expr] + self.to_list(expr.subnodes()): if isinstance(n, self.ast.LocationAccess): return True return False # SIF extension AST nodes def Low(self, expr, comparator: str = '', type_vars_map={}, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo comp = self.scala.Some(comparator) if comparator else self.None_ type_vars_map = self.to_map(type_vars_map) return self.ast_extensions.SIFLowExp(expr, comp, type_vars_map, position, info, self.NoTrafos) def LowEvent(self, position=None, info=None): position = position or self.NoPosition info = info or self.NoInfo return self.ast_extensions.SIFLowEventExp(position, info, self.NoTrafos)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/ast.py
ast.py
""" 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.viper.jvmaccess import JVM from twovyper.viper.typedefs import Program def configure_mpp_transformation(jvm: JVM): """ Configure which optimizations to apply in MPP transformation. - ctrl_opt: only generate those control variables which are needed. - seq_opt: bunch together statements which are executed under the same condition without interference with the other execution. - act_opt: at the beginning of each method add an 'assume p1' statement. - func_opt: only apply the _checkDefined and _isDefined functions in the first execution. """ jvm.viper.silver.sif.SIFExtendedTransformer.optimizeControlFlow(True) jvm.viper.silver.sif.SIFExtendedTransformer.optimizeSequential(True) jvm.viper.silver.sif.SIFExtendedTransformer.optimizeRestrictActVars(True) jvm.viper.silver.sif.SIFExtendedTransformer.onlyTransformMethodsWithRelationalSpecs(True) jvm.viper.silver.sif.SIFExtendedTransformer.addPrimedFuncAppReplacement("_checkDefined", "first_arg") jvm.viper.silver.sif.SIFExtendedTransformer.addPrimedFuncAppReplacement("_isDefined", "true") def transform(jvm: JVM, program: Program): return jvm.viper.silver.sif.SIFExtendedTransformer.transform(program, False)
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/sif.py
sif.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.viper.jvmaccess import JVM from twovyper.viper.typedefs import Program class ViperParser: def __init__(self, jvm: JVM): self.jvm = jvm self.parser = getattr(getattr(jvm.viper.silver.parser, "FastParser$"), "MODULE$") self.parsed_success = getattr(jvm.fastparse.core, 'Parsed$Success') self._None = getattr(getattr(jvm.scala, 'None$'), 'MODULE$') assert self.parser assert self._None def parse(self, text: str, file: str) -> Program: jvm = self.jvm path = jvm.java.nio.file.Paths.get(file, []) parsed = self.parser.parse(text, path, self._None) assert isinstance(parsed, self.parsed_success) parse_result = parsed.value() parse_result.initProperties() resolver = jvm.viper.silver.parser.Resolver(parse_result) resolved = resolver.run() resolved = resolved.get() translator = jvm.viper.silver.parser.Translator(resolved) # Reset messages in global Consistency object. Otherwise, left-over # translation errors from previous translations prevent loading of the # built-in silver files. jvm.viper.silver.ast.utility.Consistency.resetMessages() program = translator.translate() return program.get()
2vyper
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/viper/parser.py
parser.py