Skip to content

wake.ir.declarations.modifier_definition module #

ModifierDefinition class #

Bases: DeclarationAbc

Definition of a modifier.

Example

modifier onlyOwner {
    require(msg.sender == owner);
    _;
}
Source code in wake/ir/declarations/modifier_definition.py
 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
class ModifierDefinition(DeclarationAbc):
    """
    Definition of a modifier.

    !!! example
        ```solidity
        modifier onlyOwner {
            require(msg.sender == owner);
            _;
        }
        ```
    """

    _ast_node: SolcModifierDefinition
    _parent: weakref.ReferenceType[ContractDefinition]
    _child_modifiers: Set[weakref.ReferenceType[ModifierDefinition]]

    _body: Optional[Block]
    _implemented: bool
    _parameters: ParameterList
    _virtual: bool
    _visibility: Visibility
    _base_modifiers: List[AstNodeId]
    _documentation: Optional[Union[StructuredDocumentation, str]]
    _overrides: Optional[OverrideSpecifier]

    def __init__(
        self, init: IrInitTuple, modifier: SolcModifierDefinition, parent: SolidityAbc
    ):
        super().__init__(init, modifier, parent)
        self._child_modifiers = set()

        self._body = Block(init, modifier.body, self) if modifier.body else None
        self._implemented = self._body is not None
        self._parameters = ParameterList(init, modifier.parameters, self)
        self._virtual = modifier.virtual
        self._visibility = modifier.visibility
        self._base_modifiers = (
            list(modifier.base_modifiers) if modifier.base_modifiers is not None else []
        )
        if modifier.documentation is None:
            self._documentation = None
        elif isinstance(modifier.documentation, SolcStructuredDocumentation):
            self._documentation = StructuredDocumentation(
                init, modifier.documentation, self
            )
        elif isinstance(modifier.documentation, str):
            self._documentation = modifier.documentation
        else:
            raise TypeError(
                f"Unknown type of documentation: {type(modifier.documentation)}"
            )
        self._overrides = (
            OverrideSpecifier(init, modifier.overrides, self)
            if modifier.overrides is not None
            else None
        )
        self._reference_resolver.register_post_process_callback(self._post_process)

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

    def __setstate__(self, state):
        super().__setstate__(state)
        self._child_modifiers = set()

    @classmethod
    def _strip_weakrefs(cls, state: dict):
        super()._strip_weakrefs(state)
        del state["_child_modifiers"]

    def _post_process(self, callback_params: CallbackParams):
        base_modifiers = self.base_modifiers
        for base_modifier in base_modifiers:
            base_modifier._child_modifiers.add(weakref.ref(self))
        self._reference_resolver.register_destroy_callback(
            self.source_unit.file, partial(self._destroy, base_modifiers)
        )

    def _destroy(self, base_modifiers: Tuple[ModifierDefinition, ...]) -> None:
        for base_modifier in base_modifiers:
            ref = next(m for m in base_modifier._child_modifiers if m() is self)
            base_modifier._child_modifiers.remove(ref)

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

        source = bytearray(self._source)
        _, stripped_sums = SoliditySourceParser.strip_comments(source)

        byte_start = self._ast_node.src.byte_offset
        match = MODIFIER_RE.match(source)
        assert match

        if len(stripped_sums) == 0:
            stripped = 0
        else:
            index = bisect([s[0] for s in stripped_sums], match.start("name"))
            if index == 0:
                stripped = 0
            else:
                stripped = stripped_sums[index - 1][1]

        return (
            byte_start + match.start("name") + stripped,
            byte_start + match.end("name") + stripped,
        )

    def get_all_references(
        self, include_declarations: bool
    ) -> Iterator[
        Union[
            DeclarationAbc,
            Identifier,
            IdentifierPathPart,
            MemberAccess,
            ExternalReference,
            UnaryOperation,
            BinaryOperation,
        ]
    ]:
        processed_declarations: Set[ModifierDefinition] = {self}
        declarations_queue: Deque[ModifierDefinition] = deque([self])

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

            for base_modifier in declaration.base_modifiers:
                if base_modifier not in processed_declarations:
                    declarations_queue.append(base_modifier)
                    processed_declarations.add(base_modifier)
            for child_modifier in declaration.child_modifiers:
                if child_modifier not in processed_declarations:
                    declarations_queue.append(child_modifier)
                    processed_declarations.add(child_modifier)

    @property
    def parent(self) -> ContractDefinition:
        """
        Returns:
            Parent IR node.
        """
        return super().parent

    @property
    def children(self) -> Iterator[IrAbc]:
        """
        Yields:
            Direct children of this node.
        """
        if self._body is not None:
            yield self._body
        yield self._parameters
        if isinstance(self._documentation, StructuredDocumentation):
            yield self._documentation
        if self._overrides is not None:
            yield self._overrides

    @property
    def canonical_name(self) -> str:
        return f"{self.parent.canonical_name}.{self._name}"

    @property
    @weak_self_lru_cache(maxsize=2048)
    def declaration_string(self) -> str:
        ret = f"modifier {self._name}"
        ret += (
            f"({', '.join(param.declaration_string for param in self.parameters.parameters)})"
            if len(self.parameters.parameters) > 0
            else ""
        )
        ret += " 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 ""
        )

        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 body(self) -> Optional[Block]:
        """
        Returns:
            Body of the modifier, if any.
        """
        return self._body

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

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

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

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

    @property
    def base_modifiers(self) -> Tuple[ModifierDefinition, ...]:
        """
        !!! example
            `B.mod` on lines 6-8 lists `A.mod` on line 2 as a base modifier.

            `C.mod` on lines 12-14 lists only `B.mod` on lines 6-8 as a base modifier.
            ```solidity linenums="1"
            abstract contract A {
                modifier mod virtual;
            }

            contract B is A {
                modifier mod virtual override {
                    _;
                }
            }

            contract C is B {
                modifier mod override {
                    _;
                }
            }
            ```

        !!! example
            `B1.mod` on lines 6-8 lists `A.mod` on line 2 as a base modifier.

            `B2.mod` on lines 12-14 lists `A.mod` on line 2 as a base modifier.

            `C.mod` on lines 18-20 lists `B1.mod` on lines 6-8 and `B2.mod` on lines 12-14 as base modifiers.
            ```solidity linenums="1"
            abstract contract A {
                modifier mod virtual;
            }

            contract B1 is A {
                modifier mod virtual override {
                    _;
                }
            }

            contract B2 is A {
                modifier mod virtual override {
                    _;
                }
            }

            contract C is B1, B2 {
                modifier mod override(B1, B2) {
                    _;
                }
            }
            ```

        Returns:
            List of base modifiers overridden by this modifier.
        """
        base_modifiers = []
        for base_modifier_id in self._base_modifiers:
            base_modifier = self._reference_resolver.resolve_node(
                base_modifier_id, self.source_unit.cu_hash
            )
            assert isinstance(base_modifier, ModifierDefinition)
            base_modifiers.append(base_modifier)
        return tuple(base_modifiers)

    @property
    def child_modifiers(self) -> FrozenSet[ModifierDefinition]:
        """
        Returns:
            Modifiers that list this modifier in their [base_modifiers][wake.ir.declarations.modifier_definition.ModifierDefinition.base_modifiers] property.
        """
        return frozenset(is_not_none(m()) for m in self._child_modifiers)

    @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://docs.soliditylang.org/en/latest/natspec-format.html) documentation string, if any.
        """
        return self._documentation

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

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

            `B2.mod` on lines 12-14 has an override specifier with the [overrides][wake.ir.meta.override_specifier.OverrideSpecifier.overrides] property empty.

            `C.mod` on lines 18-20 has an override specifier with the [overrides][wake.ir.meta.override_specifier.OverrideSpecifier.overrides] property containg two items referencing the contracts `B1` and `B2` ([ContractDefinition][wake.ir.declarations.contract_definition.ContractDefinition]).
            ```solidity linenums="1"
            abstract contract A {
                modifier mod virtual;
            }

            contract B1 is A {
                modifier mod virtual override {
                    _;
                }
            }

            contract B2 is A {
                modifier mod virtual override {
                    _;
                }
            }

            contract C is B1, B2 {
                modifier mod override(B1, B2) {
                    _;
                }
            }
            ```

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

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

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

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

        return ControlFlowGraph(self)

    @property
    def references(
        self,
    ) -> FrozenSet[Union[Identifier, IdentifierPathPart]]:
        """
        Until Solidity 0.8.0, modifiers were referenced in [ModifierInvocations][wake.ir.meta.modifier_invocation.ModifierInvocation]
        using [Identifiers][wake.ir.expressions.identifier.Identifier]. Version 0.8.0 started using [IdentifierPaths][wake.ir.meta.identifier_path.IdentifierPath] instead.

        Returns:
            Set of all IR nodes referencing this modifier.
        """
        from ..expressions.identifier import Identifier
        from ..meta.identifier_path import IdentifierPathPart

        refs = [is_not_none(r()) for r in self._references]

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

base_modifiers: Tuple[ModifierDefinition, ...] property #

Example

B.mod on lines 6-8 lists A.mod on line 2 as a base modifier.

C.mod on lines 12-14 lists only B.mod on lines 6-8 as a base modifier.

abstract contract A {
    modifier mod virtual;
}

contract B is A {
    modifier mod virtual override {
        _;
    }
}

contract C is B {
    modifier mod override {
        _;
    }
}

Example

B1.mod on lines 6-8 lists A.mod on line 2 as a base modifier.

B2.mod on lines 12-14 lists A.mod on line 2 as a base modifier.

C.mod on lines 18-20 lists B1.mod on lines 6-8 and B2.mod on lines 12-14 as base modifiers.

abstract contract A {
    modifier mod virtual;
}

contract B1 is A {
    modifier mod virtual override {
        _;
    }
}

contract B2 is A {
    modifier mod virtual override {
        _;
    }
}

contract C is B1, B2 {
    modifier mod override(B1, B2) {
        _;
    }
}

Returns:

Type Description
Tuple[ModifierDefinition, ...]

List of base modifiers overridden by this modifier.

body: Optional[Block] property #

Returns:

Type Description
Optional[Block]

Body of the modifier, if any.

cfg: ControlFlowGraph property #

Raises:

Type Description
ValueError

If the modifier is not implemented.

Returns:

Type Description
ControlFlowGraph

Control flow graph of the modifier.

child_modifiers: FrozenSet[ModifierDefinition] property #

Returns:

Type Description
FrozenSet[ModifierDefinition]

Modifiers that list this modifier in their base_modifiers property.

children: Iterator[IrAbc] property #

Yields:

Type Description
IrAbc

Direct children of this node.

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.

implemented: bool property #

Returns:

Type Description
bool

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

overrides: Optional[OverrideSpecifier] property #

Returns override specifier as present in the source code.

Example

A.mod on line 2 does not have an override specifier.

B1.mod on lines 6-8 has an override specifier with the overrides property empty.

B2.mod on lines 12-14 has an override specifier with the overrides property empty.

C.mod on lines 18-20 has an override specifier with the overrides property containg two items referencing the contracts B1 and B2 (ContractDefinition).

abstract contract A {
    modifier mod virtual;
}

contract B1 is A {
    modifier mod virtual override {
        _;
    }
}

contract B2 is A {
    modifier mod virtual override {
        _;
    }
}

contract C is B1, B2 {
    modifier mod override(B1, B2) {
        _;
    }
}

Returns:

Type Description
Optional[OverrideSpecifier]

Override specifier, if any.

parameters: ParameterList property #

Returns:

Type Description
ParameterList

Parameter list describing the modifier parameters.

parent: ContractDefinition property #

Returns:

Type Description
ContractDefinition

Parent IR node.

references: FrozenSet[Union[Identifier, IdentifierPathPart]] property #

Until Solidity 0.8.0, modifiers were referenced in ModifierInvocations using Identifiers. Version 0.8.0 started using IdentifierPaths instead.

Returns:

Type Description
FrozenSet[Union[Identifier, IdentifierPathPart]]

Set of all IR nodes referencing this modifier.

virtual: bool property #

Returns:

Type Description
bool

True if the modifier is virtual, False otherwise.

visibility: Visibility property #

Returns:

Type Description
Visibility

Visibility of the modifier.