Skip to content

Abc

woke.ast.ir.abc.IrAbc class #

Bases: ABC

Base class for all IR nodes. Defines attributes and methods that are common to all Solidity and Yul IR nodes.

IR model is built on top of the AST (Abstract Syntax Tree) output of the solc compiler.

Each IR node is associated with a source code location in a source file. This means that each IR node has a corresponding (typically non-empty) Solidity or Yul source code.

Info

Yul IR nodes can have empty source code. In the case of Solidity IR nodes, this should not happen.

Source code in woke/ast/ir/abc.py
class IrAbc(ABC):
    """
    Base class for all IR nodes. Defines attributes and methods that are common to all Solidity and Yul IR nodes.

    IR model is built on top of the AST (Abstract Syntax Tree) output of the [solc compiler](https://docs.soliditylang.org/en/latest/using-the-compiler.html).

    Each IR node is associated with a [source code location][woke.ast.ir.abc.IrAbc.byte_location] in a [source file][woke.ast.ir.abc.IrAbc.file].
    This means that each IR node has a corresponding (typically non-empty) Solidity or Yul [source code][woke.ast.ir.abc.IrAbc.source].

    !!! info
        Yul IR nodes can have empty source code. In the case of Solidity IR nodes, this should not happen.

    """

    _file: Path
    _source: bytes
    _ast_node: SolcOrYulNode
    _version_ranges: SolidityVersionRanges
    _parent: Optional[IrAbc]
    _depth: int
    _cu_hash: bytes
    _reference_resolver: ReferenceResolver

    def __init__(
        self, init: IrInitTuple, solc_node: SolcOrYulNode, parent: Optional[IrAbc]
    ):
        self._file = init.file
        self._ast_node = solc_node
        self._version_ranges = init.cu.versions
        self._parent = parent
        if self._parent is not None:
            self._depth = self._parent.ast_tree_depth + 1
        else:
            self._depth = 0
        self._cu_hash = init.cu.hash

        self._reference_resolver = init.reference_resolver

        source_start = solc_node.src.byte_offset
        source_end = source_start + solc_node.src.byte_length
        self._source = init.source[source_start:source_end]
        if source_start != source_end:
            init.interval_tree[source_start:source_end] = self

    def __iter__(self) -> Iterator[IrAbc]:
        """
        Yields:
            Self and (recursively) all child IR nodes.
        """
        yield self

    @property
    @abstractmethod
    def parent(self) -> Optional[IrAbc]:
        """
        The parent node of this node. Can only be `None` for the root ([Source unit][woke.ast.ir.meta.source_unit.SourceUnit]) node.

        Returns:
            Parent node of this node.
        """
        ...

    @property
    def file(self) -> Path:
        """
        The absolute path to the source file that contains this IR node. For a given IR node, all child and parent nodes have the same file path.
        Returns:
            Absolute path to the file containing this node.
        """
        return self._file

    @property
    @abstractmethod
    def ast_node(self) -> SolcOrYulNode:
        ...

    @property
    def cu_hash(self) -> bytes:
        return self._cu_hash

    @property
    def version_ranges(self) -> SolidityVersionRanges:
        """
        !!! example
            ```python
            if "0.8.0" in node.version_ranges:
                print("The given file can be compiled with solc 0.8.0")
            ```
        Returns:
            Object listing all `solc` versions that can be used to compile the file containing this node.
        """
        return self._version_ranges

    @property
    def ast_tree_depth(self) -> int:
        """
        The depth of this node in the AST tree. The root node ([Source unit][woke.ast.ir.meta.source_unit.SourceUnit]) of each file has depth 0. Direct child nodes of a `node` have depth `{node}.ast_tree_depth + 1`.

        !!! tip
            Woke uses [interval trees](https://github.com/chaimleib/intervaltree) to get a list of all IR nodes at a given byte offset in a given file. This property can be used to sort these nodes by their depth in the AST tree and (for example) to choose the most nested one.

        Returns:
            Depth of this node in the AST tree, starting from 0.

        """
        return self._depth

    @property
    def byte_location(self) -> Tuple[int, int]:
        """
        The start and end byte offsets of this node in the source file. `{node}.byte_location[0]` is the start byte offset, `{node}.byte_location[1]` is the end byte offset.

        `{node}.byte_location[1]` is always greater than or equal to `{node}.byte_location[0]`.

        The byte location of a child node is typically a subrange of the byte location of its parent node.

        !!! info
            This is not true for [Structured documentation][woke.ast.ir.meta.structured_documentation.StructuredDocumentation], where documentation strings must be located before a declaration.

        Returns:
            Tuple of the start and end byte offsets of this node in the source file.
        """
        return (
            self._ast_node.src.byte_offset,
            self._ast_node.src.byte_offset + self._ast_node.src.byte_length,
        )

    @property
    def source(self) -> str:
        """
        UTF-8 decoded source code from the [source file][woke.ast.ir.abc.IrAbc.file] at the [byte offset][woke.ast.ir.abc.IrAbc.byte_location] of this node.
        Returns:
            Solidity or Yul source code corresponding to this node.
        """
        return self._source.decode("utf-8")

ast_tree_depth: int property #

The depth of this node in the AST tree. The root node (Source unit) of each file has depth 0. Direct child nodes of a node have depth {node}.ast_tree_depth + 1.

Tip

Woke uses interval trees to get a list of all IR nodes at a given byte offset in a given file. This property can be used to sort these nodes by their depth in the AST tree and (for example) to choose the most nested one.

Returns:

Type Description
int

Depth of this node in the AST tree, starting from 0.

byte_location: Tuple[int, int] property #

The start and end byte offsets of this node in the source file. {node}.byte_location[0] is the start byte offset, {node}.byte_location[1] is the end byte offset.

{node}.byte_location[1] is always greater than or equal to {node}.byte_location[0].

The byte location of a child node is typically a subrange of the byte location of its parent node.

Info

This is not true for Structured documentation, where documentation strings must be located before a declaration.

Returns:

Type Description
Tuple[int, int]

Tuple of the start and end byte offsets of this node in the source file.

file: Path property #

The absolute path to the source file that contains this IR node. For a given IR node, all child and parent nodes have the same file path.

Returns:

Type Description
Path

Absolute path to the file containing this node.

parent: Optional[IrAbc] abstractmethod property #

The parent node of this node. Can only be None for the root (Source unit) node.

Returns:

Type Description
Optional[IrAbc]

Parent node of this node.

source: str property #

UTF-8 decoded source code from the source file at the byte offset of this node.

Returns:

Type Description
str

Solidity or Yul source code corresponding to this node.

version_ranges: SolidityVersionRanges property #

Example

if "0.8.0" in node.version_ranges:
    print("The given file can be compiled with solc 0.8.0")

Returns:

Type Description
SolidityVersionRanges

Object listing all solc versions that can be used to compile the file containing this node.

__iter__() #

Yields:

Type Description
Iterator[IrAbc]

Self and (recursively) all child IR nodes.

Source code in woke/ast/ir/abc.py
def __iter__(self) -> Iterator[IrAbc]:
    """
    Yields:
        Self and (recursively) all child IR nodes.
    """
    yield self

woke.ast.ir.abc.SolidityAbc class #

Bases: IrAbc, ABC

Abstract base class for all Solidity IR nodes.

Source code in woke/ast/ir/abc.py
class SolidityAbc(IrAbc, ABC):
    """
    Abstract base class for all Solidity IR nodes.
    """

    _ast_node: SolcNode

    def __init__(
        self, init: IrInitTuple, solc_node: SolcNode, parent: Optional[SolidityAbc]
    ):
        super().__init__(init, solc_node, parent)
        self._reference_resolver.register_node(self, solc_node.id, self._cu_hash)

    @property
    def ast_node(self) -> SolcNode:
        return self._ast_node

    @property
    def ast_node_id(self) -> int:
        return self._ast_node.id

woke.ast.ir.yul.abc.YulAbc class #

Bases: IrAbc, ABC

Abstract base class for all Yul IR nodes.

Source code in woke/ast/ir/yul/abc.py
class YulAbc(IrAbc, ABC):
    """
    Abstract base class for all Yul IR nodes.
    """

    _ast_node: YulNode

    def __iter__(self) -> Iterator[YulAbc]:
        yield self

    @property
    def ast_node(self) -> YulNode:
        return self._ast_node

    @property
    # @abstractmethod
    def modifies_state(self) -> Set[Tuple[IrAbc, ModifiesStateFlag]]:
        return set()  # TODO

woke.ast.ir.declaration.abc.DeclarationAbc class #

Bases: SolidityAbc, ABC

Abstract base class for all Solidity declarations.

Source code in woke/ast/ir/declaration/abc.py
class DeclarationAbc(SolidityAbc, ABC):
    """
    Abstract base class for all Solidity declarations.
    """

    _name: str
    _name_location: Optional[Tuple[int, int]]
    _references: Set[
        Union[
            Identifier,
            IdentifierPathPart,
            MemberAccess,
            ExternalReference,
            UnaryOperation,
            BinaryOperation,
        ]
    ]

    def __init__(
        self, init: IrInitTuple, solc_node: SolcDeclarationUnion, parent: SolidityAbc
    ):
        super().__init__(init, solc_node, parent)
        self._name = solc_node.name
        if solc_node.name_location is None or solc_node.name_location.byte_offset < 0:
            self._name_location = None
        else:
            self._name_location = (
                solc_node.name_location.byte_offset,
                solc_node.name_location.byte_offset
                + solc_node.name_location.byte_length,
            )
        self._references = set()

    def register_reference(
        self,
        reference: Union[
            Identifier,
            IdentifierPathPart,
            MemberAccess,
            ExternalReference,
            UnaryOperation,
            BinaryOperation,
        ],
    ):
        self._references.add(reference)

    def unregister_reference(
        self,
        reference: Union[
            Identifier,
            IdentifierPathPart,
            MemberAccess,
            ExternalReference,
            UnaryOperation,
            BinaryOperation,
        ],
    ):
        self._references.remove(reference)

    def get_all_references(
        self, include_declarations: bool
    ) -> Iterator[
        Union[
            DeclarationAbc,
            Union[
                Identifier,
                IdentifierPathPart,
                MemberAccess,
                ExternalReference,
                UnaryOperation,
                BinaryOperation,
            ],
        ]
    ]:
        if include_declarations:
            yield self
        yield from self.references

    @abstractmethod
    def _parse_name_location(self) -> Tuple[int, int]:
        ...

    @property
    def name(self) -> str:
        """
        Returns:
            User-defined name of the declared object.
        """
        return self._name

    @property
    @abstractmethod
    def canonical_name(self) -> str:
        """
        !!! example
            `ContractName.StructName.FieldName` in the case of the `FieldName` [VariableDeclaration][woke.ast.ir.declaration.variable_declaration.VariableDeclaration] declaration in the following example:
            ```solidity
            contract ContractName {
                struct StructName {
                    uint FieldName;
                }
            }
            ```
        Returns:
            Canonical name of the declared object.
        """
        ...

    @property
    @abstractmethod
    def declaration_string(self) -> str:
        """
        Declaration string that can be used for example in LSP hover. Does not include the declaration body, if any.
        Does not need to match the actual declaration string in the source code (may use a different order of keywords, for example).
        !!! example
            `:::solidity function foo(uint a, uint b) public payable virtual onlyOwner returns (uint)` of the [FunctionDefinition][woke.ast.ir.declaration.function_definition.FunctionDefinition] declaration in the following example:
            ```solidity
            function foo(uint a, uint b) public onlyOwner virtual payable returns( uint ) {
                return a + b;
            }
            ```
        Returns:
            String representation of the declaration.
        """
        ...

    @property
    def name_location(self) -> Tuple[int, int]:
        """
        Similar to [byte_location][woke.ast.ir.abc.IrAbc.byte_location], but returns the location of the declaration name in the source code.
        Returns:
            Tuple of the start and end byte offsets of the declaration name in the source code.
        """
        if self._name_location is None:
            self._name_location = self._parse_name_location()
        return self._name_location

    @property
    def references(
        self,
    ) -> FrozenSet[
        Union[
            Identifier,
            IdentifierPathPart,
            MemberAccess,
            ExternalReference,
            UnaryOperation,
            BinaryOperation,
        ]
    ]:
        """
        Returns:
            Set of all IR nodes referencing to this declaration.
        """
        return frozenset(self._references)

canonical_name: str abstractmethod property #

Example

ContractName.StructName.FieldName in the case of the FieldName VariableDeclaration declaration in the following example:

contract ContractName {
    struct StructName {
        uint FieldName;
    }
}

Returns:

Type Description
str

Canonical name of the declared object.

declaration_string: str abstractmethod property #

Declaration string that can be used for example in LSP hover. Does not include the declaration body, if any. Does not need to match the actual declaration string in the source code (may use a different order of keywords, for example).

Example

function foo(uint a, uint b) public payable virtual onlyOwner returns (uint) of the FunctionDefinition declaration in the following example:

function foo(uint a, uint b) public onlyOwner virtual payable returns( uint ) {
    return a + b;
}

Returns:

Type Description
str

String representation of the declaration.

name: str property #

Returns:

Type Description
str

User-defined name of the declared object.

name_location: Tuple[int, int] property #

Similar to byte_location, but returns the location of the declaration name in the source code.

Returns:

Type Description
Tuple[int, int]

Tuple of the start and end byte offsets of the declaration name in the source code.

references: FrozenSet[Union[Identifier, IdentifierPathPart, MemberAccess, ExternalReference, UnaryOperation, BinaryOperation]] property #

Returns:

Type Description
FrozenSet[Union[Identifier, IdentifierPathPart, MemberAccess, ExternalReference, UnaryOperation, BinaryOperation]]

Set of all IR nodes referencing to this declaration.

woke.ast.ir.expression.abc.ExpressionAbc class #

Bases: SolidityAbc, ABC

Abstract base class for all IR expression nodes.

Something that has a value.

Source code in woke/ast/ir/expression/abc.py
class ExpressionAbc(SolidityAbc, ABC):
    """
    Abstract base class for all IR expression nodes.
    > Something that has a value.
    """

    _type_descriptions: TypeDescriptionsModel

    def __init__(
        self, init: IrInitTuple, expression: SolcExpressionUnion, parent: SolidityAbc
    ):
        super().__init__(init, expression, parent)
        self._type_descriptions = expression.type_descriptions

    @staticmethod
    def from_ast(
        init: IrInitTuple, expression: SolcExpressionUnion, parent: SolidityAbc
    ) -> "ExpressionAbc":
        from .assignment import Assignment
        from .binary_operation import BinaryOperation
        from .conditional import Conditional
        from .elementary_type_name_expression import ElementaryTypeNameExpression
        from .function_call import FunctionCall
        from .function_call_options import FunctionCallOptions
        from .identifier import Identifier
        from .index_access import IndexAccess
        from .index_range_access import IndexRangeAccess
        from .literal import Literal
        from .member_access import MemberAccess
        from .new_expression import NewExpression
        from .tuple_expression import TupleExpression
        from .unary_operation import UnaryOperation

        if isinstance(expression, SolcAssignment):
            return Assignment(init, expression, parent)
        elif isinstance(expression, SolcBinaryOperation):
            return BinaryOperation(init, expression, parent)
        elif isinstance(expression, SolcConditional):
            return Conditional(init, expression, parent)
        elif isinstance(expression, SolcElementaryTypeNameExpression):
            return ElementaryTypeNameExpression(init, expression, parent)
        elif isinstance(expression, SolcFunctionCall):
            return FunctionCall(init, expression, parent)
        elif isinstance(expression, SolcFunctionCallOptions):
            return FunctionCallOptions(init, expression, parent)
        elif isinstance(expression, SolcIdentifier):
            return Identifier(init, expression, parent)
        elif isinstance(expression, SolcIndexAccess):
            return IndexAccess(init, expression, parent)
        elif isinstance(expression, SolcIndexRangeAccess):
            return IndexRangeAccess(init, expression, parent)
        elif isinstance(expression, SolcLiteral):
            return Literal(init, expression, parent)
        elif isinstance(expression, SolcMemberAccess):
            return MemberAccess(init, expression, parent)
        elif isinstance(expression, SolcNewExpression):
            return NewExpression(init, expression, parent)
        elif isinstance(expression, SolcTupleExpression):
            return TupleExpression(init, expression, parent)
        elif isinstance(expression, SolcUnaryOperation):
            return UnaryOperation(init, expression, parent)

    @property
    @lru_cache(maxsize=2048)
    def type(self) -> Optional[TypeAbc]:
        """
        Can be `None` in case of an [Identifier][woke.ast.ir.expression.identifier.Identifier] in an [ImportDirective][woke.ast.ir.meta.import_directive.ImportDirective].
        !!! example
            `Ownable` in the following example has no type information:
            ```solidity
            import { Ownable } from './Ownable.sol';
            ```
        Returns:
            Type of the expression.
        """
        if self._type_descriptions.type_identifier is None:
            return None

        type_identifier = StringReader(self._type_descriptions.type_identifier)
        ret = TypeAbc.from_type_identifier(
            type_identifier, self._reference_resolver, self.cu_hash
        )
        assert (
            len(type_identifier) == 0
        ), f"Failed to parse type_identifier: {self._type_descriptions.type_identifier}"
        return ret

    @property
    def type_string(self) -> Optional[str]:
        """
        !!! example
            `:::solidity function (uint256,uint256) returns (uint256)` in the case of the `foo` [Identifier][woke.ast.ir.expression.identifier.Identifier] in the `:::solidity foo(1, 2)` expression for the following function:
            ```solidity
            function foo(uint a, uint b) public onlyOwner payable virtual onlyOwner returns(uint) {
                return a + b;
            }
            ```

        Can be `None` in case of an [Identifier][woke.ast.ir.expression.identifier.Identifier] in an [ImportDirective][woke.ast.ir.meta.import_directive.ImportDirective].
        !!! example
            `Ownable` in the following example has no type information:
            ```solidity
            import { Ownable } from './Ownable.sol';
            ```
        Returns:
            User-friendly string describing the expression type.
        """
        return self._type_descriptions.type_string

    @property
    @abstractmethod
    def is_ref_to_state_variable(self) -> bool:
        """
        In many cases it may be useful to know if an [Assignment][woke.ast.ir.expression.assignment.Assignment] to an expression modifies a state variable or not.
        This may not be straightforward to determine, e.g. if the expression is a [MemberAccess][woke.ast.ir.expression.member_access.MemberAccess] or [IndexAccess][woke.ast.ir.expression.index_access.IndexAccess] to a state variable.
        Returns:
            `True` if the expression (possibly) is a reference to a state variable.
        """
        ...

    @property
    @abstractmethod
    def modifies_state(self) -> Set[Tuple[IrAbc, ModifiesStateFlag]]:
        """
        Returns:
            Set of child IR nodes (including `self`) that modify the blockchain state and flags describing how the state is modified.
        """
        ...

is_ref_to_state_variable: bool abstractmethod property #

In many cases it may be useful to know if an Assignment to an expression modifies a state variable or not. This may not be straightforward to determine, e.g. if the expression is a MemberAccess or IndexAccess to a state variable.

Returns:

Type Description
bool

True if the expression (possibly) is a reference to a state variable.

modifies_state: Set[Tuple[IrAbc, ModifiesStateFlag]] abstractmethod property #

Returns:

Type Description
Set[Tuple[IrAbc, ModifiesStateFlag]]

Set of child IR nodes (including self) that modify the blockchain state and flags describing how the state is modified.

type: Optional[TypeAbc] cached property #

Can be None in case of an Identifier in an ImportDirective.

Example

Ownable in the following example has no type information:

import { Ownable } from './Ownable.sol';

Returns:

Type Description
Optional[TypeAbc]

Type of the expression.

type_string: Optional[str] property #

Example

function (uint256,uint256) returns (uint256) in the case of the foo Identifier in the foo(1, 2) expression for the following function:

function foo(uint a, uint b) public onlyOwner payable virtual onlyOwner returns(uint) {
    return a + b;
}

Can be None in case of an Identifier in an ImportDirective.

Example

Ownable in the following example has no type information:

import { Ownable } from './Ownable.sol';

Returns:

Type Description
Optional[str]

User-friendly string describing the expression type.

woke.ast.ir.statement.abc.StatementAbc class #

Bases: SolidityAbc, ABC

Abstract base class for all Solidity statements.

Source code in woke/ast/ir/statement/abc.py
class StatementAbc(SolidityAbc, ABC):
    """
    Abstract base class for all Solidity statements.
    """

    _documentation: Optional[str]

    def __init__(
        self, init: IrInitTuple, statement: SolcStatementUnion, parent: SolidityAbc
    ):
        super().__init__(init, statement, parent)
        self._documentation = statement.documentation

    @staticmethod
    def from_ast(
        init: IrInitTuple, statement: SolcStatementUnion, parent: SolidityAbc
    ) -> "StatementAbc":
        from .block import Block
        from .break_statement import Break
        from .continue_statement import Continue
        from .do_while_statement import DoWhileStatement
        from .emit_statement import EmitStatement
        from .expression_statement import ExpressionStatement
        from .for_statement import ForStatement
        from .if_statement import IfStatement
        from .inline_assembly import InlineAssembly
        from .placeholder_statement import PlaceholderStatement
        from .return_statement import Return
        from .revert_statement import RevertStatement
        from .try_statement import TryStatement
        from .unchecked_block import UncheckedBlock
        from .variable_declaration_statement import VariableDeclarationStatement
        from .while_statement import WhileStatement

        if isinstance(statement, SolcBlock):
            return Block(init, statement, parent)
        elif isinstance(statement, SolcBreak):
            return Break(init, statement, parent)
        elif isinstance(statement, SolcContinue):
            return Continue(init, statement, parent)
        elif isinstance(statement, SolcDoWhileStatement):
            return DoWhileStatement(init, statement, parent)
        elif isinstance(statement, SolcEmitStatement):
            return EmitStatement(init, statement, parent)
        elif isinstance(statement, SolcExpressionStatement):
            return ExpressionStatement(init, statement, parent)
        elif isinstance(statement, SolcForStatement):
            return ForStatement(init, statement, parent)
        elif isinstance(statement, SolcIfStatement):
            return IfStatement(init, statement, parent)
        elif isinstance(statement, SolcInlineAssembly):
            return InlineAssembly(init, statement, parent)
        elif isinstance(statement, SolcPlaceholderStatement):
            return PlaceholderStatement(init, statement, parent)
        elif isinstance(statement, SolcReturn):
            return Return(init, statement, parent)
        elif isinstance(statement, SolcRevertStatement):
            return RevertStatement(init, statement, parent)
        elif isinstance(statement, SolcTryStatement):
            return TryStatement(init, statement, parent)
        elif isinstance(statement, SolcUncheckedBlock):
            return UncheckedBlock(init, statement, parent)
        elif isinstance(statement, SolcVariableDeclarationStatement):
            return VariableDeclarationStatement(init, statement, parent)
        elif isinstance(statement, SolcWhileStatement):
            return WhileStatement(init, statement, parent)
        assert False, f"Unknown statement type: {type(statement)}"

    @property
    @abstractmethod
    def parent(
        self,
    ) -> Union[
        Block,
        DoWhileStatement,
        ForStatement,
        IfStatement,
        UncheckedBlock,
        WhileStatement,
        FunctionDefinition,
        ModifierDefinition,
        TryCatchClause,
    ]:
        """
        Returns:
            Parent node of the statement.
        """
        ...

    @property
    @abstractmethod
    def modifies_state(self) -> Set[Tuple[IrAbc, ModifiesStateFlag]]:
        """
        Returns:
            Set of child IR nodes (including `self`) that modify the blockchain state and flags describing how the state is modified.
        """
        ...

    def statements_iter(self) -> Iterator[StatementAbc]:
        """
        Yields:
            Child statements of the statement (recursively) including `self`.
        """
        yield self

    @property
    def documentation(self) -> Optional[str]:
        """
        Statement documentation strings should be placed above the statement.
        Returns:
            [NatSpec](https://docs.soliditylang.org/en/latest/natspec-format.html) documentation string, if any.
        """
        return self._documentation

documentation: Optional[str] property #

Statement documentation strings should be placed above the statement.

Returns:

Type Description
Optional[str]

NatSpec documentation string, if any.

modifies_state: Set[Tuple[IrAbc, ModifiesStateFlag]] abstractmethod property #

Returns:

Type Description
Set[Tuple[IrAbc, ModifiesStateFlag]]

Set of child IR nodes (including self) that modify the blockchain state and flags describing how the state is modified.

parent: Union[Block, DoWhileStatement, ForStatement, IfStatement, UncheckedBlock, WhileStatement, FunctionDefinition, ModifierDefinition, TryCatchClause] abstractmethod property #

statements_iter() #

Yields:

Type Description
Iterator[StatementAbc]

Child statements of the statement (recursively) including self.

Source code in woke/ast/ir/statement/abc.py
def statements_iter(self) -> Iterator[StatementAbc]:
    """
    Yields:
        Child statements of the statement (recursively) including `self`.
    """
    yield self

woke.ast.ir.type_name.abc.TypeNameAbc class #

Bases: SolidityAbc, ABC

Abstract base class for all IR type name nodes.

Source code in woke/ast/ir/type_name/abc.py
class TypeNameAbc(SolidityAbc, ABC):
    """
    Abstract base class for all IR type name nodes.
    """

    _type_descriptions: TypeDescriptionsModel

    def __init__(
        self, init: IrInitTuple, type_name: SolcTypeNameUnion, parent: SolidityAbc
    ):
        super().__init__(init, type_name, parent)
        self._type_descriptions = type_name.type_descriptions

    @staticmethod
    def from_ast(
        init: IrInitTuple, type_name: SolcTypeNameUnion, parent: SolidityAbc
    ) -> TypeNameAbc:
        from .array_type_name import ArrayTypeName
        from .elementary_type_name import ElementaryTypeName
        from .function_type_name import FunctionTypeName
        from .mapping import Mapping
        from .user_defined_type_name import UserDefinedTypeName

        if isinstance(type_name, SolcArrayTypeName):
            return ArrayTypeName(init, type_name, parent)
        elif isinstance(type_name, SolcElementaryTypeName):
            return ElementaryTypeName(init, type_name, parent)
        elif isinstance(type_name, SolcFunctionTypeName):
            return FunctionTypeName(init, type_name, parent)
        elif isinstance(type_name, SolcMapping):
            return Mapping(init, type_name, parent)
        elif isinstance(type_name, SolcUserDefinedTypeName):
            return UserDefinedTypeName(init, type_name, parent)

    @property
    @abstractmethod
    def parent(
        self,
    ) -> Union[
        VariableDeclaration,
        UserDefinedValueTypeDefinition,
        ElementaryTypeNameExpression,
        NewExpression,
        UsingForDirective,
        ArrayTypeName,
        Mapping,
    ]:
        """
        Returns:
            Parent node of the type name.
        """
        ...

    @property
    @lru_cache(maxsize=2048)
    def type(
        self,
    ) -> Union[
        Array,
        Address,
        Bool,
        Int,
        UInt,
        Fixed,
        UFixed,
        String,
        Bytes,
        FixedBytes,
        Type,
        Function,
        Mapping,
        Struct,
        Enum,
        Contract,
        UserDefinedValueType,
    ]:
        """
        Returns:
            Type of the type name.
        """
        assert self._type_descriptions.type_identifier is not None

        type_identifier = StringReader(self._type_descriptions.type_identifier)
        ret = TypeAbc.from_type_identifier(
            type_identifier, self._reference_resolver, self.cu_hash
        )
        assert (
            len(type_identifier) == 0 and ret is not None
        ), f"Failed to parse type identifier: {self._type_descriptions.type_identifier}"
        assert isinstance(
            ret,
            (
                Array,
                Address,
                Bool,
                Int,
                UInt,
                Fixed,
                UFixed,
                String,
                Bytes,
                FixedBytes,
                Type,
                Function,
                Mapping,
                Struct,
                Enum,
                Contract,
                UserDefinedValueType,
            ),
        )
        return ret

    @property
    def type_string(self) -> str:
        """
        !!! example
            `:::solidity mapping(uint256 => int24[])` in the case of the `:::solidity mapping(uint => int24[])` type name in the following declaration:
            ```solidity
            mapping(uint => int24[]) map;
            ```

        Returns:
            User-friendly string describing the type name type.
        """
        assert self._type_descriptions.type_string is not None
        return self._type_descriptions.type_string

parent: Union[VariableDeclaration, UserDefinedValueTypeDefinition, ElementaryTypeNameExpression, NewExpression, UsingForDirective, ArrayTypeName, Mapping] abstractmethod property #

type: Union[Array, Address, Bool, Int, UInt, Fixed, UFixed, String, Bytes, FixedBytes, Type, Function, Mapping, Struct, Enum, Contract, UserDefinedValueType] cached property #

Returns:

Type Description
Union[Array, Address, Bool, Int, UInt, Fixed, UFixed, String, Bytes, FixedBytes, Type, Function, Mapping, Struct, Enum, Contract, UserDefinedValueType]

Type of the type name.

type_string: str property #

Example

mapping(uint256 => int24[]) in the case of the mapping(uint => int24[]) type name in the following declaration:

mapping(uint => int24[]) map;

Returns:

Type Description
str

User-friendly string describing the type name type.