fix(solidity): link a call attached by using A for T to the function

`using SafeCast for uint256; x.toUint48()` and `using EnumerableSet for
EnumerableSet.AddressSet; _set.add(a)` call the library function with
the receiver as its first argument, but the extractor parked
`x.toUint48` as a qualified call on a type named `x`, which never
exists, so no such call got an edge. On OpenZeppelin v5.4.0, 0 of the
228 calls solc resolves through a `using` directive were linked.

Record the directives in scope: a contract's own (`using` is not
inherited since 0.7), the file-level ones, and the `global` ones on a
type's declaration, as `using` metadata on the contract and file nodes,
and give library and free functions their `first_param_type`. The
resolver binds `recv.f(args)`, when the receiver's declared type is
known (the receiver typing of the previous commit, a base contract's
state variable or the return type of `g` in `g().f()`), to a function
`f` that a directive whose target is `*` or that type attaches, with
args + 1 parameters and the receiver's type as its first. The type must
match exactly, including user-defined value types and library structs
(`Trace208` inside Checkpoints reads as `Checkpoints.Trace208`, as a
caller writes it). An operator binding (`using {eq as ==} for T`)
attaches no member.

Fail closed: no edge when the receiver's type is unknown, a directive's
library name is ambiguous, or more than one function fits.

OpenZeppelin v5.4.0 (solc 0.8.28 AST as the answer key): using-for calls
0/228 -> 180/228; solmate: 0/10 -> 6/10. No other kind changes. Most of
the rest are chained calls (`slot.asBoolean().tload()`), calls written
inside a `?:` that tree-sitter parses as the member's object, and 7
calls made inside `_name` functions that share a node with their
`name` counterpart (the `_name` / `name` id merge), which land on that
merged node until the id merge is fixed.

Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 7bd9be0bee)
This commit is contained in:
rohit-jsfreaky authored and safishamsi committed 2026-11-07 17:19:52 +00:00
1 parent 8f3ce12426
commit ebef2af2b9
2 files changed
+358 -3

No files matched your search

+160 -3
View File
@@ -303,6 +303,16 @@ def resolve_solidity_inherited_calls(
when the receiver's type is unknown, is not exactly one visible
contract/interface, when the name/arity is ambiguous, or when a public
state variable of that name (its getter) comes first.
A call attached by a ``using`` directive (``using SafeCast for uint256;
x.toUint48()``, ``using EnumerableSet for EnumerableSet.AddressSet;
_set.add(a)``) binds to the library or free function it attaches: the
directives of the caller's contract and file, and the ``global`` ones of
the receiver's type, whose target is ``*`` or the receiver's declared
type, offering a function of that name with one more parameter than the
call passes (the receiver) and the receiver's type as its first. Only a
single such function is linked; no edge when the receiver's type is
unknown, a directive's library is ambiguous, or two functions fit.
"""
calls = [
rc
@@ -324,6 +334,7 @@ def resolve_solidity_inherited_calls(
functions: dict[str, dict[str, list[tuple[str, Any]]]] = {}
modifiers: dict[str, dict[str, list[str]]] = {}
bases: dict[str, list[str]] = {}
using: dict[str, list[dict]] = {}
state_variables: dict[str, dict[str, str]] = {}
existing: set[tuple[Any, Any, Any]] = set()
for edge in all_edges:
@@ -334,6 +345,8 @@ def resolve_solidity_inherited_calls(
source_meta = meta(source)
if source_meta.get("language") != "solidity" or source_meta.get("kind") not in type_kinds:
continue
if isinstance(source_meta.get("using"), list):
using[source] = source_meta["using"]
if relation == "method":
member = meta(target)
name = str(node_by_id.get(target, {}).get("label", ""))
@@ -378,6 +391,11 @@ def resolve_solidity_inherited_calls(
types_by_file: dict[tuple[str, str], list[str]] = {}
file_by_id: dict[Any, str] = {}
imported: dict[str, set[str]] = {}
# `using` directives at file level, and the `global` ones by type.
file_using: dict[str, list[dict]] = {}
global_using: list[tuple[dict, str]] = []
# Free functions by (file, name), for `using {f} for T`.
free_functions: dict[tuple[str, str], list[str]] = {}
if any(rc["solidity_call"] in {"qualified", "member"} for rc in calls):
for node in all_nodes:
node_file = node.get("source_file")
@@ -385,6 +403,10 @@ def resolve_solidity_inherited_calls(
continue
if node.get("label") == Path(str(node_file)).name:
file_by_id[node.get("id")] = str(node_file)
directives = meta(node.get("id")).get("using")
if isinstance(directives, list):
file_using[str(node_file)] = directives
global_using.extend((d, str(node_file)) for d in directives if d.get("global"))
elif meta(node.get("id")).get("kind") in type_kinds:
types_by_file.setdefault((str(node_file), str(node.get("label", ""))), []).append(node["id"])
for edge in all_edges:
@@ -393,6 +415,15 @@ def resolve_solidity_inherited_calls(
imported_file = file_by_id.get(edge.get("target"))
if importer and imported_file:
imported.setdefault(importer, set()).add(imported_file)
elif (
edge.get("relation") == "contains"
and edge.get("source") in file_by_id
and meta(edge.get("target")).get("kind") == "function"
):
name = str(node_by_id.get(edge.get("target"), {}).get("label", ""))
free_functions.setdefault(
(file_by_id[edge["source"]], name[:-2] if name.endswith("()") else name), [],
).append(str(edge["target"]))
reachable_cache: dict[str, list[str]] = {}
@@ -484,6 +515,70 @@ def resolve_solidity_inherited_calls(
if len(scope) != 1 or meta(scope[0]).get("kind") not in {"contract", "interface"}:
return None
return find(linearization(scope[0]), name, rc.get("arity"), "member")
def visible_free_functions(scope_file: str, name: str) -> list[str]:
direct = free_functions.get((scope_file, name), []) + [
nid
for imported_file in sorted(imported.get(scope_file, set()))
for nid in free_functions.get((imported_file, name), [])
]
return direct or [
nid for reached in reachable(scope_file) for nid in free_functions.get((reached, name), [])
]
def attached_functions(directive: dict, scope_file: str, name: str) -> list[str] | None:
"""The functions named ``name`` that ``directive`` attaches, read in
``scope_file``; ``None`` when its library is ambiguous."""
if "library" in directive:
libraries = visible_types(scope_file, str(directive["library"]), transitive=True)
if not libraries:
return [] # a library outside the corpus
if len(libraries) != 1 or meta(libraries[0]).get("kind") != "library":
return None
return [nid for nid, _arity in functions.get(libraries[0], {}).get(name, [])]
attached: list[str] = []
for bound in directive.get("functions", []):
qualifier, _, function = str(bound).rpartition(".")
if function != name:
continue
if not qualifier:
attached.extend(visible_free_functions(scope_file, function))
continue
libraries = visible_types(scope_file, qualifier, transitive=True)
if len(libraries) > 1:
return None
if libraries:
attached.extend(nid for nid, _arity in functions.get(libraries[0], {}).get(function, []))
return attached
def using_member(rc: dict, name: str) -> str | None:
"""``recv.name()`` bound to the one function a ``using`` directive in
scope attaches to the receiver's type, if there is exactly one."""
caller = str(rc.get("caller_nid"))
caller_file = str(node_by_id.get(caller, {}).get("source_file", ""))
contract = owner.get(caller)
scoped = [(d, caller_file) for d in using.get(contract or "", [])] + [
(d, caller_file) for d in file_using.get(caller_file, []) if not d.get("global")
]
arity = rc.get("arity")
if not isinstance(arity, int):
return None
for type_name, _scope_file in receiver_types(rc):
directives = scoped + [(d, f) for d, f in global_using if d.get("for") == type_name]
found: set[str] = set()
for directive, scope_file in directives:
if directive.get("for") not in {"*", type_name}:
continue
attached = attached_functions(directive, scope_file, name)
if attached is None:
return None
found.update(
nid for nid in attached
if meta(nid).get("arity") == arity + 1
and meta(nid).get("first_param_type") == type_name
)
if found:
return next(iter(found)) if len(found) == 1 else None
return None
for rc in calls:
@@ -494,7 +589,9 @@ def resolve_solidity_inherited_calls(
kind = rc["solidity_call"]
contract = owner.get(caller)
if kind == "member":
target = typed_member(rc, name)
# A type's own member beats a `using`-attached function (Solidity
# resolution precedence), so try the typed receiver first.
target = typed_member(rc, name) or using_member(rc, name)
elif kind == "qualified":
# `Lib.f()` names its type, so it needs no owning contract (a free
# function calls libraries too).
@@ -502,10 +599,11 @@ def resolve_solidity_inherited_calls(
scope = visible_types(caller_file, str(rc.get("qualifier", "")))
# Fail closed when the name is not visible or is ambiguous. A
# name that is no type may be a base contract's state variable
# (`hevm.prank()`).
# (`hevm.prank()`), or a value with a `using`-attached function
# (`_checkpoints.push()`).
target = (
find(scope, name, rc.get("arity"), kind) if len(scope) == 1
else typed_member(rc, name) if not scope
else (typed_member(rc, name) or using_member(rc, name)) if not scope
else None
)
elif not contract:
@@ -805,6 +903,52 @@ def extract_solidity(path: Path) -> dict:
return f"{owner_name}.{head}{rest}"
return import_aliases.get(head, head) + rest
def using_directives(scope: Node, context: TypeContext) -> list[dict[str, Any]]:
"""The ``using A for T;`` / ``using A for *;`` / ``using {f, L.g} for
T [global];`` directives directly in ``scope`` (a contract body or the
file), for the resolver: ``{"for": T or "*", "library": A}`` or
``{"for": T, "functions": [..]}``, plus ``"global": True``. ``T`` is
qualified like a receiver type so the two compare equal. An operator
binding (`using {eq as ==} for T`) attaches no member and is skipped."""
directives: list[dict[str, Any]] = []
for directive in scope.named_children:
if directive.type != "using_directive":
continue
target = directive.child_by_field_name("source")
if target is None:
continue
item: dict[str, Any] = {
"for": "*" if target.type == "any_source_type"
else qualify(_normalize_type(_read_text(target, source)), context),
}
library = next((child for child in directive.named_children if child.type == "type_alias"), None)
if library is not None:
item["library"] = qualify(_normalize_type(_read_text(library, source)), file_context)
else:
functions = [
_normalize_type(_read_text(bound, source))
for alias in directive.named_children
if alias.type == "using_alias" and not any(child.type == "as" for child in alias.children)
for bound in alias.named_children
if bound.type == "user_defined_type"
]
if not functions:
continue
item["functions"] = [qualify(function, file_context) for function in functions]
if any(child.type == "global" for child in directive.children):
item["global"] = True
directives.append(item)
return directives
def first_parameter_type(callable_node: Node, context: TypeContext) -> dict[str, Any]:
"""``{"first_param_type": T}`` for a library or free function, the
type a ``using`` directive attaches it to (``x.f()`` passes ``x``)."""
first = next((child for child in callable_node.named_children if child.type == "parameter"), None)
type_node = first.child_by_field_name("type") if first is not None else None
if type_node is None:
return {}
return {"first_param_type": qualify(_normalize_type(_read_text(type_node, source)), context)}
def declared_types(callable_node: Node, context: TypeContext, inherited: VariableTypes) -> VariableTypes:
"""Parameter, return and local variable types visible in a function
or modifier, over ``inherited`` (the contract's state variables). A
@@ -916,6 +1060,12 @@ def extract_solidity(path: Path) -> dict:
return written, context
return None
file_using = using_directives(root, file_context)
if file_using:
# File-level directives apply to every contract and free function of
# the file; a `global` one to every use of its type.
nodes[0]["metadata"]["using"] = file_using
for declaration in root.named_children:
type_kind = _TYPE_DECLARATIONS.get(declaration.type)
if type_kind is None:
@@ -925,12 +1075,15 @@ def extract_solidity(path: Path) -> dict:
if name_node is None or body is None:
continue
type_name = _read_text(name_node, source)
contract_using = using_directives(body, contract_contexts[declaration.id])
type_id = add_node(
_underscore_salted_nid(_make_id(stem, type_kind, type_name), type_name, type_groups),
type_name,
declaration,
kind=type_kind,
callable_node=type_kind == "contract",
# Read by the resolver to bind `x.f()` through `using A for T`.
extra={"using": contract_using} if contract_using else None,
)
add_edge(file_id, type_id, "contains", declaration)
@@ -1147,6 +1300,8 @@ def extract_solidity(path: Path) -> dict:
for parameter in returns.named_children
if parameter.type == "parameter"
]
if type_kind == "library" and callable_kind == "function":
returned.update(first_parameter_type(member, type_context))
if len(return_types) == 1 and return_types[0] is not None:
# Read by the resolver for a receiver that is this function's
# result (`token().clock()`).
@@ -1321,6 +1476,8 @@ def extract_solidity(path: Path) -> dict:
declaration,
kind="function",
callable_node=True,
arity=arity,
extra=first_parameter_type(declaration, file_context),
)
add_edge(file_id, func_id, "contains", declaration)
free_functions.setdefault((name, arity), []).append(func_id)
+198
View File
@@ -662,6 +662,30 @@ def _typed_receiver_corpus(tmp_path: Path, vault: str) -> dict:
return extract(sorted(tmp_path.glob("*.sol")), cache_root=tmp_path)
_SAFE_CAST = (
"pragma solidity ^0.8.20;\n"
"library SafeCast {\n"
" function toUint48(uint256 value) internal pure returns (uint48) { return uint48(value); }\n"
" function toUint48(int256 value) internal pure returns (uint48) { return uint48(uint256(value)); }\n"
"}\n"
)
_SETS = (
"pragma solidity ^0.8.20;\n"
"library EnumerableSet {\n"
" struct AddressSet { address[] values; }\n"
" struct UintSet { uint256[] values; }\n"
" function add(AddressSet storage set, address value) internal returns (bool) { return true; }\n"
" function add(UintSet storage set, uint256 value) internal returns (bool) { return true; }\n"
"}\n"
)
def _using_corpus(tmp_path: Path, files: dict[str, str]) -> dict:
for name, text in files.items():
(tmp_path / name).write_text(text, encoding="utf-8")
return extract(sorted(tmp_path.glob("*.sol")), cache_root=tmp_path)
@_needs_solidity
def test_solidity_call_on_a_typed_state_variable_binds_the_interface_method(tmp_path):
# `token.transfer()` was parked as a qualified call on the type `token`,
@@ -731,6 +755,108 @@ def test_solidity_call_on_a_type_conversion_binds_through_the_base_contract(tmp_
}
@_needs_solidity
def test_solidity_using_for_binds_a_library_call_on_a_typed_value(tmp_path):
# `x.toUint48()` calls `SafeCast.toUint48(x)`, but it was parked as a
# qualified call on a type named `x`, so no `using` call got an edge
# (OpenZeppelin: 0 of 228 compiler-resolved calls). The overload is the
# one whose first parameter takes the receiver's type.
result = _using_corpus(tmp_path, {
"SafeCast.sol": _SAFE_CAST,
"Vault.sol": (
"pragma solidity ^0.8.20;\n"
'import {SafeCast} from "./SafeCast.sol";\n'
"contract Vault {\n"
" using SafeCast for uint256;\n"
" uint48 public at;\n"
" function touch(uint x) external { at = x.toUint48(); }\n"
"}\n"
),
})
assert _function_calls(result) == {("touch()", "toUint48()", "SafeCast.sol")}
toUint48 = [n for n in result["nodes"] if n["label"] == "toUint48()"]
target = next(e["target"] for e in result["edges"] if e["relation"] == "calls")
assert next(n for n in toUint48 if n["id"] == target)["metadata"]["first_param_type"] == "uint256"
@_needs_solidity
def test_solidity_using_for_binds_on_a_library_struct_through_a_mapping_and_a_base(tmp_path):
# `using EnumerableSet for EnumerableSet.AddressSet; _set.add(a)`: the
# struct is `AddressSet` inside the library and `EnumerableSet.AddressSet`
# outside it; the receiver may be a mapping element or a base contract's
# state variable.
result = _using_corpus(tmp_path, {
"EnumerableSet.sol": _SETS,
"Base.sol": (
"pragma solidity ^0.8.20;\n"
'import {EnumerableSet} from "./EnumerableSet.sol";\n'
"abstract contract Base { EnumerableSet.AddressSet internal _inherited; }\n"
),
"Roles.sol": (
"pragma solidity ^0.8.20;\n"
'import {EnumerableSet} from "./EnumerableSet.sol";\n'
'import {Base} from "./Base.sol";\n'
"contract Roles is Base {\n"
" using EnumerableSet for EnumerableSet.AddressSet;\n"
" EnumerableSet.AddressSet private _set;\n"
" mapping(bytes32 => EnumerableSet.AddressSet) private _members;\n"
" function direct(address a) external { _set.add(a); }\n"
" function element(bytes32 r, address a) external { _members[r].add(a); }\n"
" function inherited(address a) external { _inherited.add(a); }\n"
"}\n"
),
})
assert _function_calls(result) == {
("direct()", "add()", "EnumerableSet.sol"),
("element()", "add()", "EnumerableSet.sol"),
("inherited()", "add()", "EnumerableSet.sol"),
}
lines = {
next(n for n in result["nodes"] if n["id"] == e["target"])["source_location"]
for e in result["edges"] if e["relation"] == "calls"
}
assert lines == {"L5"} # add(AddressSet, ..), not add(UintSet, ..)
@_needs_solidity
def test_solidity_using_for_star_and_file_level_directives_bind(tmp_path):
# `using A for *` attaches every function whose first parameter takes the
# receiver; a file-level directive applies to every contract and free
# function of the file. A value type declared in a library reads as
# `Time.Delay` on both sides.
result = _using_corpus(tmp_path, {
"SafeCast.sol": _SAFE_CAST,
"Time.sol": (
"pragma solidity ^0.8.20;\n"
"library Time {\n"
" type Delay is uint112;\n"
" function get(Delay self) internal pure returns (uint32) { return 0; }\n"
"}\n"
),
"Vault.sol": (
"pragma solidity ^0.8.20;\n"
'import {SafeCast} from "./SafeCast.sol";\n'
'import {Time} from "./Time.sol";\n'
"using SafeCast for uint256;\n"
"function free(uint256 x) pure returns (uint48) { return x.toUint48(); }\n"
"contract Vault {\n"
" using Time for *;\n"
" Time.Delay private _delay;\n"
" function cast(uint256 x) external pure returns (uint48) { return x.toUint48(); }\n"
" function delay() external view returns (uint32) { return _delay.get(); }\n"
"}\n"
),
})
assert _function_calls(result) == {
("free()", "toUint48()", "SafeCast.sol"),
("cast()", "toUint48()", "SafeCast.sol"),
("delay()", "get()", "Time.sol"),
}
@_needs_solidity
def test_solidity_typed_receiver_through_a_reexport_a_base_state_variable_or_a_getter(tmp_path):
# OpenZeppelin imports IERC20 through ERC20.sol (`import {IERC20} from
@@ -763,6 +889,43 @@ def test_solidity_typed_receiver_through_a_reexport_a_base_state_variable_or_a_g
}
@_needs_solidity
def test_solidity_using_function_set_and_global_directive_bind(tmp_path):
# `using {add} for Price global;` on the type's declaration applies in
# every file that uses Price; `using {L.twice, half} for uint256;`
# attaches a library function and a free function.
result = _using_corpus(tmp_path, {
"Price.sol": (
"pragma solidity ^0.8.20;\n"
"type Price is uint128;\n"
"using {add, eq as ==} for Price global;\n"
"function add(Price a, Price b) pure returns (Price) { return a; }\n"
"function eq(Price a, Price b) pure returns (bool) { return true; }\n"
),
"Math.sol": (
"pragma solidity ^0.8.20;\n"
"library L { function twice(uint256 x) internal pure returns (uint256) { return 2 * x; } }\n"
"function half(uint256 x) pure returns (uint256) { return x / 2; }\n"
),
"Shop.sol": (
"pragma solidity ^0.8.20;\n"
'import {Price} from "./Price.sol";\n'
'import {L, half} from "./Math.sol";\n'
"contract Shop {\n"
" using {L.twice, half} for uint256;\n"
" function total(Price a, Price b) external pure returns (Price) { return a.add(b); }\n"
" function scale(uint256 x) external pure returns (uint256) { return x.twice().half() + x.half(); }\n"
"}\n"
),
})
assert _function_calls(result) == {
("total()", "add()", "Price.sol"),
("scale()", "twice()", "Math.sol"),
("scale()", "half()", "Math.sol"), # x.half(); x.twice().half() is chained, untyped
}
@_needs_solidity
def test_solidity_typed_receiver_fails_closed_when_ambiguous_or_untyped(tmp_path):
(tmp_path / "Over.sol").write_text(
@@ -807,6 +970,41 @@ def test_solidity_typed_receiver_fails_closed_when_ambiguous_or_untyped(tmp_path
assert _function_calls(result) == {("ok()", "g()", "Over.sol")}
@_needs_solidity
def test_solidity_using_for_fails_closed_when_unknown_ambiguous_or_out_of_scope(tmp_path):
result = _using_corpus(tmp_path, {
"SafeCast.sol": _SAFE_CAST,
"Dup.sol": (
"pragma solidity ^0.8.20;\n"
"library Dup { function toUint48(uint256 value) internal pure returns (uint48) { return 0; } }\n"
),
"Vault.sol": (
"pragma solidity ^0.8.20;\n"
'import {SafeCast} from "./SafeCast.sol";\n'
'import {Dup} from "./Dup.sol";\n'
"contract Other {\n"
" using SafeCast for uint256;\n" # not inherited by Vault (0.7+)
"}\n"
"contract Vault is Other {\n"
" using SafeCast for int256;\n"
" function run(uint256 x, int256 i, uint64 small) external {\n"
" x.toUint48();\n" # only Other attaches SafeCast to uint256
" small.toUint48();\n" # uint64 is no uint256: no exact match
" unknown.toUint48();\n" # no declared type
" }\n"
" function ok(int256 i) external pure returns (uint48) { return i.toUint48(); }\n"
"}\n"
"contract Both {\n"
" using SafeCast for uint256;\n"
" using Dup for uint256;\n"
" function two(uint256 x) external pure { x.toUint48(); }\n" # two libraries fit
"}\n"
),
})
assert _function_calls(result) == {("ok()", "toUint48()", "SafeCast.sol")}
@_needs_solidity
def test_solidity_fixture_uses_normal_extract_path(tmp_path):
result = extract([FIXTURE], cache_root=tmp_path)