How to use the vyper.ast function in vyper

To help you get started, we’ve selected a few vyper examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vyperlang / vyper / vyper / parser / stmt.py View on Github external
target.value.id in self.context.in_for_loop:
                list_name = target.value.id
                raise_exception = True

            if raise_exception:
                raise StructureException(
                    f"Altering list '{list_name}' which is being iterated!",
                    self.stmt,
                )

        if isinstance(target, ast.Name) and target.id in self.context.forvars:
            raise StructureException(
                f"Altering iterator '{target.id}' which is in use!",
                self.stmt,
            )
        if isinstance(target, ast.Tuple):
            return Expr(target, self.context).lll_node
        target = Expr.parse_variable_location(target, self.context)
        if target.location == 'storage' and self.context.is_constant():
            raise ConstancyViolationException(
                f"Cannot modify storage inside {self.context.pp_constancy()}: {target.annotation}",
                self.stmt,
            )
        if not target.mutable:
            raise ConstancyViolationException(
                f"Cannot modify function argument: {target.annotation}",
                self.stmt,
            )
        return target
github vyperlang / vyper / vyper / signatures / interface.py View on Github external
def mk_full_signature_from_json(abi):
    funcs = [func for func in abi if func['type'] == 'function']
    sigs = []

    for func in funcs:
        args = []
        returns = None
        for a in func['inputs']:
            arg = ast.arg(
                arg=a['name'],
                annotation=abi_type_to_ast(a['type']),
                lineno=0,
                col_offset=0
            )
            args.append(arg)

        if len(func['outputs']) == 1:
            returns = abi_type_to_ast(func['outputs'][0]['type'])
        elif len(func['outputs']) > 1:
            returns = ast.Tuple(
                elts=[
                    abi_type_to_ast(a['type'])
                    for a in func['outputs']
                ]
            )
github vyperlang / vyper / vyper / types / types.py View on Github external
def parse_type(item, location, sigs=None, custom_units=None, custom_structs=None, constants=None):
    # Base and custom types, e.g. num
    if isinstance(item, ast.Name):
        if item.id in BASE_TYPES:
            return BaseType(item.id)
        elif item.id in SPECIAL_TYPES:
            return SPECIAL_TYPES[item.id]
        elif (custom_structs is not None) and (item.id in custom_structs):
            return make_struct_type(
                item.id,
                location,
                custom_structs[item.id],
                custom_units,
                custom_structs,
                constants,
            )
        else:
            raise InvalidTypeException("Invalid base type: " + item.id, item)
    # Units, e.g. num (1/sec) or contracts
github vyperlang / vyper / vyper / signatures / interface.py View on Github external
elts=[
                    abi_type_to_ast(a['type'])
                    for a in func['outputs']
                ]
            )

        decorator_list = [ast.Name(id='public')]
        if func['constant']:
            decorator_list.append(ast.Name(id='constant'))
        if func['payable']:
            decorator_list.append(ast.Name(id='payable'))

        sig = FunctionSignature.from_definition(
            code=ast.FunctionDef(
                name=func['name'],
                args=ast.arguments(args=args),
                decorator_list=decorator_list,
                returns=returns,
            ),
            custom_units=set(),
            custom_structs=dict(),
            constants=Constants()
        )
        sigs.append(sig)
    return sigs
github vyperlang / vyper / vyper / parser / constants.py View on Github external
def add_constant(self, item, global_ctx):
        args = item.annotation.args
        if not item.value:
            raise StructureException('Constants must express a value!', item)

        is_correctly_formatted_struct = (
            len(args) == 1 and isinstance(args[0], (ast.Subscript, ast.Name, ast.Call))
        ) and item.target

        if is_correctly_formatted_struct:
            c_name = item.target.id
            if global_ctx.is_valid_varname(c_name, item):
                self._constants[c_name] = self.unroll_constant(item, global_ctx)
                self._constants_ast[c_name] = item.value
            # TODO: the previous `if` has no else which will result in this
            # *silently* existing without doing anything. is this intended
            # behavior.
        else:
            raise StructureException('Incorrectly formatted struct', item)
github vyperlang / vyper / vyper / parser / external_call.py View on Github external
location='storage',
            pos=getpos(stmt_expr),
            annotation='self.' + stmt_expr.func.value.attr,
        ))

        return external_contract_call(
            stmt_expr,
            context,
            contract_name,
            contract_address,
            pos=getpos(stmt_expr),
            value=value,
            gas=gas,
        )

    elif isinstance(stmt_expr.func.value, ast.Attribute) and stmt_expr.func.value.attr in context.globals:  # noqa: E501
        contract_name = context.globals[stmt_expr.func.value.attr].typ.unit
        var = context.globals[stmt_expr.func.value.attr]
        contract_address = unwrap_location(LLLnode.from_list(
            var.pos,
            typ=var.typ,
            location='storage',
            pos=getpos(stmt_expr),
            annotation='self.' + stmt_expr.func.value.attr,
        ))

        return external_contract_call(
            stmt_expr,
            context,
            contract_name,
            contract_address,
            pos=getpos(stmt_expr),
github vyperlang / vyper / vyper / signatures / function_signature.py View on Github external
))

            if isinstance(parsed_type, ByteArrayLike):
                mem_pos += 32
            else:
                mem_pos += get_size_of_type(parsed_type) * 32

        const = constant_override
        payable = False
        private = False
        public = False
        nonreentrant_key = ''

        # Update function properties from decorators
        for dec in code.decorator_list:
            if isinstance(dec, ast.Name) and dec.id == "constant":
                const = True
            elif isinstance(dec, ast.Name) and dec.id == "payable":
                payable = True
            elif isinstance(dec, ast.Name) and dec.id == "private":
                private = True
            elif isinstance(dec, ast.Name) and dec.id == "public":
                public = True
            elif isinstance(dec, ast.Call) and dec.func.id == "nonreentrant":
                if nonreentrant_key:
                    raise StructureException(
                        "Only one @nonreentrant decorator allowed per function",
                        dec
                    )
                if dec.args and len(dec.args) == 1 and isinstance(dec.args[0], ast.Str) and dec.args[0].s:  # noqa: E501
                    nonreentrant_key = dec.args[0].s
                else:
github vyperlang / vyper / vyper / parser / stmt.py View on Github external
def _check_valid_assign(self, sub):
        if isinstance(self.stmt.annotation, ast.Call):  # unit style: num(wei)
            if self.stmt.annotation.func.id != sub.typ.typ and not sub.typ.is_literal:
                raise TypeMismatchException(
                    f'Invalid type, expected: {self.stmt.annotation.func.id}', self.stmt
                )
        elif isinstance(self.stmt.annotation, ast.Name) and self.stmt.annotation.id == 'bytes32':
            if isinstance(sub.typ, ByteArrayLike):
                if sub.typ.maxlen != 32:
                    raise TypeMismatchException(
                        'Invalid type, expected: bytes32. String is incorrect length.', self.stmt
                    )
                return
            elif isinstance(sub.typ, BaseType):
                if sub.typ.typ != 'bytes32':
                    raise TypeMismatchException('Invalid type, expected: bytes32', self.stmt)
                return
            else:
github vyperlang / vyper / vyper / parser / external_call.py View on Github external
def make_external_call(stmt_expr, context):
    from vyper.parser.expr import Expr
    value, gas = get_external_contract_keywords(stmt_expr, context)

    if isinstance(stmt_expr.func, ast.Attribute) and isinstance(stmt_expr.func.value, ast.Call):
        contract_name = stmt_expr.func.value.func.id
        contract_address = Expr.parse_value_expr(stmt_expr.func.value.args[0], context)

        return external_contract_call(
            stmt_expr,
            context,
            contract_name,
            contract_address,
            pos=getpos(stmt_expr),
            value=value,
            gas=gas,
        )

    elif isinstance(stmt_expr.func.value, ast.Attribute) and stmt_expr.func.value.attr in context.sigs:  # noqa: E501
        contract_name = stmt_expr.func.value.attr
        var = context.globals[stmt_expr.func.value.attr]
github vyperlang / vyper / vyper / parser / global_context.py View on Github external
def get_item_name_and_attributes(self, item, attributes):
        is_map_invocation = (
            (
                isinstance(item, ast.Call) and isinstance(item.func, ast.Name)
            ) and item.func.id == 'map'
        )

        if isinstance(item, ast.Name):
            return item.id, attributes
        elif isinstance(item, ast.AnnAssign):
            return self.get_item_name_and_attributes(item.annotation, attributes)
        elif isinstance(item, ast.Subscript):
            return self.get_item_name_and_attributes(item.value, attributes)
        elif is_map_invocation:
            if len(item.args) != 2:
                raise StructureException(
                    "Map type expects two type arguments map(type1, type2)", item.func
                )
            return self.get_item_name_and_attributes(item.args, attributes)
        # elif ist
        elif isinstance(item, ast.Call) and isinstance(item.func, ast.Name):
            attributes[item.func.id] = True
            # Raise for multiple args
            if len(item.args) != 1:
                raise StructureException(f"{item.func.id} expects one arg (the type)")
            return self.get_item_name_and_attributes(item.args[0], attributes)