Skip to content

wake.ir.declarations.function_definition module #

FunctionDefinition class #

Bases: DeclarationAbc

Definition of a function.

Example

Free function (= outside of a contract):

1
2
3
function f(uint a, uint b) pure returns (uint) {
    return a + b;
}

Function inside a contract (lines 2-4):

1
2
3
4
5
contract C {
    function f(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}

Constructor (lines 3-5):

1
2
3
4
5
6
contract C {
    uint public x;
    constructor(uint a) public {
        x = a;
    }
}

Fallback function (line 2):

1
2
3
contract C {
    fallback() external payable {}
}

Receive function (line 2):

1
2
3
contract C {
    receive() external payable {}
}

Source code in wake/ir/declarations/function_definition.py
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class FunctionDefinition(DeclarationAbc):
    """
    Definition of a function.

    !!! example
        Free function (= outside of a contract):
        ```solidity linenums="1"
        function f(uint a, uint b) pure returns (uint) {
            return a + b;
        }
        ```

        Function inside a contract (lines 2-4):
        ```solidity linenums="1"
        contract C {
            function f(uint a, uint b) public pure returns (uint) {
                return a + b;
            }
        }
        ```

        Constructor (lines 3-5):
        ```solidity linenums="1"
        contract C {
            uint public x;
            constructor(uint a) public {
                x = a;
            }
        }
        ```

        Fallback function (line 2):
        ```solidity linenums="1"
        contract C {
            fallback() external payable {}
        }
        ```

        Receive function (line 2):
        ```solidity linenums="1"
        contract C {
            receive() external payable {}
        }
        ```
    """

    _ast_node: SolcFunctionDefinition
    _parent: Union[ContractDefinition, SourceUnit]
    _child_functions: Set[Union[FunctionDefinition, VariableDeclaration]]

    _implemented: bool
    _kind: FunctionKind
    _modifiers: List[ModifierInvocation]
    _parameters: ParameterList
    _return_parameters: ParameterList
    # __scope
    _state_mutability: StateMutability
    _virtual: bool
    _visibility: Visibility
    _base_functions: List[AstNodeId]
    _documentation: Optional[Union[StructuredDocumentation, str]]
    _function_selector: Optional[bytes]
    _body: Optional[Block]
    _overrides: Optional[OverrideSpecifier]

    def __init__(
        self, init: IrInitTuple, function: SolcFunctionDefinition, parent: SolidityAbc
    ):
        super().__init__(init, function, parent)
        self._child_functions = set()

        self._implemented = function.implemented
        self._kind = function.kind

        if self._kind == FunctionKind.CONSTRUCTOR:
            self._name = "constructor"
        elif self._kind == FunctionKind.FALLBACK:
            self._name = "fallback"
        elif self._kind == FunctionKind.RECEIVE:
            self._name = "receive"

        self._modifiers = [
            ModifierInvocation(init, modifier, self) for modifier in function.modifiers
        ]
        self._parameters = ParameterList(init, function.parameters, self)
        self._return_parameters = ParameterList(init, function.return_parameters, self)
        # self.__scope = function.scope
        self._state_mutability = function.state_mutability
        self._virtual = function.virtual
        self._visibility = function.visibility
        self._base_functions = (
            list(function.base_functions) if function.base_functions is not None else []
        )
        if function.documentation is None:
            self._documentation = None
        elif isinstance(function.documentation, SolcStructuredDocumentation):
            self._documentation = StructuredDocumentation(
                init, function.documentation, self
            )
        elif isinstance(function.documentation, str):
            self._documentation = function.documentation
        else:
            raise TypeError(
                f"Unknown type of documentation: {type(function.documentation)}"
            )
        self._function_selector = (
            bytes.fromhex(function.function_selector)
            if function.function_selector
            else None
        )

        if (
            self._visibility in {Visibility.PUBLIC, Visibility.EXTERNAL}
            and self._kind == FunctionKind.FUNCTION
        ):
            assert self._function_selector is not None
        else:
            assert self._function_selector is None

        self._body = Block(init, function.body, self) if function.body else None
        assert (self._body is not None) == self._implemented
        self._overrides = (
            OverrideSpecifier(init, function.overrides, self)
            if function.overrides
            else None
        )
        self._reference_resolver.register_post_process_callback(self._post_process)

    def __iter__(self) -> Iterator[IrAbc]:
        yield self
        for modifier in self._modifiers:
            yield from modifier
        yield from self._parameters
        yield from self._return_parameters
        if isinstance(self._documentation, StructuredDocumentation):
            yield from self._documentation
        if self._body is not None:
            yield from self._body
        if self._overrides is not None:
            yield from self._overrides

    def _post_process(self, callback_params: CallbackParams):
        base_functions = self.base_functions
        for base_function in base_functions:
            base_function._child_functions.add(self)
        self._reference_resolver.register_destroy_callback(
            self.source_unit.file, partial(self._destroy, base_functions)
        )

    def _destroy(self, base_functions: Tuple[FunctionDefinition, ...]) -> None:
        for base_function in base_functions:
            base_function._child_functions.remove(self)

    def _parse_name_location(self) -> Tuple[int, int]:
        IDENTIFIER = r"[a-zA-Z$_][a-zA-Z0-9$_]*"
        FUNCTION_RE = re.compile(
            r"^\s*function\s+(?P<name>{identifier})".format(
                identifier=IDENTIFIER
            ).encode("utf-8")
        )
        CONSTRUCTOR_RE = re.compile(r"^\s*(?P<name>constructor)".encode("utf-8"))
        FALLBACK_RE = re.compile(r"^\s*(?P<name>fallback)".encode("utf-8"))
        RECEIVE_RE = re.compile(r"^\s*(?P<name>receive)".encode("utf-8"))

        regexps = [FUNCTION_RE, CONSTRUCTOR_RE, FALLBACK_RE, RECEIVE_RE]
        matches = [regexp.match(self._source) for regexp in regexps]
        assert any(matches)

        byte_start = self._ast_node.src.byte_offset
        match = next(match for match in matches if match)
        return byte_start + match.start("name"), byte_start + match.end("name")

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

        processed_declarations: Set[Union[FunctionDefinition, VariableDeclaration]] = {
            self
        }
        declarations_queue: Deque[
            Union[FunctionDefinition, VariableDeclaration]
        ] = deque([self])

        while declarations_queue:
            declaration = declarations_queue.pop()
            if include_declarations:
                yield declaration
            yield from declaration.references

            if isinstance(declaration, (FunctionDefinition, VariableDeclaration)):
                for base_function in declaration.base_functions:
                    if base_function not in processed_declarations:
                        declarations_queue.append(base_function)
                        processed_declarations.add(base_function)
            if isinstance(declaration, FunctionDefinition):
                for child_function in declaration.child_functions:
                    if child_function not in processed_declarations:
                        declarations_queue.append(child_function)
                        processed_declarations.add(child_function)

    @property
    def parent(self) -> Union[ContractDefinition, SourceUnit]:
        """
        Returns:
            Parent IR node.
        """
        return self._parent

    @property
    @lru_cache(maxsize=2048)
    def canonical_name(self) -> str:
        from .contract_definition import ContractDefinition

        if isinstance(self._parent, ContractDefinition):
            return f"{self._parent.canonical_name}.{self._name}({','.join(param.type_name.type_string for param in self._parameters.parameters)})"
        return f"{self._name}({','.join(param.type_name.type_string for param in self._parameters.parameters)})"

    @property
    @lru_cache(maxsize=2048)
    def declaration_string(self) -> str:
        if self.kind == FunctionKind.CONSTRUCTOR:
            ret = "constructor"
        elif self.kind == FunctionKind.FALLBACK:
            ret = "fallback"
        elif self.kind == FunctionKind.RECEIVE:
            ret = "receive"
        else:
            ret = f"function {self.name}"
        ret += f"({', '.join(parameter.declaration_string for parameter in self.parameters.parameters)})"
        ret += f" {self.visibility}"
        ret += (
            f" {self.state_mutability}"
            if self.state_mutability != StateMutability.NONPAYABLE
            else ""
        )
        ret += f" virtual" if self.virtual else ""
        ret += (
            (
                f" override"
                + (
                    "("
                    + ", ".join(
                        override.source for override in self.overrides.overrides
                    )
                    + ")"
                    if len(self.overrides.overrides) > 0
                    else ""
                )
            )
            if self.overrides is not None
            else ""
        )
        ret += (
            (" " + " ".join(modifier.source for modifier in self.modifiers))
            if len(self.modifiers) > 0
            else ""
        )
        ret += (
            " returns ("
            + ", ".join(
                parameter.declaration_string
                for parameter in self.return_parameters.parameters
            )
            + ")"
            if len(self.return_parameters.parameters) > 0
            else ""
        )

        if isinstance(self.documentation, StructuredDocumentation):
            return (
                "/// "
                + "\n///".join(line for line in self.documentation.text.splitlines())
                + "\n"
                + ret
            )
        elif isinstance(self.documentation, str):
            return (
                "/// "
                + "\n///".join(line for line in self.documentation.splitlines())
                + "\n"
                + ret
            )
        else:
            return ret

    @property
    def implemented(self) -> bool:
        """
        Returns:
            `True` if the function [body][wake.ir.declarations.function_definition.FunctionDefinition.body] is not `None`, `False` otherwise.
        """
        return self._implemented

    @property
    def kind(self) -> FunctionKind:
        """
        Returns:
            Kind of the function.
        """
        return self._kind

    @property
    def modifiers(self) -> Tuple[ModifierInvocation, ...]:
        """
        Also includes base constructor invocations.
        !!! example
            Both `:::solidity ERC20Token("My Token", "MTK", msg.sender, 10 ** 18)` and `initializer` are listed by this property.
            ```solidity
            contract MyToken is ERC20Token {
                constructor() ERC20Token("My Token", "MTK", msg.sender, 10 ** 18) initializer {}
            }
            ```

        Returns:
            List of modifiers applied to the function.
        """
        return tuple(self._modifiers)

    @property
    def parameters(self) -> ParameterList:
        """
        Returns:
            Parameter list describing the function parameters.
        """
        return self._parameters

    @property
    def return_parameters(self) -> ParameterList:
        """
        Returns:
            Parameter list describing the function return parameters.
        """
        return self._return_parameters

    @property
    def state_mutability(self) -> StateMutability:
        """
        Returns:
            State mutability of the function.
        """
        return self._state_mutability

    @property
    def virtual(self) -> bool:
        """
        Returns:
            `True` if the function is virtual, `False` otherwise.
        """
        return self._virtual

    @property
    def visibility(self) -> Visibility:
        """
        Returns:
            Visibility of the function.
        """
        return self._visibility

    @property
    def base_functions(self) -> Tuple[FunctionDefinition, ...]:
        """
        !!! example
            `A.foo` on lines 6-8 lists `I.foo` on line 2 as a base function.

            `B.foo` on lines 12-14 lists only `A.foo` on lines 6-8 as a base function.
            ```solidity linenums="1"
            interface I {
                function foo() external returns(uint);
            }

            contract A is I {
                function foo() external pure virtual override returns(uint) {
                    return 1;
                }
            }

            contract B is A {
                function foo() external pure override returns(uint) {
                    return 2;
                }
            }
            ```

        !!! example
            `A1.foo` on lines 6-8 lists `I.foo` on line 2 as a base function.

            `A2.foo` on lines 12-14 lists `I.foo` on line 2 as a base function.

            `B.foo` on lines 18-20 lists `A1.foo` on lines 6-8 and `A2.foo` on lines 12-14 as base functions.
            ```solidity linenums="1"
            interface I {
                function foo() external returns(uint);
            }

            contract A1 is I {
                function foo() external pure virtual override returns(uint) {
                    return 1;
                }
            }

            contract A2 is I {
                function foo() external pure virtual override returns(uint) {
                    return 2;
                }
            }

            contract B is A1, A2 {
                function foo() external pure override(A1, A2) returns(uint) {
                    return 3;
                }
            }
            ```

        Returns:
            List of base functions overridden by this function.
        """
        base_functions = []
        for base_function_id in self._base_functions:
            base_function = self._reference_resolver.resolve_node(
                base_function_id, self.source_unit.cu_hash
            )
            assert isinstance(base_function, FunctionDefinition)
            base_functions.append(base_function)
        return tuple(base_functions)

    @property
    def child_functions(
        self,
    ) -> FrozenSet[Union[FunctionDefinition, VariableDeclaration]]:
        """
        Returns:
            Functions that list this function in their [base_functions][wake.ir.declarations.function_definition.FunctionDefinition.base_functions] property.
        """
        return frozenset(self._child_functions)

    @property
    def documentation(self) -> Optional[Union[StructuredDocumentation, str]]:
        """
        Of [StructuredDocumentation][wake.ir.meta.structured_documentation.StructuredDocumentation] type since Solidity 0.6.3.

        Returns:
            [NatSpec](https://solidity.readthedocs.io/en/latest/natspec-format.html) documentation string, if any.
        """
        return self._documentation

    @property
    def function_selector(self) -> Optional[bytes]:
        """
        Is only set for [Visibility.PUBLIC][wake.ir.enums.Visibility.PUBLIC] and [Visibility.EXTERNAL][wake.ir.enums.Visibility.EXTERNAL] functions of the [FunctionKind.FUNCTION][wake.ir.enums.FunctionKind.FUNCTION] kind.

        Returns:
            Selector of the function.
        """
        return self._function_selector

    @property
    def body(self) -> Optional[Block]:
        """
        Returns:
            Body of the function, if any.
        """
        return self._body

    @property
    def overrides(self) -> Optional[OverrideSpecifier]:
        """
        Returns override specifier as present in the source code.
        !!! example
            `I.foo` on line 2 does not have an override specifier.

            `A.foo` on lines 6-8 has an override specifier with the [overrides][wake.ir.meta.override_specifier.OverrideSpecifier.overrides] property empty.

            `B.foo` on lines 12-14 has an override specifier with the [overrides][wake.ir.meta.override_specifier.OverrideSpecifier.overrides] property containg one item referencing the contract `A` ([ContractDefinition][wake.ir.declarations.contract_definition.ContractDefinition]).
            ```solidity linenums="1"
            interface I {
                function foo() external returns(uint);
            }

            contract A is I {
                function foo() external pure virtual override returns(uint) {
                    return 1;
                }
            }

            contract B is A {
                function foo() external pure override(A) returns(uint) {
                    return 2;
                }
            }
            ```

        Returns:
            Override specifier, if any.
        """
        return self._overrides

    @property
    @lru_cache(maxsize=128)
    def cfg(self) -> ControlFlowGraph:
        """
        Raises:
            ValueError: If the function is not implemented.

        Returns:
            Control flow graph of the function.
        """
        from wake.analysis.cfg import ControlFlowGraph

        if not self._implemented:
            raise ValueError("Cannot create CFG for unimplemented function")

        return ControlFlowGraph(self)

    @property
    def references(
        self,
    ) -> FrozenSet[
        Union[
            Identifier,
            IdentifierPathPart,
            MemberAccess,
            UnaryOperation,
            BinaryOperation,
        ]
    ]:
        """
        Returns:
            Set of all IR nodes referencing this function.
        """
        from ..expressions.binary_operation import BinaryOperation
        from ..expressions.identifier import Identifier
        from ..expressions.member_access import MemberAccess
        from ..expressions.unary_operation import UnaryOperation
        from ..meta.identifier_path import IdentifierPathPart

        try:
            ref = next(
                ref
                for ref in self._references
                if not isinstance(
                    ref,
                    (
                        Identifier,
                        IdentifierPathPart,
                        MemberAccess,
                        UnaryOperation,
                        BinaryOperation,
                    ),
                )
            )
            raise AssertionError(f"Unexpected reference type: {ref}")
        except StopIteration:
            return frozenset(
                self._references
            )  # pyright: ignore reportGeneralTypeIssues

base_functions: Tuple[FunctionDefinition, ...] property #

Example

A.foo on lines 6-8 lists I.foo on line 2 as a base function.

B.foo on lines 12-14 lists only A.foo on lines 6-8 as a base function.

interface I {
    function foo() external returns(uint);
}

contract A is I {
    function foo() external pure virtual override returns(uint) {
        return 1;
    }
}

contract B is A {
    function foo() external pure override returns(uint) {
        return 2;
    }
}

Example

A1.foo on lines 6-8 lists I.foo on line 2 as a base function.

A2.foo on lines 12-14 lists I.foo on line 2 as a base function.

B.foo on lines 18-20 lists A1.foo on lines 6-8 and A2.foo on lines 12-14 as base functions.

interface I {
    function foo() external returns(uint);
}

contract A1 is I {
    function foo() external pure virtual override returns(uint) {
        return 1;
    }
}

contract A2 is I {
    function foo() external pure virtual override returns(uint) {
        return 2;
    }
}

contract B is A1, A2 {
    function foo() external pure override(A1, A2) returns(uint) {
        return 3;
    }
}

Returns:

Type Description
Tuple[FunctionDefinition, ...]

List of base functions overridden by this function.

body: Optional[Block] property #

Returns:

Type Description
Optional[Block]

Body of the function, if any.

cfg: ControlFlowGraph cached property #

Raises:

Type Description
ValueError

If the function is not implemented.

Returns:

Type Description
ControlFlowGraph

Control flow graph of the function.

child_functions: FrozenSet[Union[FunctionDefinition, VariableDeclaration]] property #

Returns:

Type Description
FrozenSet[Union[FunctionDefinition, VariableDeclaration]]

Functions that list this function in their base_functions property.

documentation: Optional[Union[StructuredDocumentation, str]] property #

Of StructuredDocumentation type since Solidity 0.6.3.

Returns:

Type Description
Optional[Union[StructuredDocumentation, str]]

NatSpec documentation string, if any.

function_selector: Optional[bytes] property #

Is only set for Visibility.PUBLIC and Visibility.EXTERNAL functions of the FunctionKind.FUNCTION kind.

Returns:

Type Description
Optional[bytes]

Selector of the function.

implemented: bool property #

Returns:

Type Description
bool

True if the function body is not None, False otherwise.

kind: FunctionKind property #

Returns:

Type Description
FunctionKind

Kind of the function.

modifiers: Tuple[ModifierInvocation, ...] property #

Also includes base constructor invocations.

Example

Both ERC20Token("My Token", "MTK", msg.sender, 10 ** 18) and initializer are listed by this property.

contract MyToken is ERC20Token {
    constructor() ERC20Token("My Token", "MTK", msg.sender, 10 ** 18) initializer {}
}

Returns:

Type Description
Tuple[ModifierInvocation, ...]

List of modifiers applied to the function.

overrides: Optional[OverrideSpecifier] property #

Returns override specifier as present in the source code.

Example

I.foo on line 2 does not have an override specifier.

A.foo on lines 6-8 has an override specifier with the overrides property empty.

B.foo on lines 12-14 has an override specifier with the overrides property containg one item referencing the contract A (ContractDefinition).

interface I {
    function foo() external returns(uint);
}

contract A is I {
    function foo() external pure virtual override returns(uint) {
        return 1;
    }
}

contract B is A {
    function foo() external pure override(A) returns(uint) {
        return 2;
    }
}

Returns:

Type Description
Optional[OverrideSpecifier]

Override specifier, if any.

parameters: ParameterList property #

Returns:

Type Description
ParameterList

Parameter list describing the function parameters.

parent: Union[ContractDefinition, SourceUnit] property #

Returns:

Type Description
Union[ContractDefinition, SourceUnit]

Parent IR node.

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

Returns:

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

Set of all IR nodes referencing this function.

return_parameters: ParameterList property #

Returns:

Type Description
ParameterList

Parameter list describing the function return parameters.

state_mutability: StateMutability property #

Returns:

Type Description
StateMutability

State mutability of the function.

virtual: bool property #

Returns:

Type Description
bool

True if the function is virtual, False otherwise.

visibility: Visibility property #

Returns:

Type Description
Visibility

Visibility of the function.