solidity icon indicating copy to clipboard operation
solidity copied to clipboard

Introduce `readonly` modifier for internal function parameters in memory

Open jubeira opened this issue 5 months ago • 1 comments

Abstract

When calling a function with reference types (such as uint256[]), the function is allowed to mutate the contents of the parameter. There is currently no way to tell just by looking at the function definition whether the function mutates the contents of the reference or not; the only way is being explicit with the documentation or reading the actual code.

In other words, the compiler does not give the developer any hints on whether the memory parameter sent to a function will stay the same or not after the call. This ambiguity can be error prone in certain cases.

Motivation

Functions can be labeled as view or pure if they don't write / read storage. These labels provide very valuable information to the reader of the code at first sight.

It would be great to have an equivalent for memory parameters. In this case, the label would apply to the parameters, not the function.

For example, let's suppose a function that searches for an element in an array, and returns its index. This function shouldn't modify the given array, and could be defined as follows:

function getIndexOfToken(address[] readonly memory tokens, address token) internal pure returns (uint256 index);

If the function does alter the given parameters, it would be defined as it is today. For example, a function that sorts a given array of values, mutating its contents:

function sort(uint256[] memory values) internal pure;

readonly and const are two keywords that come to mind, but there could be other options as well (e.g. reusing view).

Specification

  • Introduce a new keyword that shall be used to (optionally) label memory parameters.
  • If a memory argument is readonly and the function attempts to modify its contents, throw an error when compiling.
  • If a memory argument is not specified as readonly and the function does not modify its contents, throw a warning when compiling.

Backwards Compatibility

Given that the readonly label would be optional, it wouldn't break backwards compatibility. For functions that don't use it and don't actually mutate the contents of the memory arguments, a warning would be issued but the code should still compile.

jubeira avatar Jan 31 '24 20:01 jubeira

This issue has been marked as stale due to inactivity for the last 90 days. It will be automatically closed in 7 days.

github-actions[bot] avatar May 01 '24 12:05 github-actions[bot]