Skip to content

Type checking for contract explicit storage base location #15528

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions libsolidity/analysis/ContractLevelChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,41 @@ bool ContractLevelChecker::check(ContractDefinition const& _contract)
checkBaseABICompatibility(_contract);
checkPayableFallbackWithoutReceive(_contract);
checkStorageSize(_contract);
checkStorageLayoutSpecifier(_contract);

return !Error::containsErrors(m_errorReporter.errors());
}

void ContractLevelChecker::checkStorageLayoutSpecifier(ContractDefinition const& _contract)
{
if (_contract.storageLayoutSpecifier())
{
solAssert(!_contract.isLibrary() && !_contract.isInterface());

if (_contract.abstract())
m_errorReporter.typeError(
7587_error,
_contract.storageLayoutSpecifier()->location(),
"Storage layout cannot be specified for abstract contracts."
);
}

for (auto const* ancestorContract: _contract.annotation().linearizedBaseContracts | ranges::views::reverse)
{
if (*ancestorContract == _contract)
continue;
if (ancestorContract->storageLayoutSpecifier())
m_errorReporter.typeError(
8894_error,
_contract.location(),
SecondarySourceLocation().append(
"Storage layout was already specified here.",
ancestorContract->storageLayoutSpecifier()->location()
),
"Storage layout can only be specified in the most derived contract."
);
Comment on lines +124 to +132
Copy link
Member

@cameel cameel Feb 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at test output, the errors generated by this may be a bit annoying. It reports an error for every specifier in the hierarchy of every contract, which may be a lot. Consider this example:

contract A      layout at 1 {}
contract B is A layout at 2 {}

contract C1 is B {}
contract C2 is A, B {}
contract C3 is B {}

contract D1 is C1 {}
contract D2 is C2 {}
contract D3 is C3 {}

You'll get 13 error messages here. I think it would be more useful to only report an error when a contract directly inherits from one with a layout specifier. The point where a fix needs to be applied is unlikely to be far from the specifier. It's either the specifier itself being applied to the wrong contract (secondary messages already point at this) or the first contract that inherits from it (that's what the primary message should point at). This would reduce the number of messages here to 5.

This should be very easy to implement simply by iterating over baseContracts() rather than the whole annotation().linearizedBaseContract. We could then point at the exact inheritance specifier that triggered the error rather than whole contract definition (baseContracts() contains specifiers rather than contract definitions, and we can easily report their locations).

We should also have the above as a test case.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in #15900.

}
}
void ContractLevelChecker::checkDuplicateFunctions(ContractDefinition const& _contract)
{
/// Checks that two functions with the same name defined in this contract have different
Expand Down
2 changes: 2 additions & 0 deletions libsolidity/analysis/ContractLevelChecker.h
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ class ContractLevelChecker
void checkPayableFallbackWithoutReceive(ContractDefinition const& _contract);
/// Error if the contract requires too much storage
void checkStorageSize(ContractDefinition const& _contract);
/// Checks if the storage layout specifier is properly assigned in the inheritance tree and not applied to an abstract contract
void checkStorageLayoutSpecifier(ContractDefinition const& _contract);

OverrideChecker m_overrideChecker;
langutil::ErrorReporter& m_errorReporter;
Expand Down
69 changes: 68 additions & 1 deletion libsolidity/analysis/PostTypeContractLevelChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,19 @@

#include <libsolidity/analysis/PostTypeContractLevelChecker.h>

#include <fmt/format.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/ASTUtils.h>
#include <libsolidity/ast/TypeProvider.h>
#include <libsolutil/FunctionSelector.h>
#include <liblangutil/ErrorReporter.h>

#include <limits>

using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::util;

bool PostTypeContractLevelChecker::check(SourceUnit const& _sourceUnit)
{
Expand All @@ -51,7 +57,7 @@ bool PostTypeContractLevelChecker::check(ContractDefinition const& _contract)
for (ErrorDefinition const* error: _contract.interfaceErrors())
{
std::string signature = error->functionType(true)->externalSignature();
uint32_t hash = util::selectorFromSignatureU32(signature);
uint32_t hash = selectorFromSignatureU32(signature);
// Fail if there is a different signature for the same hash.
if (!errorHashes[hash].empty() && !errorHashes[hash].count(signature))
{
Expand All @@ -67,5 +73,66 @@ bool PostTypeContractLevelChecker::check(ContractDefinition const& _contract)
errorHashes[hash][signature] = error->location();
}

if (auto const* layoutSpecifier = _contract.storageLayoutSpecifier())
checkStorageLayoutSpecifier(*layoutSpecifier);

return !Error::containsErrors(m_errorReporter.errors());
}

void PostTypeContractLevelChecker::checkStorageLayoutSpecifier(StorageLayoutSpecifier const& _storageLayoutSpecifier)
{
Expression const& baseSlotExpression = _storageLayoutSpecifier.baseSlotExpression();

if (!*baseSlotExpression.annotation().isPure)
{
// TODO: introduce and handle erc7201 as a builtin function
m_errorReporter.typeError(
1139_error,
baseSlotExpression.location(),
"The base slot of the storage layout must be a compile-time constant expression."
);
return;
}

auto const* baseSlotExpressionType = type(baseSlotExpression);
auto const* rationalType = dynamic_cast<RationalNumberType const*>(baseSlotExpressionType);
if (!rationalType)
{
m_errorReporter.typeError(
6396_error,
baseSlotExpression.location(),
"The base slot of the storage layout must evaluate to a rational number."
);
return;
}

if (rationalType->isFractional())
{
m_errorReporter.typeError(
1763_error,
baseSlotExpression.location(),
"The base slot of the storage layout must evaluate to an integer."
);
return;
}
solAssert(rationalType->value().denominator() == 1);

if (
rationalType->value().numerator() < 0 ||
rationalType->value().numerator() > std::numeric_limits<u256>::max()
)
{
m_errorReporter.typeError(
6753_error,
baseSlotExpression.location(),
fmt::format(
"The base slot of the storage layout evaluates to {}, which is outside the range of type uint256.",
formatNumberReadable(rationalType->value().numerator())
)
);
return;
}

solAssert(baseSlotExpressionType->isImplicitlyConvertibleTo(*TypeProvider::uint256()));
_storageLayoutSpecifier.annotation().baseSlot = u256(rationalType->value().numerator());
}
2 changes: 2 additions & 0 deletions libsolidity/analysis/PostTypeContractLevelChecker.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ class PostTypeContractLevelChecker
/// @returns true iff all checks passed. Note even if all checks passed, errors() can still contain warnings
bool check(ContractDefinition const& _contract);

void checkStorageLayoutSpecifier(StorageLayoutSpecifier const& _storageLayoutSpecifier);

langutil::ErrorReporter& m_errorReporter;
};

Expand Down
5 changes: 5 additions & 0 deletions libsolidity/ast/AST.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,11 @@ StorageLayoutSpecifier::StorageLayoutSpecifier(
solAssert(_location.contains(m_baseSlotExpression->location()));
}

StorageLayoutSpecifierAnnotation& StorageLayoutSpecifier::annotation() const
{
return initAnnotation<StorageLayoutSpecifierAnnotation>();
}

TypeNameAnnotation& TypeName::annotation() const
{
return initAnnotation<TypeNameAnnotation>();
Expand Down
2 changes: 2 additions & 0 deletions libsolidity/ast/AST.h
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,8 @@ class StorageLayoutSpecifier : public ASTNode
void accept(ASTConstVisitor& _visitor) const override;

Expression const& baseSlotExpression() const { solAssert(m_baseSlotExpression); return *m_baseSlotExpression; }
StorageLayoutSpecifierAnnotation& annotation() const override;

private:
ASTPointer<Expression> m_baseSlotExpression;
};
Expand Down
7 changes: 7 additions & 0 deletions libsolidity/ast/ASTAnnotations.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <libsolidity/ast/ASTEnums.h>
#include <libsolidity/ast/ExperimentalFeatures.h>

#include <libsolutil/Numeric.h>
#include <libsolutil/SetOnce.h>

#include <map>
Expand Down Expand Up @@ -173,6 +174,12 @@ struct ContractDefinitionAnnotation: TypeDeclarationAnnotation, StructurallyDocu
std::map<FunctionDefinition const*, uint64_t> internalFunctionIDs;
};

struct StorageLayoutSpecifierAnnotation: ASTAnnotation
{
// The evaluated value of the expression specifying the contract storage layout base
util::SetOnce<u256> baseSlot;
};

struct CallableDeclarationAnnotation: DeclarationAnnotation
{
/// The set of functions/modifiers/events this callable overrides.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
-
21 changes: 21 additions & 0 deletions test/cmdlineTests/storage_layout_already_defined_in_ancestor/err
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Error: Storage layout can only be specified in the most derived contract.
--> <stdin>:5:1:
|
5 | contract B is A {}
| ^^^^^^^^^^^^^^^^^^
Note: Storage layout was already specified here.
--> <stdin>:4:12:
|
4 | contract A layout at 0x1234 {}
| ^^^^^^^^^^^^^^^^

Error: Storage layout can only be specified in the most derived contract.
--> <stdin>:6:1:
|
6 | contract C layout at 0x1234 is B {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note: Storage layout was already specified here.
--> <stdin>:4:12:
|
4 | contract A layout at 0x1234 {}
| ^^^^^^^^^^^^^^^^
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-3.0
pragma solidity *;

contract A layout at 0x1234 {}
contract B is A {}
contract C layout at 0x1234 is B {}
23 changes: 23 additions & 0 deletions test/libsolidity/natspecJSON/storage_layout_specifier_no_doc.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
contract C
/// @notice this changes the base slot of the contract storage
layout at
/// @dev the expression must be in range of uint256
0x1234
{ }
// ====
// stopAfter: analysis
// ----
// ----
// :C devdoc
// {
// "kind": "dev",
// "methods": {},
// "version": 1
// }
//
// :C userdoc
// {
// "kind": "user",
// "methods": {},
// "version": 1
// }
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract C layout at abi.decode(abi.encode(42), (uint)) {}
// ----
// TypeError 6396: (21-55): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
abstract contract C layout at 42 { }
// ====
// stopAfter: parsing
// ----
// TypeError 7587: (20-32): Storage layout cannot be specified for abstract contracts.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract C layout at address(0x1234) {}
// ----
// TypeError 6396: (21-36): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
contract A {}

contract C layout at address(new A()) {}
contract D layout at uint160(address(this)) {}
// ----
// TypeError 1139: (36-52): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (77-99): The base slot of the storage layout must be a compile-time constant expression.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract C layout at [1, 2, 3] {}
// ----
// TypeError 6396: (21-30): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
contract C layout at 1 = 2 { }
// ----
// TypeError 4247: (21-22): Expression has to be an lvalue.
// TypeError 7407: (25-26): Type int_const 2 is not implicitly convertible to expected type int_const 1.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract C layout at ~uint(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {}
// ----
// TypeError 6396: (21-94): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract C layout at true {}
// ----
// TypeError 6396: (21-25): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
contract A layout at block.basefee { }
contract B layout at block.chainid { }
contract C layout at block.number { }
contract D layout at uint160(address(block.coinbase)) { }
contract E layout at block.prevrandao { }
contract F layout at uint(blockhash(0)) { }
contract G layout at msg.value { }
contract H layout at msg.sender { }
contract I layout at msg.data { }
contract J layout at tx.gasprice { }
contract K layout at uint160(tx.origin) { }
contract L layout at address(this).balance { }
contract M layout at uint(address(this).codehash) { }

// ====
// EVMVersion: >=paris
// ----
// TypeError 1139: (21-34): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (60-73): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (99-111): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (137-169): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (195-211): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (237-255): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (281-290): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (316-326): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (352-360): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (386-397): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (423-441): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (467-488): The base slot of the storage layout must be a compile-time constant expression.
// TypeError 1139: (514-542): The base slot of the storage layout must be a compile-time constant expression.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract C layout at bytes("ABCD").length {}
// ----
// TypeError 1139: (21-41): The base slot of the storage layout must be a compile-time constant expression.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
uint constant N = 100;
contract C layout at N / ~N {}
// ----
// TypeError 6396: (44-50): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
uint constant N = 100;
contract C layout at N / 0 {}
// ----
// TypeError 6396: (44-49): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
contract A {
uint constant x = 10;
}

contract C is A layout at A.x { }
// ----
// TypeError 6396: (68-71): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
contract at layout at 0x1234ABC { }
// ====
// stopAfter: parsing
// ----
// UnimplementedFeatureError 1834: (0-35): Code generation is not supported for contracts with specified storage layout base.
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
contract layout layout at 0x1234ABC { }
// ====
// stopAfter: parsing
// ----
// UnimplementedFeatureError 1834: (0-39): Code generation is not supported for contracts with specified storage layout base.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@ contract C layout at 0x1234 {
uint layout;
function at() public pure { }
}
// ====
// stopAfter: parsing
// ----
// UnimplementedFeatureError 1834: (0-82): Code generation is not supported for contracts with specified storage layout base.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
contract C layout at delete 2 { }
// ----
// TypeError 4247: (28-29): Expression has to be an lvalue.
// TypeError 9767: (21-29): Built-in unary operator delete cannot be applied to type int_const 2.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
contract A layout at 1 / 0 {}
// ----
// TypeError 2271: (21-26): Built-in binary operator / cannot be applied to types int_const 1 and int_const 0.
5 changes: 5 additions & 0 deletions test/libsolidity/syntaxTests/storageLayoutSpecifier/enum.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
enum Color {Red, Green, Blue}

contract C layout at Color.Red {}
// ----
// TypeError 6396: (52-61): The base slot of the storage layout must evaluate to a rational number.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
contract A {
function f() public pure {}
}

contract C is A layout at this.f.address {}
// ----
// TypeError 1139: (74-88): The base slot of the storage layout must be a compile-time constant expression.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
contract A {
function f() external pure {}
}

contract C layout at A.f { }
// ----
// TypeError 6396: (71-74): The base slot of the storage layout must evaluate to a rational number.
Loading