id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,000
|
SolidityExecutionFramework.cpp
|
ethereum_solidity/test/libsolidity/SolidityExecutionFramework.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Framework for executing Solidity contracts and testing them against C++ implementation.
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <test/libsolidity/util/Common.h>
#include <liblangutil/DebugInfoSelection.h>
#include <libyul/Exceptions.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <boost/test/framework.hpp>
#include <cstdlib>
#include <iostream>
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::langutil;
using namespace solidity::test;
bytes SolidityExecutionFramework::multiSourceCompileContract(
std::map<std::string, std::string> const& _sourceCode,
std::optional<std::string> const& _mainSourceName,
std::string const& _contractName,
std::map<std::string, Address> const& _libraryAddresses
)
{
if (_mainSourceName.has_value())
solAssert(_sourceCode.find(_mainSourceName.value()) != _sourceCode.end(), "");
m_compiler.reset();
m_compiler.setSources(withPreamble(
_sourceCode,
solidity::test::CommonOptions::get().useABIEncoderV1 // _addAbicoderV1Pragma
));
m_compiler.setLibraries(_libraryAddresses);
m_compiler.setRevertStringBehaviour(m_revertStrings);
m_compiler.setEVMVersion(m_evmVersion);
m_compiler.setEOFVersion(m_eofVersion);
m_compiler.setOptimiserSettings(m_optimiserSettings);
m_compiler.setViaIR(m_compileViaYul);
m_compiler.setRevertStringBehaviour(m_revertStrings);
if (!m_appendCBORMetadata) {
m_compiler.setMetadataFormat(CompilerStack::MetadataFormat::NoMetadata);
}
m_compiler.setMetadataHash(m_metadataHash);
if (!m_compiler.compile())
{
// The testing framework expects an exception for
// "unimplemented" yul IR generation.
if (m_compileViaYul)
for (auto const& error: m_compiler.errors())
if (error->type() == langutil::Error::Type::CodeGenerationError)
BOOST_THROW_EXCEPTION(*error);
langutil::SourceReferenceFormatter{std::cerr, m_compiler, true, false}
.printErrorInformation(m_compiler.errors());
BOOST_ERROR("Compiling contract failed");
}
std::string contractName(_contractName.empty() ? m_compiler.lastContractName(_mainSourceName) : _contractName);
evmasm::LinkerObject obj = m_compiler.object(contractName);
BOOST_REQUIRE(obj.linkReferences.empty());
if (m_showMetadata)
std::cout << "metadata: " << m_compiler.metadata(contractName) << std::endl;
return obj.bytecode;
}
bytes SolidityExecutionFramework::compileContract(
std::string const& _sourceCode,
std::string const& _contractName,
std::map<std::string, Address> const& _libraryAddresses
)
{
return multiSourceCompileContract(
{{"", _sourceCode}},
std::nullopt,
_contractName,
_libraryAddresses
);
}
| 3,479
|
C++
|
.cpp
| 90
| 36.533333
| 112
| 0.784128
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,001
|
SolidityEndToEndTest.cpp
|
ethereum_solidity/test/libsolidity/SolidityEndToEndTest.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @author Gav Wood <g@ethdev.com>
* @date 2014
* Unit tests for the solidity expression compiler, testing the behaviour of the code.
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <test/Common.h>
#include <test/EVMHost.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/EVMVersion.h>
#include <libevmasm/Assembly.h>
#include <libsolutil/Keccak256.h>
#include <libsolutil/ErrorCodes.h>
#include <libyul/Exceptions.h>
#include <boost/test/unit_test.hpp>
#include <range/v3/view/transform.hpp>
#include <functional>
#include <numeric>
#include <string>
#include <tuple>
using namespace std::placeholders;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::test;
using namespace solidity::langutil;
#define ALSO_VIA_YUL(CODE) \
{ \
m_compileViaYul = false; \
RUN_AND_RERUN_WITH_OPTIMIZER_ON_STACK_ERROR(CODE) \
\
m_compileViaYul = true; \
reset(); \
RUN_AND_RERUN_WITH_OPTIMIZER_ON_STACK_ERROR(CODE) \
}
#define RUN_AND_RERUN_WITH_OPTIMIZER_ON_STACK_ERROR(CODE) \
{ \
try \
{ CODE } \
catch (yul::StackTooDeepError const&) \
{ \
if (m_optimiserSettings == OptimiserSettings::full()) \
throw; \
\
reset(); \
m_optimiserSettings = OptimiserSettings::full(); \
{ CODE } \
} \
}
namespace solidity::frontend::test
{
struct SolidityEndToEndTestExecutionFramework: public SolidityExecutionFramework
{
};
BOOST_FIXTURE_TEST_SUITE(SolidityEndToEndTest, SolidityEndToEndTestExecutionFramework)
BOOST_AUTO_TEST_CASE(creation_code_optimizer)
{
std::string codeC = R"(
contract C {
constructor(uint x) {
if (x == 0xFFFFFFFFFFFFFFFF42)
revert();
}
}
)";
std::string codeD = R"(
contract D {
function f() public pure returns (bytes memory) {
return type(C).creationCode;
}
}
)";
m_metadataHash = CompilerStack::MetadataHash::None;
ALSO_VIA_YUL({
bytes bytecodeC = compileContract(codeC);
reset();
compileAndRun(codeC + codeD);
ABI_CHECK(callContractFunction("f()"), encodeArgs(0x20, bytecodeC.size()) + encode(bytecodeC, false));
})
}
unsigned constexpr roundTo32(unsigned _num)
{
return (_num + 31) / 32 * 32;
}
BOOST_AUTO_TEST_CASE(exp_operator)
{
char const* sourceCode = R"(
contract test {
function f(uint a) public returns(uint d) { return 2 ** a; }
}
)";
compileAndRun(sourceCode);
testContractAgainstCppOnRange("f(uint256)", [](u256 const& a) -> u256 { return u256(1 << a.convert_to<int>()); }, 0, 16);
}
BOOST_AUTO_TEST_CASE(exp_zero)
{
char const* sourceCode = R"(
contract test {
function f(uint a) public returns(uint d) { return a ** 0; }
}
)";
compileAndRun(sourceCode);
testContractAgainstCppOnRange("f(uint256)", [](u256 const&) -> u256 { return u256(1); }, 0, 16);
}
/* TODO let's add this back when I figure out the correct type conversion.
BOOST_AUTO_TEST_CASE(conditional_expression_string_literal)
{
char const* sourceCode = R"(
contract test {
function f(bool cond) public returns (bytes32) {
return cond ? "true" : "false";
}
}
)";
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f(bool)", true), encodeArgs(string("true", 4)));
ABI_CHECK(callContractFunction("f(bool)", false), encodeArgs(string("false", 5)));
}
*/
BOOST_AUTO_TEST_CASE(recursive_calls)
{
char const* sourceCode = R"(
contract test {
function f(uint n) public returns(uint nfac) {
if (n <= 1) return 1;
else return n * f(n - 1);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
std::function<u256(u256)> recursive_calls_cpp = [&recursive_calls_cpp](u256 const& n) -> u256
{
if (n <= 1)
return 1;
else
return n * recursive_calls_cpp(n - 1);
};
testContractAgainstCppOnRange("f(uint256)", recursive_calls_cpp, 0, 5);
)
}
BOOST_AUTO_TEST_CASE(while_loop)
{
char const* sourceCode = R"(
contract test {
function f(uint n) public returns(uint nfac) {
nfac = 1;
uint i = 2;
while (i <= n) nfac *= i++;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto while_loop_cpp = [](u256 const& n) -> u256
{
u256 nfac = 1;
u256 i = 2;
while (i <= n)
nfac *= i++;
return nfac;
};
testContractAgainstCppOnRange("f(uint256)", while_loop_cpp, 0, 5);
)
}
BOOST_AUTO_TEST_CASE(do_while_loop)
{
char const* sourceCode = R"(
contract test {
function f(uint n) public returns(uint nfac) {
nfac = 1;
uint i = 2;
do { nfac *= i++; } while (i <= n);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto do_while_loop_cpp = [](u256 const& n) -> u256
{
u256 nfac = 1;
u256 i = 2;
do
{
nfac *= i++;
}
while (i <= n);
return nfac;
};
testContractAgainstCppOnRange("f(uint256)", do_while_loop_cpp, 0, 5);
)
}
BOOST_AUTO_TEST_CASE(do_while_loop_multiple_local_vars)
{
char const* sourceCode = R"(
contract test {
function f(uint x) public pure returns(uint r) {
uint i = 0;
do
{
uint z = x * 2;
if (z < 4) break;
else {
uint k = z + 1;
if (k < 8) {
x++;
continue;
}
}
if (z > 12) return 0;
x++;
i++;
} while (true);
return 42;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto do_while = [](u256 n) -> u256
{
u256 i = 0;
do
{
u256 z = n * 2;
if (z < 4) break;
else {
u256 k = z + 1;
if (k < 8) {
n++;
continue;
}
}
if (z > 12) return 0;
n++;
i++;
} while (true);
return 42;
};
testContractAgainstCppOnRange("f(uint256)", do_while, 0, 12);
)
}
BOOST_AUTO_TEST_CASE(nested_loops)
{
// tests that break and continue statements in nested loops jump to the correct place
char const* sourceCode = R"(
contract test {
function f(uint x) public returns(uint y) {
while (x > 1) {
if (x == 10) break;
while (x > 5) {
if (x == 8) break;
x--;
if (x == 6) continue;
return x;
}
x--;
if (x == 3) continue;
break;
}
return x;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto nested_loops_cpp = [](u256 n) -> u256
{
while (n > 1)
{
if (n == 10)
break;
while (n > 5)
{
if (n == 8)
break;
n--;
if (n == 6)
continue;
return n;
}
n--;
if (n == 3)
continue;
break;
}
return n;
};
testContractAgainstCppOnRange("f(uint256)", nested_loops_cpp, 0, 12);
)
}
BOOST_AUTO_TEST_CASE(nested_loops_multiple_local_vars)
{
// tests that break and continue statements in nested loops jump to the correct place
// and free local variables properly
char const* sourceCode = R"(
contract test {
function f(uint x) public returns(uint y) {
while (x > 0) {
uint z = x + 10;
uint k = z + 1;
if (k > 20) {
break;
uint p = 100;
k += p;
}
if (k > 15) {
x--;
continue;
uint t = 1000;
x += t;
}
while (k > 10) {
uint m = k - 1;
if (m == 10) return x;
return k;
uint h = 10000;
z += h;
}
x--;
break;
}
return x;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto nested_loops_cpp = [](u256 n) -> u256
{
while (n > 0)
{
u256 z = n + 10;
u256 k = z + 1;
if (k > 20) break;
if (k > 15) {
n--;
continue;
}
while (k > 10)
{
u256 m = k - 1;
if (m == 10) return n;
return k;
}
n--;
break;
}
return n;
};
testContractAgainstCppOnRange("f(uint256)", nested_loops_cpp, 0, 12);
)
}
BOOST_AUTO_TEST_CASE(for_loop_multiple_local_vars)
{
char const* sourceCode = R"(
contract test {
function f(uint x) public pure returns(uint r) {
for (uint i = 0; i < 12; i++)
{
uint z = x + 1;
if (z < 4) break;
else {
uint k = z * 2;
if (i + k < 10) {
x++;
continue;
}
}
if (z > 8) return 0;
x++;
}
return 42;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto for_loop = [](u256 n) -> u256
{
for (u256 i = 0; i < 12; i++)
{
u256 z = n + 1;
if (z < 4) break;
else {
u256 k = z * 2;
if (i + k < 10) {
n++;
continue;
}
}
if (z > 8) return 0;
n++;
}
return 42;
};
testContractAgainstCppOnRange("f(uint256)", for_loop, 0, 12);
)
}
BOOST_AUTO_TEST_CASE(nested_for_loop_multiple_local_vars)
{
char const* sourceCode = R"(
contract test {
function f(uint x) public pure returns(uint r) {
for (uint i = 0; i < 5; i++)
{
uint z = x + 1;
if (z < 3) {
break;
uint p = z + 2;
}
for (uint j = 0; j < 5; j++)
{
uint k = z * 2;
if (j + k < 8) {
x++;
continue;
uint t = z * 3;
}
x++;
if (x > 20) {
return 84;
uint h = x + 42;
}
}
if (x > 30) {
return 42;
uint b = 0xcafe;
}
}
return 42;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto for_loop = [](u256 n) -> u256
{
for (u256 i = 0; i < 5; i++)
{
u256 z = n + 1;
if (z < 3) break;
for (u256 j = 0; j < 5; j++)
{
u256 k = z * 2;
if (j + k < 8) {
n++;
continue;
}
n++;
if (n > 20) return 84;
}
if (n > 30) return 42;
}
return 42;
};
testContractAgainstCppOnRange("f(uint256)", for_loop, 0, 12);
)
}
BOOST_AUTO_TEST_CASE(for_loop)
{
char const* sourceCode = R"(
contract test {
function f(uint n) public returns(uint nfac) {
nfac = 1;
uint i;
for (i = 2; i <= n; i++)
nfac *= i;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto for_loop_cpp = [](u256 const& n) -> u256
{
u256 nfac = 1;
for (auto i = 2; i <= n; i++)
nfac *= i;
return nfac;
};
testContractAgainstCppOnRange("f(uint256)", for_loop_cpp, 0, 5);
)
}
BOOST_AUTO_TEST_CASE(for_loop_simple_init_expr)
{
char const* sourceCode = R"(
contract test {
function f(uint n) public returns(uint nfac) {
nfac = 1;
uint256 i;
for (i = 2; i <= n; i++)
nfac *= i;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto for_loop_simple_init_expr_cpp = [](u256 const& n) -> u256
{
u256 nfac = 1;
u256 i;
for (i = 2; i <= n; i++)
nfac *= i;
return nfac;
};
testContractAgainstCppOnRange("f(uint256)", for_loop_simple_init_expr_cpp, 0, 5);
)
}
BOOST_AUTO_TEST_CASE(for_loop_break_continue)
{
char const* sourceCode = R"(
contract test {
function f(uint n) public returns (uint r)
{
uint i = 1;
uint k = 0;
for (i *= 5; k < n; i *= 7)
{
k++;
i += 4;
if (n % 3 == 0)
break;
i += 9;
if (n % 2 == 0)
continue;
i += 19;
}
return i;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto breakContinue = [](u256 const& n) -> u256
{
u256 i = 1;
u256 k = 0;
for (i *= 5; k < n; i *= 7)
{
k++;
i += 4;
if (n % 3 == 0)
break;
i += 9;
if (n % 2 == 0)
continue;
i += 19;
}
return i;
};
testContractAgainstCppOnRange("f(uint256)", breakContinue, 0, 10);
);
}
BOOST_AUTO_TEST_CASE(short_circuiting)
{
char const* sourceCode = R"(
contract test {
function run(uint x) public returns(uint y) {
x == 0 || ((x = 8) > 0);
return x;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
auto short_circuiting_cpp = [](u256 n) -> u256
{
(void)(n == 0 || (n = 8) > 0);
return n;
};
testContractAgainstCppOnRange("run(uint256)", short_circuiting_cpp, 0, 2);
)
}
BOOST_AUTO_TEST_CASE(high_bits_cleaning)
{
char const* sourceCode = R"(
contract test {
function run() public returns(uint256 y) {
unchecked {
uint32 t = uint32(0xffffffff);
uint32 x = t + 10;
if (x >= 0xffffffff) return 0;
return x;
}
}
}
)";
compileAndRun(sourceCode);
auto high_bits_cleaning_cpp = []() -> u256
{
uint32_t t = uint32_t(0xffffffff);
uint32_t x = t + 10;
if (x >= 0xffffffff)
return 0;
return x;
};
testContractAgainstCpp("run()", high_bits_cleaning_cpp);
}
BOOST_AUTO_TEST_CASE(sign_extension)
{
char const* sourceCode = R"(
contract test {
function run() public returns(uint256 y) {
unchecked {
int64 x = -int32(int64(0xff));
if (x >= 0xff) return 0;
return 0 - uint256(int256(x));
}
}
}
)";
compileAndRun(sourceCode);
auto sign_extension_cpp = []() -> u256
{
int64_t x = -int32_t(0xff);
if (x >= 0xff)
return 0;
return u256(x) * -1;
};
testContractAgainstCpp("run()", sign_extension_cpp);
}
BOOST_AUTO_TEST_CASE(small_unsigned_types)
{
char const* sourceCode = R"(
contract test {
function run() public returns(uint256 y) {
unchecked {
uint32 t = uint32(0xffffff);
uint32 x = t * 0xffffff;
return x / 0x100;
}
}
}
)";
compileAndRun(sourceCode);
auto small_unsigned_types_cpp = []() -> u256
{
uint32_t t = uint32_t(0xffffff);
uint32_t x = t * 0xffffff;
return x / 0x100;
};
testContractAgainstCpp("run()", small_unsigned_types_cpp);
}
BOOST_AUTO_TEST_CASE(mapping_state_inc_dec)
{
char const* sourceCode = R"(
contract test {
uint value;
mapping(uint => uint) table;
function f(uint x) public returns (uint y) {
value = x;
if (x > 0) table[++value] = 8;
if (x > 1) value--;
if (x > 2) table[value]++;
table[value] += 10;
return --table[value++];
}
}
)";
u256 value;
std::map<u256, u256> table;
auto f = [&](u256 const& _x) -> u256
{
value = _x;
if (_x > 0)
table[++value] = 8;
if (_x > 1)
value --;
if (_x > 2)
table[value]++;
table[value] += 10;
return --table[value++];
};
ALSO_VIA_YUL(
compileAndRun(sourceCode);
value = 0;
table.clear();
testContractAgainstCppOnRange("f(uint256)", f, 0, 5);
)
}
BOOST_AUTO_TEST_CASE(multi_level_mapping)
{
char const* sourceCode = R"(
contract test {
mapping(uint => mapping(uint => uint)) table;
function f(uint x, uint y, uint z) public returns (uint w) {
if (z == 0) return table[x][y];
else return table[x][y] = z;
}
}
)";
std::map<u256, std::map<u256, u256>> table;
auto f = [&](u256 const& _x, u256 const& _y, u256 const& _z) -> u256
{
if (_z == 0) return table[_x][_y];
else return table[_x][_y] = _z;
};
ALSO_VIA_YUL(
compileAndRun(sourceCode);
table.clear();
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(0));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(0));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(9));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(0));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(0));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(7));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(4), u256(5), u256(0));
testContractAgainstCpp("f(uint256,uint256,uint256)", f, u256(5), u256(4), u256(0));
)
}
BOOST_AUTO_TEST_CASE(constructor)
{
char const* sourceCode = R"(
contract test {
mapping(uint => uint) data;
constructor() {
data[7] = 8;
}
function get(uint key) public returns (uint value) {
return data[key];
}
}
)";
std::map<u256, uint8_t> data;
data[7] = 8;
auto get = [&](u256 const& _x) -> u256
{
return data[_x];
};
ALSO_VIA_YUL(
compileAndRun(sourceCode);
testContractAgainstCpp("get(uint256)", get, u256(6));
testContractAgainstCpp("get(uint256)", get, u256(7));
)
}
BOOST_AUTO_TEST_CASE(send_ether)
{
char const* sourceCode = R"(
contract test {
constructor() payable {}
function a(address payable addr, uint amount) public returns (uint ret) {
addr.send(amount);
return address(this).balance;
}
}
)";
ALSO_VIA_YUL(
u256 amount(250);
compileAndRun(sourceCode, amount + 1);
h160 address(23);
ABI_CHECK(callContractFunction("a(address,uint256)", address, amount), encodeArgs(1));
BOOST_CHECK_EQUAL(balanceAt(address), amount);
)
}
BOOST_AUTO_TEST_CASE(transfer_ether)
{
char const* sourceCode = R"(
contract A {
constructor() payable {}
function a(address payable addr, uint amount) public returns (uint) {
addr.transfer(amount);
return address(this).balance;
}
function b(address payable addr, uint amount) public {
addr.transfer(amount);
}
}
contract B {
}
contract C {
receive () external payable {
revert();
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "B");
h160 const nonPayableRecipient = m_contractAddress;
compileAndRun(sourceCode, 0, "C");
h160 const oogRecipient = m_contractAddress;
compileAndRun(sourceCode, 20, "A");
h160 payableRecipient(23);
ABI_CHECK(callContractFunction("a(address,uint256)", payableRecipient, 10), encodeArgs(10));
BOOST_CHECK_EQUAL(balanceAt(payableRecipient), 10);
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 10);
ABI_CHECK(callContractFunction("b(address,uint256)", nonPayableRecipient, 10), encodeArgs());
ABI_CHECK(callContractFunction("b(address,uint256)", oogRecipient, 10), encodeArgs());
)
}
BOOST_AUTO_TEST_CASE(inter_contract_calls)
{
char const* sourceCode = R"(
contract Helper {
function multiply(uint a, uint b) public returns (uint c) {
return a * b;
}
}
contract Main {
Helper h;
function callHelper(uint a, uint b) public returns (uint c) {
return h.multiply(a, b);
}
function getHelper() public returns (address haddress) {
return address(h);
}
function setHelper(address haddress) public {
h = Helper(haddress);
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress));
u256 a(3456789);
u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b));
}
BOOST_AUTO_TEST_CASE(inter_contract_calls_with_complex_parameters)
{
char const* sourceCode = R"(
contract Helper {
function sel(uint a, bool select, uint b) public returns (uint c) {
if (select) return a; else return b;
}
}
contract Main {
Helper h;
function callHelper(uint a, bool select, uint b) public returns (uint c) {
return h.sel(a, select, b) * 3;
}
function getHelper() public returns (address haddress) {
return address(h);
}
function setHelper(address haddress) public {
h = Helper(haddress);
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress));
u256 a(3456789);
u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, true, b) == encodeArgs(a * 3));
BOOST_REQUIRE(callContractFunction("callHelper(uint256,bool,uint256)", a, false, b) == encodeArgs(b * 3));
}
BOOST_AUTO_TEST_CASE(inter_contract_calls_accessing_this)
{
char const* sourceCode = R"(
contract Helper {
function getAddress() public returns (address addr) {
return address(this);
}
}
contract Main {
Helper h;
function callHelper() public returns (address addr) {
return h.getAddress();
}
function getHelper() public returns (address addr) {
return address(h);
}
function setHelper(address addr) public {
h = Helper(addr);
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress));
BOOST_REQUIRE(callContractFunction("callHelper()") == encodeArgs(c_helperAddress));
}
BOOST_AUTO_TEST_CASE(calls_to_this)
{
char const* sourceCode = R"(
contract Helper {
function invoke(uint a, uint b) public returns (uint c) {
return this.multiply(a, b, 10);
}
function multiply(uint a, uint b, uint8 c) public returns (uint ret) {
return a * b + c;
}
}
contract Main {
Helper h;
function callHelper(uint a, uint b) public returns (uint ret) {
return h.invoke(a, b);
}
function getHelper() public returns (address addr) {
return address(h);
}
function setHelper(address addr) public {
h = Helper(addr);
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress));
u256 a(3456789);
u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b + 10));
}
BOOST_AUTO_TEST_CASE(inter_contract_calls_with_local_vars)
{
// note that a reference to another contract's function occupies two stack slots,
// so this tests correct stack slot allocation
char const* sourceCode = R"(
contract Helper {
function multiply(uint a, uint b) public returns (uint c) {
return a * b;
}
}
contract Main {
Helper h;
function callHelper(uint a, uint b) public returns (uint c) {
uint8 y = 9;
uint256 ret = h.multiply(a, b);
return ret + y;
}
function getHelper() public returns (address haddress) {
return address(h);
}
function setHelper(address haddress) public {
h = Helper(haddress);
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress));
u256 a(3456789);
u256 b("0x282837623374623234aa74");
BOOST_REQUIRE(callContractFunction("callHelper(uint256,uint256)", a, b) == encodeArgs(a * b + 9));
}
BOOST_AUTO_TEST_CASE(fixed_bytes_in_calls)
{
char const* sourceCode = R"(
contract Helper {
function invoke(bytes3 x, bool stop) public returns (bytes4 ret) {
return x;
}
}
contract Main {
Helper h;
function callHelper(bytes2 x, bool stop) public returns (bytes5 ret) {
return h.invoke(x, stop);
}
function getHelper() public returns (address addr) {
return address(h);
}
function setHelper(address addr) public {
h = Helper(addr);
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 0, "Main");
BOOST_REQUIRE(callContractFunction("setHelper(address)", c_helperAddress) == bytes());
BOOST_REQUIRE(callContractFunction("getHelper()", c_helperAddress) == encodeArgs(c_helperAddress));
ABI_CHECK(callContractFunction("callHelper(bytes2,bool)", std::string("\0a", 2), true), encodeArgs(std::string("\0a\0\0\0", 5)));
}
BOOST_AUTO_TEST_CASE(constructor_with_long_arguments)
{
char const* sourceCode = R"(
contract Main {
string public a;
string public b;
constructor(string memory _a, string memory _b) {
a = _a;
b = _b;
}
}
)";
std::string a = "01234567890123gabddunaouhdaoneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi45678907890123456789abcd123456787890123456789abcd90123456789012345678901234567890123456789aboneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi45678907890123456789abcd123456787890123456789abcd90123456789012345678901234567890123456789aboneudapcgadi4567890789012oneudapcgadi4567890789012oneudapcgadi45678907890123456789abcd123456787890123456789abcd90123456789012345678901234567890123456789aboneudapcgadi4567890789012cdef";
std::string b = "AUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PYAUTAHIACIANOTUHAOCUHAOEUNAOEHUNTHDYDHPYDRCPYDRSTITOEUBXHUDGO>PY";
compileAndRun(sourceCode, 0, "Main", encodeArgs(
u256(0x40),
u256(0x40 + 0x20 + ((a.length() + 31) / 32) * 32),
u256(a.length()),
a,
u256(b.length()),
b
));
ABI_CHECK(callContractFunction("a()"), encodeDyn(a));
ABI_CHECK(callContractFunction("b()"), encodeDyn(b));
}
BOOST_AUTO_TEST_CASE(contracts_as_addresses)
{
char const* sourceCode = R"(
contract helper {
receive() external payable { } // can receive ether
}
contract test {
helper h;
constructor() payable { h = new helper(); payable(h).send(5); }
function getBalance() public returns (uint256 myBalance, uint256 helperBalance) {
myBalance = address(this).balance;
helperBalance = address(h).balance;
}
}
)";
compileAndRun(sourceCode, 20);
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 20 - 5);
BOOST_REQUIRE(callContractFunction("getBalance()") == encodeArgs(u256(20 - 5), u256(5)));
}
BOOST_AUTO_TEST_CASE(blockhash)
{
char const* sourceCode = R"(
contract C {
uint256 counter;
function g() public returns (bool) { counter++; return true; }
function f() public returns (bytes32[] memory r) {
r = new bytes32[](259);
for (uint i = 0; i < 259; i++) {
unchecked {
r[i] = blockhash(block.number - 257 + i);
}
}
}
}
)";
compileAndRun(sourceCode);
// generate a sufficient amount of blocks
while (blockNumber() < u256(255))
ABI_CHECK(callContractFunction("g()"), encodeArgs(true));
std::vector<u256> hashes;
// ``blockhash()`` is only valid for the last 256 blocks, otherwise zero
hashes.emplace_back(0);
for (u256 i = blockNumber() - u256(255); i <= blockNumber(); i++)
hashes.emplace_back(blockHash(i));
// the current block hash is not yet known at execution time and therefore zero
hashes.emplace_back(0);
// future block hashes are zero
hashes.emplace_back(0);
ABI_CHECK(callContractFunction("f()"), encodeDyn(hashes));
}
BOOST_AUTO_TEST_CASE(internal_constructor)
{
char const* sourceCode = R"(
abstract contract C {
constructor() {}
}
)";
// via yul disabled because it will throw an error instead of
// returning empty bytecode.
BOOST_CHECK(compileAndRunWithoutCheck({{"", sourceCode}}, 0, "C").empty());
}
BOOST_AUTO_TEST_CASE(default_fallback_throws)
{
char const* sourceCode = R"YY(
contract A {
function f() public returns (bool) {
(bool success,) = address(this).call("");
return success;
}
}
)YY";
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f()"), encodeArgs(0));
if (solidity::test::CommonOptions::get().evmVersion().hasStaticCall())
{
char const* sourceCode = R"YY(
contract A {
function f() public returns (bool) {
(bool success, bytes memory data) = address(this).staticcall("");
assert(data.length == 0);
return success;
}
}
)YY";
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f()"), encodeArgs(0));
}
}
BOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one)
{
char const* sourceCode = R"(
contract test {
function f(uint, uint k) public returns(uint ret_k, uint ret_g){
uint g = 8;
ret_k = k;
ret_g = g;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
BOOST_CHECK(callContractFunction("f(uint256,uint256)", 5, 9) != encodeArgs(5, 8));
ABI_CHECK(callContractFunction("f(uint256,uint256)", 5, 9), encodeArgs(9, 8));
)
}
BOOST_AUTO_TEST_CASE(generic_call)
{
char const* sourceCode = R"**(
contract receiver {
uint public received;
function recv(uint256 x) public payable { received = x; }
}
contract sender {
constructor() payable {}
function doSend(address rec) public returns (uint d)
{
bytes4 signature = bytes4(bytes32(keccak256("recv(uint256)")));
rec.call{value: 2}(abi.encodeWithSelector(signature, 23));
return receiver(rec).received();
}
}
)**";
compileAndRun(sourceCode, 0, "receiver");
h160 const c_receiverAddress = m_contractAddress;
compileAndRun(sourceCode, 50, "sender");
BOOST_REQUIRE(callContractFunction("doSend(address)", c_receiverAddress) == encodeArgs(23));
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 50 - 2);
}
BOOST_AUTO_TEST_CASE(generic_delegatecall)
{
char const* sourceCode = R"**(
contract Receiver {
uint public received;
address public sender;
uint public value;
constructor() payable {}
function recv(uint256 x) public payable { received = x; sender = msg.sender; value = msg.value; }
}
contract Sender {
uint public received;
address public sender;
uint public value;
constructor() payable {}
function doSend(address rec) public payable
{
bytes4 signature = bytes4(bytes32(keccak256("recv(uint256)")));
(bool success,) = rec.delegatecall(abi.encodeWithSelector(signature, 23));
success;
}
}
)**";
for (auto v2: {false, true})
{
std::string source = "pragma abicoder " + std::string(v2 ? "v2" : "v1") + ";\n" + std::string(sourceCode);
compileAndRun(source, 0, "Receiver");
h160 const c_receiverAddress = m_contractAddress;
compileAndRun(source, 50, "Sender");
h160 const c_senderAddress = m_contractAddress;
BOOST_CHECK(m_sender != c_senderAddress); // just for sanity
ABI_CHECK(callContractFunctionWithValue("doSend(address)", 11, c_receiverAddress), encodeArgs());
ABI_CHECK(callContractFunction("received()"), encodeArgs(u256(23)));
ABI_CHECK(callContractFunction("sender()"), encodeArgs(m_sender));
ABI_CHECK(callContractFunction("value()"), encodeArgs(u256(11)));
m_contractAddress = c_receiverAddress;
ABI_CHECK(callContractFunction("received()"), encodeArgs(u256(0)));
ABI_CHECK(callContractFunction("sender()"), encodeArgs(u256(0)));
ABI_CHECK(callContractFunction("value()"), encodeArgs(u256(0)));
BOOST_CHECK(storageEmpty(c_receiverAddress));
BOOST_CHECK(!storageEmpty(c_senderAddress));
BOOST_CHECK_EQUAL(balanceAt(c_receiverAddress), 0);
BOOST_CHECK_EQUAL(balanceAt(c_senderAddress), 50 + 11);
}
}
BOOST_AUTO_TEST_CASE(generic_staticcall)
{
if (solidity::test::CommonOptions::get().evmVersion().hasStaticCall())
{
char const* sourceCode = R"**(
contract A {
uint public x;
constructor() { x = 42; }
function pureFunction(uint256 p) public pure returns (uint256) { return p; }
function viewFunction(uint256 p) public view returns (uint256) { return p + x; }
function nonpayableFunction(uint256 p) public returns (uint256) { x = p; return x; }
function assertFunction(uint256 p) public view returns (uint256) { assert(x == p); return x; }
}
contract C {
function f(address a) public view returns (bool, bytes memory)
{
return a.staticcall(abi.encodeWithSignature("pureFunction(uint256)", 23));
}
function g(address a) public view returns (bool, bytes memory)
{
return a.staticcall(abi.encodeWithSignature("viewFunction(uint256)", 23));
}
function h(address a) public view returns (bool, bytes memory)
{
return a.staticcall(abi.encodeWithSignature("nonpayableFunction(uint256)", 23));
}
function i(address a, uint256 v) public view returns (bool, bytes memory)
{
return a.staticcall(abi.encodeWithSignature("assertFunction(uint256)", v));
}
}
)**";
compileAndRun(sourceCode, 0, "A");
h160 const c_addressA = m_contractAddress;
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f(address)", c_addressA), encodeArgs(true, 0x40, 0x20, 23));
ABI_CHECK(callContractFunction("g(address)", c_addressA), encodeArgs(true, 0x40, 0x20, 23 + 42));
ABI_CHECK(callContractFunction("h(address)", c_addressA), encodeArgs(false, 0x40, 0x00));
ABI_CHECK(callContractFunction("i(address,uint256)", c_addressA, 42), encodeArgs(true, 0x40, 0x20, 42));
ABI_CHECK(callContractFunction("i(address,uint256)", c_addressA, 23), encodeArgs(false, 0x40, 0x24) + panicData(PanicCode::Assert) + bytes(32 - 4, 0));
}
}
BOOST_AUTO_TEST_CASE(library_call_protection)
{
// This tests code that reverts a call if it is a direct call to a library
// as opposed to a delegatecall.
char const* sourceCode = R"(
library Lib {
struct S { uint x; }
// a direct call to this should revert
function np(S storage s) public returns (address) { s.x = 3; return msg.sender; }
// a direct call to this is fine
function v(S storage) public view returns (address) { return msg.sender; }
// a direct call to this is fine
function pu() public pure returns (uint) { return 2; }
}
contract Test {
Lib.S public s;
function np() public returns (address) { return Lib.np(s); }
function v() public view returns (address) { return Lib.v(s); }
function pu() public pure returns (uint) { return Lib.pu(); }
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "Lib");
ABI_CHECK(callContractFunction("np(Lib.S storage)", 0), encodeArgs());
ABI_CHECK(callContractFunction("v(Lib.S storage)", 0), encodeArgs(m_sender));
ABI_CHECK(callContractFunction("pu()"), encodeArgs(2));
compileAndRun(sourceCode, 0, "Test", bytes(), std::map<std::string, h160>{{":Lib", m_contractAddress}});
ABI_CHECK(callContractFunction("s()"), encodeArgs(0));
ABI_CHECK(callContractFunction("np()"), encodeArgs(m_sender));
ABI_CHECK(callContractFunction("s()"), encodeArgs(3));
ABI_CHECK(callContractFunction("v()"), encodeArgs(m_sender));
ABI_CHECK(callContractFunction("pu()"), encodeArgs(2));
)
}
BOOST_AUTO_TEST_CASE(bytes_from_calldata_to_memory)
{
char const* sourceCode = R"(
contract C {
function f() public returns (bytes32) {
return keccak256(abi.encodePacked("abc", msg.data));
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
bytes calldata1 = util::selectorFromSignatureH32("f()").asBytes() + bytes(61, 0x22) + bytes(12, 0x12);
sendMessage(calldata1, false);
BOOST_CHECK(m_transactionSuccessful);
BOOST_CHECK(m_output == encodeArgs(util::keccak256(bytes{'a', 'b', 'c'} + calldata1)));
);
}
BOOST_AUTO_TEST_CASE(call_forward_bytes_length)
{
char const* sourceCode = R"(
contract receiver {
uint public calledLength;
fallback() external { calledLength = msg.data.length; }
}
contract sender {
receiver rec;
constructor() { rec = new receiver(); }
function viaCalldata() public returns (uint) {
(bool success,) = address(rec).call(msg.data);
require(success);
return rec.calledLength();
}
function viaMemory() public returns (uint) {
bytes memory x = msg.data;
(bool success,) = address(rec).call(x);
require(success);
return rec.calledLength();
}
bytes s;
function viaStorage() public returns (uint) {
s = msg.data;
(bool success,) = address(rec).call(s);
require(success);
return rec.calledLength();
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "sender");
// No additional data, just function selector
ABI_CHECK(callContractFunction("viaCalldata()"), encodeArgs(4));
ABI_CHECK(callContractFunction("viaMemory()"), encodeArgs(4));
ABI_CHECK(callContractFunction("viaStorage()"), encodeArgs(4));
// Some additional unpadded data
bytes unpadded = asBytes(std::string("abc"));
ABI_CHECK(callContractFunctionNoEncoding("viaCalldata()", unpadded), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("viaMemory()", unpadded), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("viaStorage()", unpadded), encodeArgs(7));
);
}
BOOST_AUTO_TEST_CASE(copying_bytes_multiassign)
{
char const* sourceCode = R"(
contract receiver {
uint public received;
function recv(uint x) public { received += x + 1; }
fallback() external { received = 0x80; }
}
contract sender {
constructor() { rec = new receiver(); }
fallback() external { savedData1 = savedData2 = msg.data; }
function forward(bool selector) public returns (bool) {
if (selector) { address(rec).call(savedData1); delete savedData1; }
else { address(rec).call(savedData2); delete savedData2; }
return true;
}
function val() public returns (uint) { return rec.received(); }
receiver rec;
bytes savedData1;
bytes savedData2;
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "sender");
ABI_CHECK(callContractFunction("recv(uint256)", 7), bytes());
ABI_CHECK(callContractFunction("val()"), encodeArgs(0));
ABI_CHECK(callContractFunction("forward(bool)", true), encodeArgs(true));
ABI_CHECK(callContractFunction("val()"), encodeArgs(8));
ABI_CHECK(callContractFunction("forward(bool)", false), encodeArgs(true));
ABI_CHECK(callContractFunction("val()"), encodeArgs(16));
ABI_CHECK(callContractFunction("forward(bool)", true), encodeArgs(true));
ABI_CHECK(callContractFunction("val()"), encodeArgs(0x80));
);
}
BOOST_AUTO_TEST_CASE(copy_from_calldata_removes_bytes_data)
{
char const* sourceCode = R"(
contract c {
function set() public returns (bool) { data = msg.data; return true; }
fallback() external { data = msg.data; }
bytes data;
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("set()", 1, 2, 3, 4, 5), encodeArgs(true));
BOOST_CHECK(!storageEmpty(m_contractAddress));
sendMessage(bytes(), false);
BOOST_CHECK(m_transactionSuccessful);
BOOST_CHECK(m_output.empty());
BOOST_CHECK(storageEmpty(m_contractAddress));
);
}
BOOST_AUTO_TEST_CASE(struct_referencing)
{
static char const* sourceCode = R"(
pragma abicoder v2;
interface I {
struct S { uint a; }
}
library L {
struct S { uint b; uint a; }
function f() public pure returns (S memory) {
S memory s;
s.a = 3;
return s;
}
function g() public pure returns (I.S memory) {
I.S memory s;
s.a = 4;
return s;
}
// argument-dependent lookup tests
function a(I.S memory) public pure returns (uint) { return 1; }
function a(S memory) public pure returns (uint) { return 2; }
}
contract C is I {
function f() public pure returns (S memory) {
S memory s;
s.a = 1;
return s;
}
function g() public pure returns (I.S memory) {
I.S memory s;
s.a = 2;
return s;
}
function h() public pure returns (L.S memory) {
L.S memory s;
s.a = 5;
return s;
}
function x() public pure returns (L.S memory) {
return L.f();
}
function y() public pure returns (I.S memory) {
return L.g();
}
function a1() public pure returns (uint) { S memory s; return L.a(s); }
function a2() public pure returns (uint) { L.S memory s; return L.a(s); }
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "L");
ABI_CHECK(callContractFunction("f()"), encodeArgs(0, 3));
ABI_CHECK(callContractFunction("g()"), encodeArgs(4));
compileAndRun(sourceCode, 0, "C", bytes(), std::map<std::string, h160>{ {":L", m_contractAddress}});
ABI_CHECK(callContractFunction("f()"), encodeArgs(1));
ABI_CHECK(callContractFunction("g()"), encodeArgs(2));
ABI_CHECK(callContractFunction("h()"), encodeArgs(0, 5));
ABI_CHECK(callContractFunction("x()"), encodeArgs(0, 3));
ABI_CHECK(callContractFunction("y()"), encodeArgs(4));
ABI_CHECK(callContractFunction("a1()"), encodeArgs(1));
ABI_CHECK(callContractFunction("a2()"), encodeArgs(2));
)
}
BOOST_AUTO_TEST_CASE(enum_referencing)
{
char const* sourceCode = R"(
interface I {
enum Direction { A, B, Left, Right }
}
library L {
enum Direction { Left, Right }
function f() public pure returns (Direction) {
return Direction.Right;
}
function g() public pure returns (I.Direction) {
return I.Direction.Right;
}
}
contract C is I {
function f() public pure returns (Direction) {
return Direction.Right;
}
function g() public pure returns (I.Direction) {
return I.Direction.Right;
}
function h() public pure returns (L.Direction) {
return L.Direction.Right;
}
function x() public pure returns (L.Direction) {
return L.f();
}
function y() public pure returns (I.Direction) {
return L.g();
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "L");
ABI_CHECK(callContractFunction("f()"), encodeArgs(1));
ABI_CHECK(callContractFunction("g()"), encodeArgs(3));
compileAndRun(sourceCode, 0, "C", bytes(), std::map<std::string, h160>{{":L", m_contractAddress}});
ABI_CHECK(callContractFunction("f()"), encodeArgs(3));
ABI_CHECK(callContractFunction("g()"), encodeArgs(3));
ABI_CHECK(callContractFunction("h()"), encodeArgs(1));
ABI_CHECK(callContractFunction("x()"), encodeArgs(1));
ABI_CHECK(callContractFunction("y()"), encodeArgs(3));
)
}
BOOST_AUTO_TEST_CASE(bytes_in_arguments)
{
char const* sourceCode = R"(
contract c {
uint result;
function f(uint a, uint b) public { result += a + b; }
function g(uint a) public { result *= a; }
function test(uint a, bytes calldata data1, bytes calldata data2, uint b) external returns (uint r_a, uint r, uint r_b, uint l) {
r_a = a;
address(this).call(data1);
address(this).call(data2);
r = result;
r_b = b;
l = data1.length;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
std::string innercalldata1 = asString(util::selectorFromSignatureH32("f(uint256,uint256)").asBytes() + encodeArgs(8, 9));
std::string innercalldata2 = asString(util::selectorFromSignatureH32("g(uint256)").asBytes() + encodeArgs(3));
bytes calldata = encodeArgs(
12, 32 * 4, u256(32 * 4 + 32 + (innercalldata1.length() + 31) / 32 * 32), 13,
u256(innercalldata1.length()), innercalldata1,
u256(innercalldata2.length()), innercalldata2);
ABI_CHECK(
callContractFunction("test(uint256,bytes,bytes,uint256)", calldata),
encodeArgs(12, (8 + 9) * 3, 13, u256(innercalldata1.length()))
);
);
}
BOOST_AUTO_TEST_CASE(array_copy_storage_abi)
{
// NOTE: This does not really test copying from storage to ABI directly,
// because it will always copy to memory first.
char const* sourceCode = R"(
pragma abicoder v2;
contract c {
uint8[] x;
uint16[] y;
uint24[] z;
uint24[][] w;
function test1() public returns (uint8[] memory) {
for (uint i = 0; i < 101; ++i)
x.push(uint8(i));
return x;
}
function test2() public returns (uint16[] memory) {
for (uint i = 0; i < 101; ++i)
y.push(uint16(i));
return y;
}
function test3() public returns (uint24[] memory) {
for (uint i = 0; i < 101; ++i)
z.push(uint24(i));
return z;
}
function test4() public returns (uint24[][] memory) {
w = new uint24[][](5);
for (uint i = 0; i < 5; ++i)
for (uint j = 0; j < 101; ++j)
w[i].push(uint24(j));
return w;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode);
bytes valueSequence;
for (size_t i = 0; i < 101; ++i)
valueSequence += toBigEndian(u256(i));
ABI_CHECK(callContractFunction("test1()"), encodeArgs(0x20, 101) + valueSequence);
ABI_CHECK(callContractFunction("test2()"), encodeArgs(0x20, 101) + valueSequence);
ABI_CHECK(callContractFunction("test3()"), encodeArgs(0x20, 101) + valueSequence);
ABI_CHECK(callContractFunction("test4()"),
encodeArgs(0x20, 5, 0xa0, 0xa0 + 102 * 32 * 1, 0xa0 + 102 * 32 * 2, 0xa0 + 102 * 32 * 3, 0xa0 + 102 * 32 * 4) +
encodeArgs(101) + valueSequence +
encodeArgs(101) + valueSequence +
encodeArgs(101) + valueSequence +
encodeArgs(101) + valueSequence +
encodeArgs(101) + valueSequence
);
);
}
//BOOST_AUTO_TEST_CASE(assignment_to_const_array_vars)
//{
// char const* sourceCode = R"(
// contract C {
// uint[3] constant x = [uint(1), 2, 3];
// uint constant y = x[0] + x[1] + x[2];
// function f() public returns (uint) { return y; }
// }
// )";
// compileAndRun(sourceCode);
// ABI_CHECK(callContractFunction("f()"), encodeArgs(1 + 2 + 3));
//}
// Disabled until https://github.com/ethereum/solidity/issues/715 is implemented
//BOOST_AUTO_TEST_CASE(constant_struct)
//{
// char const* sourceCode = R"(
// contract C {
// struct S { uint x; uint[] y; }
// S constant x = S(5, new uint[](4));
// function f() public returns (uint) { return x.x; }
// }
// )";
// compileAndRun(sourceCode);
// ABI_CHECK(callContractFunction("f()"), encodeArgs(5));
//}
BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_out_of_baund)
{
char const* sourceCode = R"(
contract A {
uint public test = 1;
uint[3] arr;
constructor()
{
uint index = 5;
test = arr[index];
++test;
}
}
)";
ABI_CHECK(compileAndRunWithoutCheck({{"", sourceCode}}, 0, "A"), panicData(PanicCode::ArrayOutOfBounds));
BOOST_CHECK(!m_transactionSuccessful);
}
BOOST_AUTO_TEST_CASE(failing_send)
{
char const* sourceCode = R"(
contract Helper {
uint[] data;
fallback () external {
data[9]; // trigger exception
}
}
contract Main {
constructor() payable {}
function callHelper(address payable _a) public returns (bool r, uint bal) {
r = !_a.send(5);
bal = address(this).balance;
}
}
)";
compileAndRun(sourceCode, 0, "Helper");
h160 const c_helperAddress = m_contractAddress;
compileAndRun(sourceCode, 20, "Main");
BOOST_REQUIRE(callContractFunction("callHelper(address)", c_helperAddress) == encodeArgs(true, 20));
}
BOOST_AUTO_TEST_CASE(return_multiple_strings_of_various_sizes)
{
char const* sourceCode = R"(
contract Main {
string public s1;
string public s2;
function set(string calldata _s1, uint x, string calldata _s2) external returns (uint) {
s1 = _s1;
s2 = _s2;
return x;
}
function get() public returns (string memory r1, string memory r2) {
r1 = s1;
r2 = s2;
}
}
)";
compileAndRun(sourceCode, 0, "Main");
std::string s1(
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
);
std::string s2(
"ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"
"ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"
"ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"
"ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"
"ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ"
);
std::vector<size_t> lengths{0, 30, 32, 63, 64, 65, 210, 300};
for (auto l1: lengths)
for (auto l2: lengths)
{
bytes dyn1 = encodeArgs(u256(l1), s1.substr(0, l1));
bytes dyn2 = encodeArgs(u256(l2), s2.substr(0, l2));
bytes args = encodeArgs(u256(0x60), u256(l1), u256(0x60 + dyn1.size())) + dyn1 + dyn2;
BOOST_REQUIRE(
callContractFunction("set(string,uint256,string)", asString(args)) ==
encodeArgs(u256(l1))
);
bytes result = encodeArgs(u256(0x40), u256(0x40 + dyn1.size())) + dyn1 + dyn2;
ABI_CHECK(callContractFunction("get()"), result);
ABI_CHECK(callContractFunction("s1()"), encodeArgs(0x20) + dyn1);
ABI_CHECK(callContractFunction("s2()"), encodeArgs(0x20) + dyn2);
}
}
BOOST_AUTO_TEST_CASE(accessor_involving_strings)
{
char const* sourceCode = R"(
contract Main {
struct stringData { string a; uint b; string c; }
mapping(uint => stringData[]) public data;
function set(uint x, uint y, string calldata a, uint b, string calldata c) external returns (bool) {
while (data[x].length < y + 1)
data[x].push();
data[x][y].a = a;
data[x][y].b = b;
data[x][y].c = c;
return true;
}
}
)";
compileAndRun(sourceCode, 0, "Main");
std::string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
std::string s2("ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ");
bytes s1Data = encodeArgs(u256(s1.length()), s1);
bytes s2Data = encodeArgs(u256(s2.length()), s2);
u256 b = 765;
u256 x = 7;
u256 y = 123;
bytes args = encodeArgs(x, y, u256(0xa0), b, u256(0xa0 + s1Data.size()), s1Data, s2Data);
bytes result = encodeArgs(u256(0x60), b, u256(0x60 + s1Data.size()), s1Data, s2Data);
BOOST_REQUIRE(callContractFunction("set(uint256,uint256,string,uint256,string)", asString(args)) == encodeArgs(true));
BOOST_REQUIRE(callContractFunction("data(uint256,uint256)", x, y) == result);
}
BOOST_AUTO_TEST_CASE(bytes_in_function_calls)
{
char const* sourceCode = R"(
contract Main {
string public s1;
string public s2;
function set(string memory _s1, uint x, string memory _s2) public returns (uint) {
s1 = _s1;
s2 = _s2;
return x;
}
function setIndirectFromMemory(string memory _s1, uint x, string memory _s2) public returns (uint) {
return this.set(_s1, x, _s2);
}
function setIndirectFromCalldata(string calldata _s1, uint x, string calldata _s2) external returns (uint) {
return this.set(_s1, x, _s2);
}
}
)";
compileAndRun(sourceCode, 0, "Main");
std::string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
std::string s2("ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJKLMNOPQRSTUVXYZ");
std::vector<size_t> lengths{0, 31, 64, 65};
for (auto l1: lengths)
for (auto l2: lengths)
{
bytes dyn1 = encodeArgs(u256(l1), s1.substr(0, l1));
bytes dyn2 = encodeArgs(u256(l2), s2.substr(0, l2));
bytes args1 = encodeArgs(u256(0x60), u256(l1), u256(0x60 + dyn1.size())) + dyn1 + dyn2;
BOOST_REQUIRE(
callContractFunction("setIndirectFromMemory(string,uint256,string)", asString(args1)) ==
encodeArgs(u256(l1))
);
ABI_CHECK(callContractFunction("s1()"), encodeArgs(0x20) + dyn1);
ABI_CHECK(callContractFunction("s2()"), encodeArgs(0x20) + dyn2);
// swapped
bytes args2 = encodeArgs(u256(0x60), u256(l1), u256(0x60 + dyn2.size())) + dyn2 + dyn1;
BOOST_REQUIRE(
callContractFunction("setIndirectFromCalldata(string,uint256,string)", asString(args2)) ==
encodeArgs(u256(l1))
);
ABI_CHECK(callContractFunction("s1()"), encodeArgs(0x20) + dyn2);
ABI_CHECK(callContractFunction("s2()"), encodeArgs(0x20) + dyn1);
}
}
BOOST_AUTO_TEST_CASE(return_bytes_internal)
{
char const* sourceCode = R"(
contract Main {
bytes s1;
function doSet(bytes memory _s1) public returns (bytes memory _r1) {
s1 = _s1;
_r1 = s1;
}
function set(bytes calldata _s1) external returns (uint _r, bytes memory _r1) {
_r1 = doSet(_s1);
_r = _r1.length;
}
}
)";
compileAndRun(sourceCode, 0, "Main");
std::string s1("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz");
std::vector<size_t> lengths{0, 31, 64, 65};
for (auto l1: lengths)
{
bytes dyn1 = encodeArgs(u256(l1), s1.substr(0, l1));
bytes args1 = encodeArgs(u256(0x20)) + dyn1;
BOOST_REQUIRE(
callContractFunction("set(bytes)", asString(args1)) ==
encodeArgs(u256(l1), u256(0x40)) + dyn1
);
}
}
BOOST_AUTO_TEST_CASE(calldata_struct_short)
{
char const* sourceCode = R"(
pragma abicoder v2;
contract C {
struct S { uint256 a; uint256 b; }
function f(S calldata) external pure returns (uint256) {
return msg.data.length;
}
}
)";
compileAndRun(sourceCode, 0, "C");
// double check that the valid case goes through
ABI_CHECK(callContractFunction("f((uint256,uint256))", u256(1), u256(2)), encodeArgs(0x44));
ABI_CHECK(callContractFunctionNoEncoding("f((uint256,uint256))", bytes(63,0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f((uint256,uint256))", bytes(33,0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f((uint256,uint256))", bytes(32,0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f((uint256,uint256))", bytes(31,0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f((uint256,uint256))", bytes()), encodeArgs());
}
BOOST_AUTO_TEST_CASE(calldata_struct_function_type)
{
char const* sourceCode = R"(
pragma abicoder v2;
contract C {
struct S { function (uint) external returns (uint) fn; }
function f(S calldata s) external returns (uint256) {
return s.fn(42);
}
function g(uint256 a) external returns (uint256) {
return a * 3;
}
function h(uint256 a) external returns (uint256) {
return 23;
}
}
)";
compileAndRun(sourceCode, 0, "C");
bytes fn_C_g = m_contractAddress.asBytes() + util::selectorFromSignatureH32("g(uint256)").asBytes() + bytes(8,0);
bytes fn_C_h = m_contractAddress.asBytes() + util::selectorFromSignatureH32("h(uint256)").asBytes() + bytes(8,0);
ABI_CHECK(callContractFunctionNoEncoding("f((function))", fn_C_g), encodeArgs(42 * 3));
ABI_CHECK(callContractFunctionNoEncoding("f((function))", fn_C_h), encodeArgs(23));
}
BOOST_AUTO_TEST_CASE(calldata_array_dynamic_three_dimensional)
{
std::vector<std::vector<std::vector<u256>>> data {
{
{ 0x010A01, 0x010A02, 0x010A03 },
{ 0x010B01, 0x010B02, 0x010B03 }
},
{
{ 0x020A01, 0x020A02, 0x020A03 },
{ 0x020B01, 0x020B02, 0x020B03 }
}
};
for (bool outerDynamicallySized: { true, false })
for (bool middleDynamicallySized: { true, false })
for (bool innerDynamicallySized: { true, false })
{
// only test dynamically encoded arrays
if (!outerDynamicallySized && !middleDynamicallySized && !innerDynamicallySized)
continue;
std::string arrayType = "uint256";
arrayType += innerDynamicallySized ? "[]" : "[3]";
arrayType += middleDynamicallySized ? "[]" : "[2]";
arrayType += outerDynamicallySized ? "[]" : "[2]";
std::string sourceCode = R"(
pragma abicoder v2;
contract C {
function test()" + arrayType + R"( calldata a) external returns (uint256) {
return a.length;
}
function test()" + arrayType + R"( calldata a, uint256 i) external returns (uint256) {
return a[i].length;
}
function test()" + arrayType + R"( calldata a, uint256 i, uint256 j) external returns (uint256) {
return a[i][j].length;
}
function test()" + arrayType + R"( calldata a, uint256 i, uint256 j, uint256 k) external returns (uint256) {
return a[i][j][k];
}
function reenc()" + arrayType + R"( calldata a, uint256 i, uint256 j, uint256 k) external returns (uint256) {
return this.test(a, i, j, k);
}
}
)";
compileAndRun(sourceCode, 0, "C");
bytes encoding = encodeArray(
outerDynamicallySized,
middleDynamicallySized || innerDynamicallySized,
data | ranges::views::transform([&](auto const& _middleData) {
return encodeArray(
middleDynamicallySized,
innerDynamicallySized,
_middleData | ranges::views::transform([&](auto const& _values) {
return encodeArray(innerDynamicallySized, false, _values);
})
);
})
);
ABI_CHECK(callContractFunction("test(" + arrayType + ")", 0x20, encoding), encodeArgs(data.size()));
for (size_t i = 0; i < data.size(); i++)
{
ABI_CHECK(callContractFunction("test(" + arrayType + ",uint256)", 0x40, i, encoding), encodeArgs(data[i].size()));
for (size_t j = 0; j < data[i].size(); j++)
{
ABI_CHECK(callContractFunction("test(" + arrayType + ",uint256,uint256)", 0x60, i, j, encoding), encodeArgs(data[i][j].size()));
for (size_t k = 0; k < data[i][j].size(); k++)
{
ABI_CHECK(callContractFunction("test(" + arrayType + ",uint256,uint256,uint256)", 0x80, i, j, k, encoding), encodeArgs(data[i][j][k]));
ABI_CHECK(callContractFunction("reenc(" + arrayType + ",uint256,uint256,uint256)", 0x80, i, j, k, encoding), encodeArgs(data[i][j][k]));
}
ABI_CHECK(callContractFunction("test(" + arrayType + ",uint256,uint256,uint256)", 0x80, i, j, data[i][j].size(), encoding), panicData(PanicCode::ArrayOutOfBounds));
}
ABI_CHECK(callContractFunction("test(" + arrayType + ",uint256,uint256)", 0x60, i, data[i].size(), encoding), panicData(PanicCode::ArrayOutOfBounds));
}
ABI_CHECK(callContractFunction("test(" + arrayType + ",uint256)", 0x40, data.size(), encoding), panicData(PanicCode::ArrayOutOfBounds));
}
}
BOOST_AUTO_TEST_CASE(literal_strings)
{
char const* sourceCode = R"(
contract Test {
string public long;
string public medium;
string public short;
string public empty;
function f() public returns (string memory) {
long = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
medium = "01234567890123456789012345678901234567890123456789012345678901234567890123456789";
short = "123";
empty = "";
return "Hello, World!";
}
}
)";
compileAndRun(sourceCode, 0, "Test");
std::string longStr = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
std::string medium = "01234567890123456789012345678901234567890123456789012345678901234567890123456789";
std::string shortStr = "123";
std::string hello = "Hello, World!";
ABI_CHECK(callContractFunction("f()"), encodeDyn(hello));
ABI_CHECK(callContractFunction("long()"), encodeDyn(longStr));
ABI_CHECK(callContractFunction("medium()"), encodeDyn(medium));
ABI_CHECK(callContractFunction("short()"), encodeDyn(shortStr));
ABI_CHECK(callContractFunction("empty()"), encodeDyn(std::string()));
}
BOOST_AUTO_TEST_CASE(initialise_string_constant)
{
char const* sourceCode = R"(
contract Test {
string public short = "abcdef";
string public long = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
}
)";
compileAndRun(sourceCode, 0, "Test");
std::string longStr = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
std::string shortStr = "abcdef";
ABI_CHECK(callContractFunction("long()"), encodeDyn(longStr));
ABI_CHECK(callContractFunction("short()"), encodeDyn(shortStr));
}
BOOST_AUTO_TEST_CASE(string_as_mapping_key)
{
char const* sourceCode = R"(
contract Test {
mapping(string => uint) data;
function set(string memory _s, uint _v) public { data[_s] = _v; }
function get(string memory _s) public returns (uint) { return data[_s]; }
}
)";
std::vector<std::string> strings{
"Hello, World!",
"Hello, World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1111",
"",
"1"
};
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "Test");
for (unsigned i = 0; i < strings.size(); i++)
ABI_CHECK(callContractFunction(
"set(string,uint256)",
u256(0x40),
u256(7 + i),
u256(strings[i].size()),
strings[i]
), encodeArgs());
for (unsigned i = 0; i < strings.size(); i++)
ABI_CHECK(callContractFunction(
"get(string)",
u256(0x20),
u256(strings[i].size()),
strings[i]
), encodeArgs(u256(7 + i)));
)
}
BOOST_AUTO_TEST_CASE(string_as_public_mapping_key)
{
char const* sourceCode = R"(
contract Test {
mapping(string => uint) public data;
function set(string memory _s, uint _v) public { data[_s] = _v; }
}
)";
compileAndRun(sourceCode, 0, "Test");
std::vector<std::string> strings{
"Hello, World!",
"Hello, World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1111",
"",
"1"
};
for (unsigned i = 0; i < strings.size(); i++)
ABI_CHECK(callContractFunction(
"set(string,uint256)",
u256(0x40),
u256(7 + i),
u256(strings[i].size()),
strings[i]
), encodeArgs());
for (unsigned i = 0; i < strings.size(); i++)
ABI_CHECK(callContractFunction(
"data(string)",
u256(0x20),
u256(strings[i].size()),
strings[i]
), encodeArgs(u256(7 + i)));
}
BOOST_AUTO_TEST_CASE(nested_string_as_public_mapping_key)
{
char const* sourceCode = R"(
contract Test {
mapping(string => mapping(string => uint)) public data;
function set(string memory _s, string memory _s2, uint _v) public {
data[_s][_s2] = _v; }
}
)";
compileAndRun(sourceCode, 0, "Test");
std::vector<std::string> strings{
"Hello, World!",
"Hello, World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1111",
"",
"1",
"last one"
};
for (unsigned i = 0; i + 1 < strings.size(); i++)
ABI_CHECK(callContractFunction(
"set(string,string,uint256)",
u256(0x60),
u256(roundTo32(static_cast<unsigned>(0x80 + strings[i].size()))),
u256(7 + i),
u256(strings[i].size()),
strings[i],
u256(strings[i+1].size()),
strings[i+1]
), encodeArgs());
for (unsigned i = 0; i + 1 < strings.size(); i++)
ABI_CHECK(callContractFunction(
"data(string,string)",
u256(0x40),
u256(roundTo32(static_cast<unsigned>(0x60 + strings[i].size()))),
u256(strings[i].size()),
strings[i],
u256(strings[i+1].size()),
strings[i+1]
), encodeArgs(u256(7 + i)));
}
BOOST_AUTO_TEST_CASE(nested_mixed_string_as_public_mapping_key)
{
char const* sourceCode = R"(
contract Test {
mapping(string =>
mapping(int =>
mapping(address =>
mapping(bytes => int)))) public data;
function set(
string memory _s1,
int _s2,
address _s3,
bytes memory _s4,
int _value
) public
{
data[_s1][_s2][_s3][_s4] = _value;
}
}
)";
compileAndRun(sourceCode, 0, "Test");
struct Index
{
std::string s1;
int s2;
int s3;
std::string s4;
};
std::vector<Index> data{
{ "aabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcbc", 4, 23, "efg" },
{ "tiaron", 456, 63245, "908apzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapzapz" },
{ "", 2345, 12934, "665i65i65i65i65i65i65i65i65i65i65i65i65i65i65i65i65i65i5iart" },
{ "¡¿…", 9781, 8148, "" },
{ "ρν♀♀ω₂₃♀", 929608, 303030, "" }
};
for (size_t i = 0; i + 1 < data.size(); i++)
ABI_CHECK(callContractFunction(
"set(string,int256,address,bytes,int256)",
u256(0xA0),
u256(data[i].s2),
u256(data[i].s3),
u256(roundTo32(static_cast<unsigned>(0xC0 + data[i].s1.size()))),
u256(i - 3),
u256(data[i].s1.size()),
data[i].s1,
u256(data[i].s4.size()),
data[i].s4
), encodeArgs());
for (size_t i = 0; i + 1 < data.size(); i++)
ABI_CHECK(callContractFunction(
"data(string,int256,address,bytes)",
u256(0x80),
u256(data[i].s2),
u256(data[i].s3),
u256(roundTo32(static_cast<unsigned>(0xA0 + data[i].s1.size()))),
u256(data[i].s1.size()),
data[i].s1,
u256(data[i].s4.size()),
data[i].s4
), encodeArgs(u256(i - 3)));
}
BOOST_AUTO_TEST_CASE(library_call)
{
char const* sourceCode = R"(
library Lib { function m(uint x, uint y) public returns (uint) { return x * y; } }
contract Test {
function f(uint x) public returns (uint) {
return Lib.m(x, 9);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "Lib");
compileAndRun(sourceCode, 0, "Test", bytes(), std::map<std::string, h160>{{":Lib", m_contractAddress}});
ABI_CHECK(callContractFunction("f(uint256)", u256(33)), encodeArgs(u256(33) * 9));
)
}
BOOST_AUTO_TEST_CASE(library_function_external)
{
char const* sourceCode = R"(
library Lib { function m(bytes calldata b) external pure returns (bytes1) { return b[2]; } }
contract Test {
function f(bytes memory b) public pure returns (bytes1) {
return Lib.m(b);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "Lib");
compileAndRun(sourceCode, 0, "Test", bytes(), std::map<std::string, h160>{{":Lib", m_contractAddress}});
ABI_CHECK(callContractFunction("f(bytes)", u256(0x20), u256(5), "abcde"), encodeArgs("c"));
)
}
BOOST_AUTO_TEST_CASE(using_library_mappings_external)
{
char const* libSourceCode = R"(
library Lib {
function set(mapping(uint => uint) storage m, uint key, uint value) external
{
m[key] = value * 2;
}
}
)";
char const* sourceCode = R"(
library Lib {
function set(mapping(uint => uint) storage m, uint key, uint value) external {}
}
contract Test {
mapping(uint => uint) m1;
mapping(uint => uint) m2;
function f() public returns (uint, uint, uint, uint, uint, uint)
{
Lib.set(m1, 0, 1);
Lib.set(m1, 2, 42);
Lib.set(m2, 0, 23);
Lib.set(m2, 2, 99);
return (m1[0], m1[1], m1[2], m2[0], m2[1], m2[2]);
}
}
)";
for (auto v2: {false, true})
{
std::string prefix = "pragma abicoder " + std::string(v2 ? "v2" : "v1") + ";\n";
compileAndRun(prefix + libSourceCode, 0, "Lib");
compileAndRun(prefix + sourceCode, 0, "Test", bytes(), std::map<std::string, h160>{{":Lib", m_contractAddress}});
ABI_CHECK(callContractFunction("f()"), encodeArgs(u256(2), u256(0), u256(84), u256(46), u256(0), u256(198)));
}
}
BOOST_AUTO_TEST_CASE(short_strings)
{
// This test verifies that the byte array encoding that combines length and data works
// correctly.
char const* sourceCode = R"(
contract A {
bytes public data1 = "123";
bytes data2;
function lengthChange() public returns (uint)
{
// store constant in short and long string
data1 = "123";
if (!equal(data1, "123")) return 1;
data2 = "12345678901234567890123456789012345678901234567890a";
if (data2[17] != "8") return 3;
if (data2.length != 51) return 4;
if (data2[data2.length - 1] != "a") return 5;
// change length: short -> short
while (data1.length < 5)
data1.push();
if (data1.length != 5) return 6;
data1[4] = "4";
if (data1[0] != "1") return 7;
if (data1[4] != "4") return 8;
// change length: short -> long
while (data1.length < 80)
data1.push();
if (data1.length != 80) return 9;
while (data1.length > 70)
data1.pop();
if (data1.length != 70) return 9;
if (data1[0] != "1") return 10;
if (data1[4] != "4") return 11;
for (uint i = 0; i < data1.length; i ++)
data1[i] = bytes1(uint8(i * 3));
if (uint8(data1[4]) != 4 * 3) return 12;
if (uint8(data1[67]) != 67 * 3) return 13;
// change length: long -> short
while (data1.length > 22)
data1.pop();
if (data1.length != 22) return 14;
if (uint8(data1[21]) != 21 * 3) return 15;
if (uint8(data1[2]) != 2 * 3) return 16;
// change length: short -> shorter
while (data1.length > 19)
data1.pop();
if (data1.length != 19) return 17;
if (uint8(data1[7]) != 7 * 3) return 18;
// and now again to original size
while (data1.length < 22)
data1.push();
if (data1.length != 22) return 19;
if (data1[21] != 0) return 20;
while (data1.length > 0)
data1.pop();
while (data2.length > 0)
data2.pop();
}
function copy() public returns (uint) {
bytes memory x = "123";
bytes memory y = "012345678901234567890123456789012345678901234567890123456789";
bytes memory z = "1234567";
data1 = x;
data2 = y;
if (!equal(data1, x)) return 1;
if (!equal(data2, y)) return 2;
// lengthen
data1 = y;
if (!equal(data1, y)) return 3;
// shorten
data1 = x;
if (!equal(data1, x)) return 4;
// change while keeping short
data1 = z;
if (!equal(data1, z)) return 5;
// copy storage -> storage
data1 = x;
data2 = y;
// lengthen
data1 = data2;
if (!equal(data1, y)) return 6;
// shorten
data1 = x;
data2 = data1;
if (!equal(data2, x)) return 7;
bytes memory c = data2;
data1 = c;
if (!equal(data1, x)) return 8;
data1 = "";
data2 = "";
}
function deleteElements() public returns (uint) {
data1 = "01234";
delete data1[2];
if (data1[2] != 0) return 1;
if (data1[0] != "0") return 2;
if (data1[3] != "3") return 3;
delete data1;
if (data1.length != 0) return 4;
}
function equal(bytes storage a, bytes memory b) internal returns (bool) {
if (a.length != b.length) return false;
for (uint i = 0; i < a.length; ++i) if (a[i] != b[i]) return false;
return true;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "A");
ABI_CHECK(callContractFunction("data1()"), encodeDyn(std::string("123")));
ABI_CHECK(callContractFunction("lengthChange()"), encodeArgs(u256(0)));
BOOST_CHECK(storageEmpty(m_contractAddress));
ABI_CHECK(callContractFunction("deleteElements()"), encodeArgs(u256(0)));
BOOST_CHECK(storageEmpty(m_contractAddress));
ABI_CHECK(callContractFunction("copy()"), encodeArgs(u256(0)));
BOOST_CHECK(storageEmpty(m_contractAddress));
)
}
BOOST_AUTO_TEST_CASE(calldata_offset)
{
// This tests a specific bug that was caused by not using the correct memory offset in the
// calldata unpacker.
char const* sourceCode = R"(
contract CB
{
address[] _arr;
string public last = "nd";
constructor(address[] memory guardians)
{
_arr = guardians;
}
}
)";
compileAndRun(sourceCode, 0, "CB", encodeArgs(u256(0x20), u256(0x00)));
ABI_CHECK(callContractFunction("last()", encodeArgs()), encodeDyn(std::string("nd")));
}
BOOST_AUTO_TEST_CASE(reject_ether_sent_to_library)
{
char const* sourceCode = R"(
library lib {}
contract c {
constructor() payable {}
function f(address payable x) public returns (bool) {
return x.send(1);
}
receive () external payable {}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "lib");
Address libraryAddress = m_contractAddress;
compileAndRun(sourceCode, 10, "c");
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 10);
BOOST_CHECK_EQUAL(balanceAt(libraryAddress), 0);
ABI_CHECK(callContractFunction("f(address)", encodeArgs(libraryAddress)), encodeArgs(false));
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 10);
BOOST_CHECK_EQUAL(balanceAt(libraryAddress), 0);
ABI_CHECK(callContractFunction("f(address)", encodeArgs(m_contractAddress)), encodeArgs(true));
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 10);
BOOST_CHECK_EQUAL(balanceAt(libraryAddress), 0);
)
}
BOOST_AUTO_TEST_CASE(create_memory_array_allocation_size)
{
// Check allocation size of byte array. Should be 32 plus length rounded up to next
// multiple of 32
char const* sourceCode = R"(
contract C {
function f() public pure returns (uint d1, uint d2, uint d3, uint memsize) {
bytes memory b1 = new bytes(31);
bytes memory b2 = new bytes(32);
bytes memory b3 = new bytes(256);
bytes memory b4 = new bytes(31);
assembly {
d1 := sub(b2, b1)
d2 := sub(b3, b2)
d3 := sub(b4, b3)
memsize := msize()
}
}
}
)";
if (!m_optimiserSettings.runYulOptimiser)
{
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f()"), encodeArgs(0x40, 0x40, 0x20 + 256, 0x260));
}
}
BOOST_AUTO_TEST_CASE(inline_long_string_return)
{
char const* sourceCode = R"(
contract C {
function f() public returns (string memory) {
return (["somethingShort", "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"][1]);
}
}
)";
std::string strLong = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789001234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f()"), encodeDyn(strLong));
}
BOOST_AUTO_TEST_CASE(index_access_with_type_conversion)
{
// Test for a bug where higher order bits cleanup was not done for array index access.
char const* sourceCode = R"(
contract C {
function f(uint x) public returns (uint[256] memory r){
r[uint8(x)] = 2;
}
}
)";
compileAndRun(sourceCode, 0, "C");
// neither of the two should throw due to out-of-bounds access
BOOST_CHECK(callContractFunction("f(uint256)", u256(0x01)).size() == 256 * 32);
BOOST_CHECK(callContractFunction("f(uint256)", u256(0x101)).size() == 256 * 32);
}
BOOST_AUTO_TEST_CASE(correctly_initialize_memory_array_in_constructor)
{
// Memory arrays are initialized using calldatacopy past the size of the calldata.
// This test checks that it also works in the constructor context.
char const* sourceCode = R"(
contract C {
bool public success;
constructor() {
// Make memory dirty.
assembly {
for { let i := 0 } lt(i, 64) { i := add(i, 1) } {
mstore(msize(), not(0))
}
}
uint16[3] memory c;
require(c[0] == 0 && c[1] == 0 && c[2] == 0);
uint16[] memory x = new uint16[](3);
require(x[0] == 0 && x[1] == 0 && x[2] == 0);
success = true;
}
}
)";
// Cannot run against yul optimizer because of msize
if (!m_optimiserSettings.runYulOptimiser)
{
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("success()"), encodeArgs(u256(1)));
}
}
BOOST_AUTO_TEST_CASE(mutex)
{
char const* sourceCode = R"(
contract mutexed {
bool locked;
modifier protected {
if (locked) revert();
locked = true;
_;
locked = false;
}
}
contract Fund is mutexed {
uint shares;
constructor() payable { shares = msg.value; }
function withdraw(uint amount) public protected returns (uint) {
// NOTE: It is very bad practice to write this function this way.
// Please refer to the documentation of how to do this properly.
if (amount > shares) revert();
(bool success,) = msg.sender.call{value: amount}("");
require(success);
shares -= amount;
return shares;
}
function withdrawUnprotected(uint amount) public returns (uint) {
// NOTE: It is very bad practice to write this function this way.
// Please refer to the documentation of how to do this properly.
if (amount > shares) revert();
(bool success,) = msg.sender.call{value: amount}("");
require(success);
shares -= amount;
return shares;
}
}
contract Attacker {
Fund public fund;
uint callDepth;
bool protected;
function setProtected(bool _protected) public { protected = _protected; }
constructor(Fund _fund) { fund = _fund; }
function attack() public returns (uint) {
callDepth = 0;
return attackInternal();
}
function attackInternal() internal returns (uint) {
if (protected)
return fund.withdraw(10);
else
return fund.withdrawUnprotected(10);
}
fallback() external payable {
callDepth++;
if (callDepth < 4)
attackInternal();
}
}
)";
compileAndRun(sourceCode, 500, "Fund");
h160 const fund = m_contractAddress;
BOOST_CHECK_EQUAL(balanceAt(fund), 500);
compileAndRun(sourceCode, 0, "Attacker", encodeArgs(fund));
ABI_CHECK(callContractFunction("setProtected(bool)", true), encodeArgs());
ABI_CHECK(callContractFunction("attack()"), encodeArgs());
BOOST_CHECK_EQUAL(balanceAt(fund), 500);
ABI_CHECK(callContractFunction("setProtected(bool)", false), encodeArgs());
ABI_CHECK(callContractFunction("attack()"), encodeArgs(u256(460)));
BOOST_CHECK_EQUAL(balanceAt(fund), 460);
}
BOOST_AUTO_TEST_CASE(payable_function)
{
char const* sourceCode = R"(
contract C {
uint public a;
function f() payable public returns (uint) {
return msg.value;
}
fallback() external payable {
a = msg.value + 1;
}
}
)";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunctionWithValue("f()", 27), encodeArgs(u256(27)));
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 27);
ABI_CHECK(callContractFunctionWithValue("", 27), encodeArgs());
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 27 + 27);
ABI_CHECK(callContractFunction("a()"), encodeArgs(u256(28)));
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 27 + 27);
}
BOOST_AUTO_TEST_CASE(non_payable_throw)
{
char const* sourceCode = R"(
contract C {
uint public a;
function f() public returns (uint) {
return msgvalue();
}
function msgvalue() internal returns (uint) {
return msg.value;
}
fallback() external {
update();
}
function update() internal {
a = msg.value + 1;
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunctionWithValue("f()", 27), encodeArgs());
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 0);
ABI_CHECK(callContractFunction(""), encodeArgs());
ABI_CHECK(callContractFunction("a()"), encodeArgs(u256(1)));
ABI_CHECK(callContractFunctionWithValue("", 27), encodeArgs());
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 0);
ABI_CHECK(callContractFunction("a()"), encodeArgs(u256(1)));
ABI_CHECK(callContractFunctionWithValue("a()", 27), encodeArgs());
BOOST_CHECK_EQUAL(balanceAt(m_contractAddress), 0);
)
}
BOOST_AUTO_TEST_CASE(mem_resize_is_not_paid_at_call)
{
// This tests that memory resize for return values is not paid during the call, which would
// make the gas calculation overly complex. We access the end of the output area before
// the call is made.
// Tests that this also survives the optimizer.
char const* sourceCode = R"(
contract C {
function f() public returns (uint[200] memory) {}
}
contract D {
function f(C c) public returns (uint) { c.f(); return 7; }
}
)";
compileAndRun(sourceCode, 0, "C");
h160 const cAddr = m_contractAddress;
compileAndRun(sourceCode, 0, "D");
ABI_CHECK(callContractFunction("f(address)", cAddr), encodeArgs(u256(7)));
}
BOOST_AUTO_TEST_CASE(receive_external_function_type)
{
char const* sourceCode = R"(
contract C {
function g() public returns (uint) { return 7; }
function f(function() external returns (uint) g) public returns (uint) {
return g();
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction(
"f(function)",
m_contractAddress.asBytes() + util::selectorFromSignatureH32("g()").asBytes() + bytes(32 - 4 - 20, 0)
), encodeArgs(u256(7)));
)
}
BOOST_AUTO_TEST_CASE(return_external_function_type)
{
char const* sourceCode = R"(
contract C {
function g() public {}
function f() public returns (function() external) {
return this.g;
}
}
)";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(
callContractFunction("f()"),
m_contractAddress.asBytes() + util::selectorFromSignatureH32("g()").asBytes() + bytes(32 - 4 - 20, 0)
);
}
// TODO: store attached internal library functions
BOOST_AUTO_TEST_CASE(shift_bytes)
{
char const* sourceCode = R"(
contract C {
function left(bytes20 x, uint8 y) public returns (bytes20) {
return x << y;
}
function right(bytes20 x, uint8 y) public returns (bytes20) {
return x >> y;
}
}
)";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("left(bytes20,uint8)", "12345678901234567890", 8 * 8), encodeArgs("901234567890" + std::string(8, 0)));
ABI_CHECK(callContractFunction("right(bytes20,uint8)", "12345678901234567890", 8 * 8), encodeArgs(std::string(8, 0) + "123456789012"));
}
BOOST_AUTO_TEST_CASE(contracts_separated_with_comment)
{
char const* sourceCode = R"(
contract C1 {}
/**
**/
contract C2 {}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C1");
compileAndRun(sourceCode, 0, "C2");
)
}
BOOST_AUTO_TEST_CASE(include_creation_bytecode_only_once)
{
char const* sourceCode = R"(
contract D {
bytes a = hex"1237651237125387136581271652831736512837126583171583712358126123765123712538713658127165283173651283712658317158371235812612376512371253871365812716528317365128371265831715837123581261237651237125387136581271652831736512837126583171583712358126";
bytes b = hex"1237651237125327136581271252831736512837126583171383712358126123765125712538713658127165253173651283712658357158371235812612376512371a5387136581271652a317365128371265a317158371235812612a765123712538a13658127165a83173651283712a58317158371235a126";
constructor(uint) {}
}
contract Double {
function f() public {
new D(2);
}
function g() public {
new D(3);
}
}
contract Single {
function f() public {
new D(2);
}
}
)";
compileAndRun(sourceCode);
BOOST_CHECK_LE(
double(m_compiler.object("Double").bytecode.size()),
1.2 * double(m_compiler.object("Single").bytecode.size())
);
}
BOOST_AUTO_TEST_CASE(revert_with_cause)
{
char const* sourceCode = R"(
contract D {
string constant msg1 = "test1234567890123456789012345678901234567890";
string msg2 = "test1234567890123456789012345678901234567890";
function f() public {
revert("test123");
}
function g() public {
revert("test1234567890123456789012345678901234567890");
}
function h() public {
revert(msg1);
}
function i() public {
revert(msg2);
}
function j() public {
string memory msg3 = "test1234567890123456789012345678901234567890";
revert(msg3);
}
}
contract C {
D d = new D();
function forward(address target, bytes memory data) internal returns (bool success, bytes memory retval) {
uint retsize;
assembly {
success := call(not(0), target, 0, add(data, 0x20), mload(data), 0, 0)
retsize := returndatasize()
}
retval = new bytes(retsize);
assembly {
returndatacopy(add(retval, 0x20), 0, returndatasize())
}
}
function f() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function g() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function h() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function i() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function j() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
}
)";
if (solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
compileAndRun(sourceCode, 0, "C");
bytes const errorSignature = bytes{0x08, 0xc3, 0x79, 0xa0};
ABI_CHECK(callContractFunction("f()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 7, "test123") + bytes(28, 0));
ABI_CHECK(callContractFunction("g()"), encodeArgs(0, 0x40, 0x84) + errorSignature + encodeArgs(0x20, 44, "test1234567890123456789012345678901234567890") + bytes(28, 0));
ABI_CHECK(callContractFunction("h()"), encodeArgs(0, 0x40, 0x84) + errorSignature + encodeArgs(0x20, 44, "test1234567890123456789012345678901234567890") + bytes(28, 0));
ABI_CHECK(callContractFunction("i()"), encodeArgs(0, 0x40, 0x84) + errorSignature + encodeArgs(0x20, 44, "test1234567890123456789012345678901234567890") + bytes(28, 0));
ABI_CHECK(callContractFunction("j()"), encodeArgs(0, 0x40, 0x84) + errorSignature + encodeArgs(0x20, 44, "test1234567890123456789012345678901234567890") + bytes(28, 0));
}
}
BOOST_AUTO_TEST_CASE(require_with_message)
{
char const* sourceCode = R"(
contract D {
bool flag = false;
string storageError = "abc";
string constant constantError = "abc";
function f(uint x) public {
require(x > 7, "failed");
}
function g() public {
// As a side-effect of internalFun, the flag will be set to true
// (even if the condition is true),
// but it will only throw in the next evaluation.
bool flagCopy = flag;
require(flagCopy == false, internalFun());
}
function internalFun() public returns (string memory) {
flag = true;
return "only on second run";
}
function h() public {
require(false, storageError);
}
function i() public {
require(false, constantError);
}
function j() public {
string memory errMsg = "msg";
require(false, errMsg);
}
}
contract C {
D d = new D();
function forward(address target, bytes memory data) internal returns (bool success, bytes memory retval) {
uint retsize;
assembly {
success := call(not(0), target, 0, add(data, 0x20), mload(data), 0, 0)
retsize := returndatasize()
}
retval = new bytes(retsize);
assembly {
returndatacopy(add(retval, 0x20), 0, returndatasize())
}
}
function f(uint x) public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function g() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function h() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function i() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function j() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
}
)";
if (solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
compileAndRun(sourceCode, 0, "C");
bytes const errorSignature = bytes{0x08, 0xc3, 0x79, 0xa0};
ABI_CHECK(callContractFunction("f(uint256)", 8), encodeArgs(1, 0x40, 0));
ABI_CHECK(callContractFunction("f(uint256)", 5), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 6, "failed") + bytes(28, 0));
ABI_CHECK(callContractFunction("g()"), encodeArgs(1, 0x40, 0));
ABI_CHECK(callContractFunction("g()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 18, "only on second run") + bytes(28, 0));
ABI_CHECK(callContractFunction("h()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 3, "abc") + bytes(28, 0));
ABI_CHECK(callContractFunction("i()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 3, "abc") + bytes(28, 0));
ABI_CHECK(callContractFunction("j()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 3, "msg") + bytes(28, 0));
}
}
BOOST_AUTO_TEST_CASE(bubble_up_error_messages)
{
char const* sourceCode = R"(
contract D {
function f() public {
revert("message");
}
function g() public {
this.f();
}
}
contract C {
D d = new D();
function forward(address target, bytes memory data) internal returns (bool success, bytes memory retval) {
uint retsize;
assembly {
success := call(not(0), target, 0, add(data, 0x20), mload(data), 0, 0)
retsize := returndatasize()
}
retval = new bytes(retsize);
assembly {
returndatacopy(add(retval, 0x20), 0, returndatasize())
}
}
function f() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
function g() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
}
)";
if (solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
compileAndRun(sourceCode, 0, "C");
bytes const errorSignature = bytes{0x08, 0xc3, 0x79, 0xa0};
ABI_CHECK(callContractFunction("f()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 7, "message") + bytes(28, 0));
ABI_CHECK(callContractFunction("g()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 7, "message") + bytes(28, 0));
}
}
BOOST_AUTO_TEST_CASE(bubble_up_error_messages_through_transfer)
{
char const* sourceCode = R"(
contract D {
receive() external payable {
revert("message");
}
function f() public {
payable(this).transfer(0);
}
}
contract C {
D d = new D();
function forward(address target, bytes memory data) internal returns (bool success, bytes memory retval) {
uint retsize;
assembly {
success := call(not(0), target, 0, add(data, 0x20), mload(data), 0, 0)
retsize := returndatasize()
}
retval = new bytes(retsize);
assembly {
returndatacopy(add(retval, 0x20), 0, returndatasize())
}
}
function f() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
}
)";
if (solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
compileAndRun(sourceCode, 0, "C");
bytes const errorSignature = bytes{0x08, 0xc3, 0x79, 0xa0};
ABI_CHECK(callContractFunction("f()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 7, "message") + bytes(28, 0));
}
}
BOOST_AUTO_TEST_CASE(bubble_up_error_messages_through_create)
{
char const* sourceCode = R"(
contract E {
constructor() {
revert("message");
}
}
contract D {
function f() public {
E x = new E();
}
}
contract C {
D d = new D();
function forward(address target, bytes memory data) internal returns (bool success, bytes memory retval) {
uint retsize;
assembly {
success := call(not(0), target, 0, add(data, 0x20), mload(data), 0, 0)
retsize := returndatasize()
}
retval = new bytes(retsize);
assembly {
returndatacopy(add(retval, 0x20), 0, returndatasize())
}
}
function f() public returns (bool, bytes memory) {
return forward(address(d), msg.data);
}
}
)";
if (solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
compileAndRun(sourceCode, 0, "C");
bytes const errorSignature = bytes{0x08, 0xc3, 0x79, 0xa0};
ABI_CHECK(callContractFunction("f()"), encodeArgs(0, 0x40, 0x64) + errorSignature + encodeArgs(0x20, 7, "message") + bytes(28, 0));
}
}
BOOST_AUTO_TEST_CASE(interface_contract)
{
char const* sourceCode = R"(
interface I {
event A();
function f() external returns (bool);
fallback() external payable;
}
contract A is I {
function f() public override returns (bool) {
return g();
}
function g() public returns (bool) {
return true;
}
fallback() override external payable {
}
}
contract C {
function f(address payable _interfaceAddress) public returns (bool) {
I i = I(_interfaceAddress);
return i.f();
}
}
)";
compileAndRun(sourceCode, 0, "A");
h160 const recipient = m_contractAddress;
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f(address)", recipient), encodeArgs(true));
}
BOOST_AUTO_TEST_CASE(bare_call_invalid_address)
{
char const* sourceCode = R"YY(
contract C {
/// Calling into non-existent account is successful (creates the account)
function f() external returns (bool) {
(bool success,) = address(0x4242).call("");
return success;
}
function h() external returns (bool) {
(bool success,) = address(0x4242).delegatecall("");
return success;
}
}
)YY";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f()"), encodeArgs(u256(1)));
ABI_CHECK(callContractFunction("h()"), encodeArgs(u256(1)));
if (solidity::test::CommonOptions::get().evmVersion().hasStaticCall())
{
char const* sourceCode = R"YY(
contract C {
function f() external returns (bool, bytes memory) {
return address(0x4242).staticcall("");
}
}
)YY";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f()"), encodeArgs(u256(1), 0x40, 0x00));
}
}
BOOST_AUTO_TEST_CASE(bare_call_return_data)
{
if (solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
{
std::vector<std::string> calltypes = {"call", "delegatecall"};
if (solidity::test::CommonOptions::get().evmVersion().hasStaticCall())
calltypes.emplace_back("staticcall");
for (std::string const& calltype: calltypes)
{
std::string sourceCode = R"DELIMITER(
contract A {
constructor() {
}
function return_bool() public pure returns(bool) {
return true;
}
function return_int32() public pure returns(int32) {
return -32;
}
function return_uint32() public pure returns(uint32) {
return 0x3232;
}
function return_int256() public pure returns(int256) {
return -256;
}
function return_uint256() public pure returns(uint256) {
return 0x256256;
}
function return_bytes4() public pure returns(bytes4) {
return 0xabcd0012;
}
function return_multi() public pure returns(bool, uint32, bytes4) {
return (false, 0x3232, 0xabcd0012);
}
function return_bytes() public pure returns(bytes memory b) {
b = new bytes(2);
b[0] = 0x42;
b[1] = 0x21;
}
}
contract C {
A addr;
constructor() {
addr = new A();
}
function f(string memory signature) public returns (bool, bytes memory) {
return address(addr).)DELIMITER" + calltype + R"DELIMITER((abi.encodeWithSignature(signature));
}
function check_bool() external returns (bool) {
(bool success, bytes memory data) = f("return_bool()");
assert(success);
bool a = abi.decode(data, (bool));
assert(a);
return true;
}
function check_int32() external returns (bool) {
(bool success, bytes memory data) = f("return_int32()");
assert(success);
int32 a = abi.decode(data, (int32));
assert(a == -32);
return true;
}
function check_uint32() external returns (bool) {
(bool success, bytes memory data) = f("return_uint32()");
assert(success);
uint32 a = abi.decode(data, (uint32));
assert(a == 0x3232);
return true;
}
function check_int256() external returns (bool) {
(bool success, bytes memory data) = f("return_int256()");
assert(success);
int256 a = abi.decode(data, (int256));
assert(a == -256);
return true;
}
function check_uint256() external returns (bool) {
(bool success, bytes memory data) = f("return_uint256()");
assert(success);
uint256 a = abi.decode(data, (uint256));
assert(a == 0x256256);
return true;
}
function check_bytes4() external returns (bool) {
(bool success, bytes memory data) = f("return_bytes4()");
assert(success);
bytes4 a = abi.decode(data, (bytes4));
assert(a == 0xabcd0012);
return true;
}
function check_multi() external returns (bool) {
(bool success, bytes memory data) = f("return_multi()");
assert(success);
(bool a, uint32 b, bytes4 c) = abi.decode(data, (bool, uint32, bytes4));
assert(a == false && b == 0x3232 && c == 0xabcd0012);
return true;
}
function check_bytes() external returns (bool) {
(bool success, bytes memory data) = f("return_bytes()");
assert(success);
(bytes memory d) = abi.decode(data, (bytes));
assert(d.length == 2 && d[0] == 0x42 && d[1] == 0x21);
return true;
}
}
)DELIMITER";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_bool()"))), encodeArgs(true, 0x40, 0x20, true));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_int32()"))), encodeArgs(true, 0x40, 0x20, u256(-32)));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_uint32()"))), encodeArgs(true, 0x40, 0x20, u256(0x3232)));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_int256()"))), encodeArgs(true, 0x40, 0x20, u256(-256)));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_uint256()"))), encodeArgs(true, 0x40, 0x20, u256(0x256256)));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_bytes4()"))), encodeArgs(true, 0x40, 0x20, u256(0xabcd0012) << (28*8)));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_multi()"))), encodeArgs(true, 0x40, 0x60, false, u256(0x3232), u256(0xabcd0012) << (28*8)));
ABI_CHECK(callContractFunction("f(string)", encodeDyn(std::string("return_bytes()"))), encodeArgs(true, 0x40, 0x60, 0x20, 0x02, encode(bytes{0x42,0x21}, false)));
ABI_CHECK(callContractFunction("check_bool()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_int32()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_uint32()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_int256()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_uint256()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_bytes4()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_multi()"), encodeArgs(true));
ABI_CHECK(callContractFunction("check_bytes()"), encodeArgs(true));
)
}
}
}
BOOST_AUTO_TEST_CASE(abi_encodePacked)
{
char const* sourceCode = R"(
contract C {
function f0() public pure returns (bytes memory) {
return abi.encodePacked();
}
function f1() public pure returns (bytes memory) {
return abi.encodePacked(uint8(1), uint8(2));
}
function f2() public pure returns (bytes memory) {
string memory x = "abc";
return abi.encodePacked(uint8(1), x, uint8(2));
}
function f3() public pure returns (bytes memory r) {
// test that memory is properly allocated
string memory x = "abc";
r = abi.encodePacked(uint8(1), x, uint8(2));
bytes memory y = "def";
require(y[0] == "d");
y[0] = "e";
require(y[0] == "e");
}
function f4() public pure returns (bytes memory) {
string memory x = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
return abi.encodePacked(uint16(0x0701), x, uint16(0x1201));
}
function f_literal() public pure returns (bytes memory) {
return abi.encodePacked(uint8(0x01), "abc", uint8(0x02));
}
function f_calldata() public pure returns (bytes memory) {
return abi.encodePacked(uint8(0x01), msg.data, uint8(0x02));
}
}
)";
for (auto v2: {false, true})
{
ALSO_VIA_YUL(
std::string prefix = "pragma abicoder " + std::string(v2 ? "v2" : "v1") + ";\n";
compileAndRun(prefix + sourceCode, 0, "C");
ABI_CHECK(callContractFunction("f0()"), encodeArgs(0x20, 0));
ABI_CHECK(callContractFunction("f1()"), encodeArgs(0x20, 2, "\x01\x02"));
ABI_CHECK(callContractFunction("f2()"), encodeArgs(0x20, 5, "\x01" "abc" "\x02"));
ABI_CHECK(callContractFunction("f3()"), encodeArgs(0x20, 5, "\x01" "abc" "\x02"));
ABI_CHECK(callContractFunction("f4()"), encodeArgs(0x20, 2 + 26 + 26 + 2, "\x07\x01" "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" "\x12\x01"));
ABI_CHECK(callContractFunction("f_literal()"), encodeArgs(0x20, 5, "\x01" "abc" "\x02"));
ABI_CHECK(callContractFunction("f_calldata()"), encodeArgs(0x20, 6, "\x01" "\xa5\xbf\xa1\xee" "\x02"));
)
}
}
BOOST_AUTO_TEST_CASE(abi_encodePacked_from_storage)
{
char const* sourceCode = R"(
contract C {
uint24[9] small_fixed;
int24[9] small_fixed_signed;
uint24[] small_dyn;
uint248[5] large_fixed;
uint248[] large_dyn;
bytes bytes_storage;
function sf() public returns (bytes memory) {
small_fixed[0] = 0xfffff1;
small_fixed[2] = 0xfffff2;
small_fixed[5] = 0xfffff3;
small_fixed[8] = 0xfffff4;
return abi.encodePacked(uint8(0x01), small_fixed, uint8(0x02));
}
function sd() public returns (bytes memory) {
small_dyn.push(0xfffff1);
small_dyn.push(0x00);
small_dyn.push(0xfffff2);
small_dyn.push(0x00);
small_dyn.push(0x00);
small_dyn.push(0xfffff3);
small_dyn.push(0x00);
small_dyn.push(0x00);
small_dyn.push(0xfffff4);
return abi.encodePacked(uint8(0x01), small_dyn, uint8(0x02));
}
function sfs() public returns (bytes memory) {
small_fixed_signed[0] = -2;
small_fixed_signed[2] = 0xffff2;
small_fixed_signed[5] = -200;
small_fixed_signed[8] = 0xffff4;
return abi.encodePacked(uint8(0x01), small_fixed_signed, uint8(0x02));
}
function lf() public returns (bytes memory) {
large_fixed[0] = 2**248-1;
large_fixed[1] = 0xfffff2;
large_fixed[2] = 2**248-2;
large_fixed[4] = 0xfffff4;
return abi.encodePacked(uint8(0x01), large_fixed, uint8(0x02));
}
function ld() public returns (bytes memory) {
large_dyn.push(2**248-1);
large_dyn.push(0xfffff2);
large_dyn.push(2**248-2);
large_dyn.push(0);
large_dyn.push(0xfffff4);
return abi.encodePacked(uint8(0x01), large_dyn, uint8(0x02));
}
function bytes_short() public returns (bytes memory) {
bytes_storage = "abcd";
return abi.encodePacked(uint8(0x01), bytes_storage, uint8(0x02));
}
function bytes_long() public returns (bytes memory) {
bytes_storage = "0123456789012345678901234567890123456789";
return abi.encodePacked(uint8(0x01), bytes_storage, uint8(0x02));
}
}
)";
for (auto v2: {false, true})
{
ALSO_VIA_YUL(
std::string prefix = "pragma abicoder " + std::string(v2 ? "v2" : "v1") + ";\n";
compileAndRun(prefix + sourceCode, 0, "C");
bytes payload = encodeArgs(0xfffff1, 0, 0xfffff2, 0, 0, 0xfffff3, 0, 0, 0xfffff4);
bytes encoded = encodeArgs(0x20, 0x122, "\x01" + asString(payload) + "\x02");
ABI_CHECK(callContractFunction("sf()"), encoded);
ABI_CHECK(callContractFunction("sd()"), encoded);
ABI_CHECK(callContractFunction("sfs()"), encodeArgs(0x20, 0x122, "\x01" + asString(encodeArgs(
u256(-2), 0, 0xffff2, 0, 0, u256(-200), 0, 0, 0xffff4
)) + "\x02"));
payload = encodeArgs(
u256("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
0xfffff2,
u256("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"),
0,
0xfffff4
);
ABI_CHECK(callContractFunction("lf()"), encodeArgs(0x20, 5 * 32 + 2, "\x01" + asString(encodeArgs(payload)) + "\x02"));
ABI_CHECK(callContractFunction("ld()"), encodeArgs(0x20, 5 * 32 + 2, "\x01" + asString(encodeArgs(payload)) + "\x02"));
ABI_CHECK(callContractFunction("bytes_short()"), encodeArgs(0x20, 6, "\x01" "abcd\x02"));
ABI_CHECK(callContractFunction("bytes_long()"), encodeArgs(0x20, 42, "\x01" "0123456789012345678901234567890123456789\x02"));
)
}
}
BOOST_AUTO_TEST_CASE(abi_encodePacked_from_memory)
{
char const* sourceCode = R"(
contract C {
function sf() public pure returns (bytes memory) {
uint24[9] memory small_fixed;
small_fixed[0] = 0xfffff1;
small_fixed[2] = 0xfffff2;
small_fixed[5] = 0xfffff3;
small_fixed[8] = 0xfffff4;
return abi.encodePacked(uint8(0x01), small_fixed, uint8(0x02));
}
function sd() public pure returns (bytes memory) {
uint24[] memory small_dyn = new uint24[](9);
small_dyn[0] = 0xfffff1;
small_dyn[2] = 0xfffff2;
small_dyn[5] = 0xfffff3;
small_dyn[8] = 0xfffff4;
return abi.encodePacked(uint8(0x01), small_dyn, uint8(0x02));
}
function sfs() public pure returns (bytes memory) {
int24[9] memory small_fixed_signed;
small_fixed_signed[0] = -2;
small_fixed_signed[2] = 0xffff2;
small_fixed_signed[5] = -200;
small_fixed_signed[8] = 0xffff4;
return abi.encodePacked(uint8(0x01), small_fixed_signed, uint8(0x02));
}
function lf() public pure returns (bytes memory) {
uint248[5] memory large_fixed;
large_fixed[0] = 2**248-1;
large_fixed[1] = 0xfffff2;
large_fixed[2] = 2**248-2;
large_fixed[4] = 0xfffff4;
return abi.encodePacked(uint8(0x01), large_fixed, uint8(0x02));
}
function ld() public pure returns (bytes memory) {
uint248[] memory large_dyn = new uint248[](5);
large_dyn[0] = 2**248-1;
large_dyn[1] = 0xfffff2;
large_dyn[2] = 2**248-2;
large_dyn[4] = 0xfffff4;
return abi.encodePacked(uint8(0x01), large_dyn, uint8(0x02));
}
}
)";
for (auto v2: {false, true})
{
ALSO_VIA_YUL(
std::string prefix = "pragma abicoder " + std::string(v2 ? "v2" : "v1") + ";\n";
compileAndRun(prefix + sourceCode, 0, "C");
bytes payload = encodeArgs(0xfffff1, 0, 0xfffff2, 0, 0, 0xfffff3, 0, 0, 0xfffff4);
bytes encoded = encodeArgs(0x20, 0x122, "\x01" + asString(payload) + "\x02");
ABI_CHECK(callContractFunction("sf()"), encoded);
ABI_CHECK(callContractFunction("sd()"), encoded);
ABI_CHECK(callContractFunction("sfs()"), encodeArgs(0x20, 0x122, "\x01" + asString(encodeArgs(
u256(-2), 0, 0xffff2, 0, 0, u256(-200), 0, 0, 0xffff4
)) + "\x02"));
payload = encodeArgs(
u256("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
0xfffff2,
u256("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"),
0,
0xfffff4
);
ABI_CHECK(callContractFunction("lf()"), encodeArgs(0x20, 5 * 32 + 2, "\x01" + asString(encodeArgs(payload)) + "\x02"));
ABI_CHECK(callContractFunction("ld()"), encodeArgs(0x20, 5 * 32 + 2, "\x01" + asString(encodeArgs(payload)) + "\x02"));
)
}
}
BOOST_AUTO_TEST_CASE(abi_encodePacked_functionPtr)
{
char const* sourceCode = R"(
contract C {
C other = C(0x1112131400000000000011121314000000000087);
function testDirect() public view returns (bytes memory) {
return abi.encodePacked(uint8(8), other.f, uint8(2));
}
function testFixedArray() public view returns (bytes memory) {
function () external pure returns (bytes memory)[1] memory x;
x[0] = other.f;
return abi.encodePacked(uint8(8), x, uint8(2));
}
function testDynamicArray() public view returns (bytes memory) {
function () external pure returns (bytes memory)[] memory x = new function() external pure returns (bytes memory)[](1);
x[0] = other.f;
return abi.encodePacked(uint8(8), x, uint8(2));
}
function f() public pure returns (bytes memory) {}
}
)";
for (auto v2: {false, true})
{
ALSO_VIA_YUL(
std::string prefix = "pragma abicoder " + std::string(v2 ? "v2" : "v1") + ";\n";
compileAndRun(prefix + sourceCode, 0, "C");
std::string directEncoding = asString(fromHex("08" "1112131400000000000011121314000000000087" "26121ff0" "02"));
ABI_CHECK(callContractFunction("testDirect()"), encodeArgs(0x20, directEncoding.size(), directEncoding));
std::string arrayEncoding = asString(fromHex("08" "1112131400000000000011121314000000000087" "26121ff0" "0000000000000000" "02"));
ABI_CHECK(callContractFunction("testFixedArray()"), encodeArgs(0x20, arrayEncoding.size(), arrayEncoding));
ABI_CHECK(callContractFunction("testDynamicArray()"), encodeArgs(0x20, arrayEncoding.size(), arrayEncoding));
)
}
}
BOOST_AUTO_TEST_CASE(abi_encodePackedV2_structs)
{
char const* sourceCode = R"(
pragma abicoder v2;
contract C {
struct S {
uint8 a;
int16 b;
uint8[2] c;
int16[] d;
}
S s;
event E(S indexed);
constructor() {
s.a = 0x12;
s.b = -7;
s.c[0] = 2;
s.c[1] = 3;
s.d.push(-7);
s.d.push(-8);
}
function testStorage() public {
emit E(s);
}
function testMemory() public {
S memory m = s;
emit E(m);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C");
bytes structEnc = encodeArgs(int(0x12), u256(-7), int(2), int(3), u256(-7), u256(-8));
ABI_CHECK(callContractFunction("testStorage()"), encodeArgs());
BOOST_REQUIRE_EQUAL(numLogTopics(0), 2);
BOOST_CHECK_EQUAL(logTopic(0, 0), util::keccak256(std::string("E((uint8,int16,uint8[2],int16[]))")));
BOOST_CHECK_EQUAL(logTopic(0, 1), util::keccak256(asString(structEnc)));
ABI_CHECK(callContractFunction("testMemory()"), encodeArgs());
BOOST_REQUIRE_EQUAL(numLogTopics(0), 2);
BOOST_CHECK_EQUAL(logTopic(0, 0), util::keccak256(std::string("E((uint8,int16,uint8[2],int16[]))")));
BOOST_CHECK_EQUAL(logTopic(0, 1), util::keccak256(asString(structEnc)));
)
}
BOOST_AUTO_TEST_CASE(abi_encodePackedV2_nestedArray)
{
char const* sourceCode = R"(
pragma abicoder v2;
contract C {
struct S {
uint8 a;
int16 b;
}
event E(S[2][][3] indexed);
function testNestedArrays() public {
S[2][][3] memory x;
x[1] = new S[2][](2);
x[1][0][0].a = 1;
x[1][0][0].b = 2;
x[1][0][1].a = 3;
x[1][1][1].b = 4;
emit E(x);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C");
bytes structEnc = encodeArgs(1, 2, 3, 0, 0, 0, 0, 4);
ABI_CHECK(callContractFunction("testNestedArrays()"), encodeArgs());
BOOST_REQUIRE_EQUAL(numLogTopics(0), 2);
BOOST_CHECK_EQUAL(logTopic(0, 0), util::keccak256(std::string("E((uint8,int16)[2][][3])")));
BOOST_CHECK_EQUAL(logTopic(0, 1), util::keccak256(asString(structEnc)));
)
}
BOOST_AUTO_TEST_CASE(abi_encodePackedV2_arrayOfStrings)
{
char const* sourceCode = R"(
pragma abicoder v2;
contract C {
string[] x;
event E(string[] indexed);
constructor() {
x.push("abc");
x.push("0123456789012345678901234567890123456789");
}
function testStorage() public {
emit E(x);
}
function testMemory() public {
string[] memory y = x;
emit E(y);
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "C");
bytes arrayEncoding = encodeArgs("abc", "0123456789012345678901234567890123456789");
ABI_CHECK(callContractFunction("testStorage()"), encodeArgs());
BOOST_REQUIRE_EQUAL(numLogTopics(0), 2);
BOOST_CHECK_EQUAL(logTopic(0, 0), util::keccak256(std::string("E(string[])")));
BOOST_CHECK_EQUAL(logTopic(0, 1), util::keccak256(asString(arrayEncoding)));
ABI_CHECK(callContractFunction("testMemory()"), encodeArgs());
BOOST_REQUIRE_EQUAL(numLogTopics(0), 2);
BOOST_CHECK_EQUAL(logTopic(0, 0), util::keccak256(std::string("E(string[])")));
BOOST_CHECK_EQUAL(logTopic(0, 1), util::keccak256(asString(arrayEncoding)));
)
}
BOOST_AUTO_TEST_CASE(code_access)
{
char const* sourceCode = R"(
contract C {
function lengths() public pure returns (bool) {
uint crLen = type(D).creationCode.length;
uint runLen = type(D).runtimeCode.length;
require(runLen < crLen);
require(crLen >= 0x20);
require(runLen >= 0x20);
return true;
}
function creation() public pure returns (bytes memory) {
return type(D).creationCode;
}
function runtime() public pure returns (bytes memory) {
return type(D).runtimeCode;
}
function runtimeAllocCheck() public pure returns (bytes memory) {
uint[] memory a = new uint[](2);
bytes memory c = type(D).runtimeCode;
uint[] memory b = new uint[](2);
a[0] = 0x1111;
a[1] = 0x2222;
b[0] = 0x3333;
b[1] = 0x4444;
return c;
}
}
contract D {
function f() public pure returns (uint) { return 7; }
}
)";
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("lengths()"), encodeArgs(true));
bytes codeCreation = callContractFunction("creation()");
bytes codeRuntime1 = callContractFunction("runtime()");
bytes codeRuntime2 = callContractFunction("runtimeAllocCheck()");
ABI_CHECK(codeRuntime1, codeRuntime2);
}
BOOST_AUTO_TEST_CASE(contract_name)
{
char const* sourceCode = R"(
contract C {
string public nameAccessor = type(C).name;
string public constant constantNameAccessor = type(C).name;
function name() public virtual pure returns (string memory) {
return type(C).name;
}
}
contract D is C {
function name() public override pure returns (string memory) {
return type(D).name;
}
function name2() public pure returns (string memory) {
return type(C).name;
}
}
contract ThisIsAVeryLongContractNameExceeding256bits {
string public nameAccessor = type(ThisIsAVeryLongContractNameExceeding256bits).name;
string public constant constantNameAccessor = type(ThisIsAVeryLongContractNameExceeding256bits).name;
function name() public pure returns (string memory) {
return type(ThisIsAVeryLongContractNameExceeding256bits).name;
}
}
)";
compileAndRun(sourceCode, 0, "C");
bytes argsC = encodeArgs(u256(0x20), u256(1), "C");
ABI_CHECK(callContractFunction("name()"), argsC);
ABI_CHECK(callContractFunction("nameAccessor()"), argsC);
ABI_CHECK(callContractFunction("constantNameAccessor()"), argsC);
compileAndRun(sourceCode, 0, "D");
bytes argsD = encodeArgs(u256(0x20), u256(1), "D");
ABI_CHECK(callContractFunction("name()"), argsD);
ABI_CHECK(callContractFunction("name2()"), argsC);
std::string longName = "ThisIsAVeryLongContractNameExceeding256bits";
compileAndRun(sourceCode, 0, longName);
bytes argsLong = encodeArgs(u256(0x20), u256(longName.length()), longName);
ABI_CHECK(callContractFunction("name()"), argsLong);
ABI_CHECK(callContractFunction("nameAccessor()"), argsLong);
ABI_CHECK(callContractFunction("constantNameAccessor()"), argsLong);
}
BOOST_AUTO_TEST_CASE(event_wrong_abi_name)
{
char const* sourceCode = R"(
library ClientReceipt {
event Deposit(Test indexed _from, bytes32 indexed _id, uint _value);
function deposit(bytes32 _id) public {
Test a;
emit Deposit(a, _id, msg.value);
}
}
contract Test {
function f() public {
ClientReceipt.deposit("123");
}
}
)";
ALSO_VIA_YUL(
compileAndRun(sourceCode, 0, "ClientReceipt", bytes());
compileAndRun(sourceCode, 0, "Test", bytes(), std::map<std::string, h160>{{":ClientReceipt", m_contractAddress}});
callContractFunction("f()");
BOOST_REQUIRE_EQUAL(numLogs(), 1);
BOOST_CHECK_EQUAL(logAddress(0), m_contractAddress);
BOOST_REQUIRE_EQUAL(numLogTopics(0), 3);
BOOST_CHECK_EQUAL(logTopic(0, 0), util::keccak256(std::string("Deposit(address,bytes32,uint256)")));
)
}
BOOST_AUTO_TEST_CASE(dirty_scratch_space_prior_to_constant_optimiser)
{
char const* sourceCode = R"(
contract C {
event X(uint);
constructor() {
assembly {
// make scratch space dirty
mstore(0, 0x4242424242424242424242424242424242424242424242424242424242424242)
}
uint x = 0x0000000000001234123412431234123412412342112341234124312341234124;
// This is just to create many instances of x
unchecked { emit X(x + f() * g(tx.origin) ^ h(block.number)); }
assembly {
// make scratch space dirty
mstore(0, 0x4242424242424242424242424242424242424242424242424242424242424242)
}
emit X(x);
}
function f() internal pure returns (uint) {
return 0x0000000000001234123412431234123412412342112341234124312341234124;
}
function g(address a) internal pure returns (uint) {
unchecked { return uint(uint160(a)) * 0x0000000000001234123412431234123412412342112341234124312341234124; }
}
function h(uint a) internal pure returns (uint) {
unchecked { return a * 0x0000000000001234123412431234123412412342112341234124312341234124; }
}
}
)";
compileAndRun(sourceCode, 0, "C");
BOOST_REQUIRE_EQUAL(numLogs(), 2);
BOOST_CHECK_EQUAL(logAddress(1), m_contractAddress);
ABI_CHECK(
logData(1),
encodeArgs(u256("0x0000000000001234123412431234123412412342112341234124312341234124"))
);
}
BOOST_AUTO_TEST_CASE(strip_reason_strings)
{
char const* sourceCode = R"(
contract C {
function f(bool _x) public pure returns (uint) {
require(_x, "some reason");
return 7;
}
function g(bool _x) public pure returns (uint) {
string memory x = "some indirect reason";
require(_x, x);
return 8;
}
function f1(bool _x) public pure returns (uint) {
if (!_x) revert( /* */ "some reason" /* */ );
return 9;
}
function g1(bool _x) public pure returns (uint) {
string memory x = "some indirect reason";
if (!_x) revert(x);
return 10;
}
}
)";
ALSO_VIA_YUL(
m_revertStrings = RevertStrings::Default;
compileAndRun(sourceCode, 0, "C");
if (
m_optimiserSettings == OptimiserSettings::minimal() ||
m_optimiserSettings == OptimiserSettings::none()
)
// check that the reason string IS part of the binary.
BOOST_CHECK(util::toHex(m_output).find("736f6d6520726561736f6e") != std::string::npos);
m_revertStrings = RevertStrings::Strip;
compileAndRun(sourceCode, 0, "C");
// check that the reason string is NOT part of the binary.
BOOST_CHECK(util::toHex(m_output).find("736f6d6520726561736f6e") == std::string::npos);
ABI_CHECK(callContractFunction("f(bool)", true), encodeArgs(7));
ABI_CHECK(callContractFunction("f(bool)", false), encodeArgs());
ABI_CHECK(callContractFunction("g(bool)", true), encodeArgs(8));
ABI_CHECK(callContractFunction("g(bool)", false), encodeArgs());
ABI_CHECK(callContractFunction("f1(bool)", true), encodeArgs(9));
ABI_CHECK(callContractFunction("f1(bool)", false), encodeArgs());
ABI_CHECK(callContractFunction("g1(bool)", true), encodeArgs(10));
ABI_CHECK(callContractFunction("g1(bool)", false), encodeArgs());
)
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 120,464
|
C++
|
.cpp
| 3,634
| 29.519813
| 1,154
| 0.679319
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,002
|
Common.cpp
|
ethereum_solidity/test/libsolidity/util/Common.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/libsolidity/util/Common.h>
#include <regex>
using namespace solidity;
using namespace solidity::frontend;
std::string test::withPreamble(std::string const& _sourceCode, bool _addAbicoderV1Pragma)
{
static std::string const versionPragma = "pragma solidity >=0.0;\n";
static std::string const licenseComment = "// SPDX-License-Identifier: GPL-3.0\n";
static std::string const abicoderPragma = "pragma abicoder v1;\n";
// NOTE: These checks are intentionally loose to match weird cases.
// We can manually adjust a test case where this causes problem.
bool licenseMissing = _sourceCode.find("SPDX-License-Identifier:") == std::string::npos;
bool abicoderMissing =
_sourceCode.find("pragma experimental ABIEncoderV2;") == std::string::npos &&
_sourceCode.find("pragma abicoder") == std::string::npos;
return
versionPragma +
(licenseMissing ? licenseComment : "") +
(abicoderMissing && _addAbicoderV1Pragma ? abicoderPragma : "") +
_sourceCode;
}
StringMap test::withPreamble(StringMap _sources, bool _addAbicoderV1Pragma)
{
for (auto&& [sourceName, source]: _sources)
source = withPreamble(source, _addAbicoderV1Pragma);
return _sources;
}
std::string test::stripPreReleaseWarning(std::string const& _stderrContent)
{
static std::regex const preReleaseWarningRegex{
R"(Warning( \(3805\))?: This is a pre-release compiler version, please do not use it in production\.\n)"
R"((\n)?)"
};
static std::regex const noOutputRegex{
R"(Compiler run successful, no output requested\.\n)"
};
std::string output = std::regex_replace(_stderrContent, preReleaseWarningRegex, "");
return std::regex_replace(std::move(output), noOutputRegex, "");
}
| 2,376
|
C++
|
.cpp
| 53
| 42.698113
| 106
| 0.762338
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,005
|
TestFunctionCall.cpp
|
ethereum_solidity/test/libsolidity/util/TestFunctionCall.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <test/libsolidity/util/TestFunctionCall.h>
#include <test/libsolidity/util/BytesUtils.h>
#include <test/libsolidity/util/ContractABIUtils.h>
#include <libsolutil/AnsiColorized.h>
#include <boost/algorithm/string.hpp>
#include <fmt/format.h>
#include <range/v3/view/map.hpp>
#include <range/v3/view/set_algorithm.hpp>
#include <optional>
#include <stdexcept>
#include <string>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::frontend::test;
using Token = soltest::Token;
std::string TestFunctionCall::format(
ErrorReporter& _errorReporter,
std::string const& _linePrefix,
RenderMode _renderMode,
bool const _highlight,
bool const _interactivePrint
) const
{
std::stringstream stream;
bool highlight = !matchesExpectation() && _highlight;
auto formatOutput = [&](bool const _singleLine)
{
std::string ws = " ";
std::string arrow = formatToken(Token::Arrow);
std::string colon = formatToken(Token::Colon);
std::string comma = formatToken(Token::Comma);
std::string comment = formatToken(Token::Comment);
std::string ether = formatToken(Token::Ether);
std::string wei = formatToken(Token::Wei);
std::string newline = formatToken(Token::Newline);
std::string failure = formatToken(Token::Failure);
if (m_call.kind == FunctionCall::Kind::Library)
{
stream << _linePrefix << newline << ws << "library:" << ws;
if (!m_call.libraryFile.empty())
stream << "\"" << m_call.libraryFile << "\":";
stream << m_call.signature;
return;
}
/// Formats the function signature. This is the same independent from the display-mode.
stream << _linePrefix << newline << ws << m_call.signature;
if (m_call.value.value > u256(0))
{
switch (m_call.value.unit)
{
case FunctionValueUnit::Ether:
stream << comma << ws << (m_call.value.value / exp256(10, 18)) << ws << ether;
break;
case FunctionValueUnit::Wei:
stream << comma << ws << m_call.value.value << ws << wei;
break;
default:
soltestAssert(false, "");
}
}
if (!m_call.arguments.rawBytes().empty())
{
std::string output = formatRawParameters(m_call.arguments.parameters, _linePrefix);
stream << colon;
if (!m_call.arguments.parameters.at(0).format.newline)
stream << ws;
stream << output;
}
/// Formats comments on the function parameters and the arrow taking
/// the display-mode into account.
if (_singleLine)
{
if (!m_call.arguments.comment.empty())
stream << ws << comment << m_call.arguments.comment << comment;
if (m_call.omitsArrow)
{
if (_renderMode == RenderMode::ActualValuesExpectedGas && (m_failure || !matchesExpectation()))
stream << ws << arrow;
}
else
stream << ws << arrow;
}
else
{
stream << std::endl << _linePrefix << newline << ws;
if (!m_call.arguments.comment.empty())
{
stream << comment << m_call.arguments.comment << comment;
stream << std::endl << _linePrefix << newline << ws;
}
stream << arrow;
}
/// Format either the expected output or the actual result output
std::string result;
if (_renderMode != RenderMode::ActualValuesExpectedGas)
{
bool const isFailure = m_call.expectations.failure;
result = isFailure ?
formatFailure(_errorReporter, m_call, m_rawBytes, /* _renderResult */ false, highlight) :
formatRawParameters(m_call.expectations.result);
if (!result.empty())
AnsiColorized(stream, highlight, {util::formatting::RED_BACKGROUND}) << ws << result;
}
else
{
if (m_calledNonExistingFunction)
_errorReporter.warning("The function \"" + m_call.signature + "\" is not known to the compiler.");
bytes output = m_rawBytes;
bool const isFailure = m_failure;
result = isFailure ?
formatFailure(_errorReporter, m_call, output, _renderMode == RenderMode::ActualValuesExpectedGas, highlight) :
matchesExpectation() ?
formatRawParameters(m_call.expectations.result) :
formatBytesParameters(
_errorReporter,
output,
m_call.signature,
m_call.expectations.result,
highlight
);
if (!matchesExpectation())
{
std::optional<ParameterList> abiParams;
if (isFailure)
{
if (!output.empty())
abiParams = ContractABIUtils::failureParameters(output);
}
else
abiParams = ContractABIUtils::parametersFromJsonOutputs(
_errorReporter,
m_contractABI,
m_call.signature
);
std::string bytesOutput = abiParams ?
BytesUtils::formatRawBytes(output, abiParams.value(), _linePrefix) :
BytesUtils::formatRawBytes(
output,
ContractABIUtils::defaultParameters((output.size() + 31) / 32),
_linePrefix
);
_errorReporter.warning(
"The call to \"" + m_call.signature + "\" returned \n" +
bytesOutput
);
}
if (isFailure)
AnsiColorized(stream, highlight, {util::formatting::RED_BACKGROUND}) << ws << result;
else
if (!result.empty())
stream << ws << result;
}
/// Format comments on expectations taking the display-mode into account.
if (_singleLine)
{
if (!m_call.expectations.comment.empty())
stream << ws << comment << m_call.expectations.comment << comment;
}
else
{
if (!m_call.expectations.comment.empty())
{
stream << std::endl << _linePrefix << newline << ws;
stream << comment << m_call.expectations.comment << comment;
}
}
std::vector<std::string> sideEffects;
if (_renderMode == RenderMode::ExpectedValuesExpectedGas || _renderMode == RenderMode::ExpectedValuesActualGas)
sideEffects = m_call.expectedSideEffects;
else
sideEffects = m_call.actualSideEffects;
if (!sideEffects.empty())
{
stream << std::endl;
size_t i = 0;
for (; i < sideEffects.size() - 1; ++i)
stream << _linePrefix << "// ~ " << sideEffects[i] << std::endl;
stream << _linePrefix << "// ~ " << sideEffects[i];
}
stream << formatGasExpectations(_linePrefix, _renderMode == RenderMode::ExpectedValuesActualGas, _interactivePrint);
};
formatOutput(m_call.displayMode == FunctionCall::DisplayMode::SingleLine);
return stream.str();
}
std::string TestFunctionCall::formatBytesParameters(
ErrorReporter& _errorReporter,
bytes const& _bytes,
std::string const& _signature,
solidity::frontend::test::ParameterList const& _parameters,
bool _highlight,
bool _failure
) const
{
using ParameterList = solidity::frontend::test::ParameterList;
std::stringstream os;
if (_bytes.empty())
return {};
if (_failure)
{
os << BytesUtils::formatBytesRange(
_bytes,
ContractABIUtils::failureParameters(_bytes),
_highlight
);
return os.str();
}
else
{
std::optional<ParameterList> abiParams = ContractABIUtils::parametersFromJsonOutputs(
_errorReporter,
m_contractABI,
_signature
);
if (abiParams)
{
std::optional<ParameterList> preferredParams = ContractABIUtils::preferredParameters(
_errorReporter,
_parameters,
abiParams.value(),
_bytes
);
if (preferredParams)
{
ContractABIUtils::overwriteParameters(_errorReporter, preferredParams.value(), abiParams.value());
os << BytesUtils::formatBytesRange(_bytes, preferredParams.value(), _highlight);
}
}
else
{
ParameterList defaultParameters = ContractABIUtils::defaultParameters((_bytes.size() + 31) / 32);
ContractABIUtils::overwriteParameters(_errorReporter, defaultParameters, _parameters);
os << BytesUtils::formatBytesRange(_bytes, defaultParameters, _highlight);
}
return os.str();
}
}
std::string TestFunctionCall::formatFailure(
ErrorReporter& _errorReporter,
solidity::frontend::test::FunctionCall const& _call,
bytes const& _output,
bool _renderResult,
bool _highlight
) const
{
std::stringstream os;
os << formatToken(Token::Failure);
if (!_output.empty())
os << ", ";
if (_renderResult)
os << formatBytesParameters(
_errorReporter,
_output,
_call.signature,
_call.expectations.result,
_highlight,
true
);
else
os << formatRawParameters(_call.expectations.result);
return os.str();
}
std::string TestFunctionCall::formatRawParameters(
solidity::frontend::test::ParameterList const& _params,
std::string const& _linePrefix
) const
{
std::stringstream os;
for (auto const& param: _params)
if (!param.rawString.empty())
{
if (param.format.newline)
os << std::endl << _linePrefix << "// ";
for (auto const c: param.rawString)
// NOTE: Even though we have a toHex() overload specifically for uint8_t, the compiler
// chooses the one for bytes if the second argument is omitted.
os << (c >= ' ' ? std::string(1, c) : "\\x" + util::toHex(static_cast<uint8_t>(c), HexCase::Lower));
if (¶m != &_params.back())
os << ", ";
}
return os.str();
}
namespace
{
std::string formatGasDiff(std::optional<u256> const& _gasUsed, std::optional<u256> const& _reference)
{
if (!_reference.has_value() || !_gasUsed.has_value() || _gasUsed == _reference)
return "";
solUnimplementedAssert(*_gasUsed < u256(1) << 255);
solUnimplementedAssert(*_reference < u256(1) << 255);
s256 difference = static_cast<s256>(*_gasUsed) - static_cast<s256>(*_reference);
if (*_reference == 0)
return fmt::format("{}", difference.str());
int percent = static_cast<int>(
100.0 * (static_cast<double>(difference) / static_cast<double>(*_reference))
);
return fmt::format("{} ({:+}%)", difference.str(), percent);
}
// TODO: Convert this into a generic helper for getting optional form a map
std::optional<u256> gasOrNullopt(std::map<std::string, u256> const& _map, std::string const& _key)
{
auto it = _map.find(_key);
if (it == _map.end())
return std::nullopt;
return it->second;
}
}
std::string TestFunctionCall::formatGasExpectations(
std::string const& _linePrefix,
bool _useActualCost,
bool _showDifference
) const
{
using ranges::views::keys;
using ranges::views::set_symmetric_difference;
soltestAssert(set_symmetric_difference(m_codeDepositGasCosts | keys, m_gasCostsExcludingCode | keys).empty());
soltestAssert(set_symmetric_difference(m_call.expectations.gasUsedForCodeDeposit | keys, m_call.expectations.gasUsedExcludingCode | keys).empty());
std::stringstream os;
for (auto const& [runType, gasUsedExcludingCode]: (_useActualCost ? m_gasCostsExcludingCode : m_call.expectations.gasUsedExcludingCode))
{
soltestAssert(runType != "");
u256 gasUsedForCodeDeposit = (_useActualCost ? m_codeDepositGasCosts : m_call.expectations.gasUsedForCodeDeposit).at(runType);
os << std::endl << _linePrefix << "// gas " << runType << ": " << gasUsedExcludingCode.str();
std::string gasDiff = formatGasDiff(
gasOrNullopt(m_gasCostsExcludingCode, runType),
gasOrNullopt(m_call.expectations.gasUsedExcludingCode, runType)
);
if (_showDifference && !gasDiff.empty() && _useActualCost)
os << " [" << gasDiff << "]";
if (gasUsedForCodeDeposit != 0)
{
os << std::endl << _linePrefix << "// gas " << runType << " code: " << gasUsedForCodeDeposit.str();
std::string codeGasDiff = formatGasDiff(
gasOrNullopt(m_codeDepositGasCosts, runType),
gasOrNullopt(m_call.expectations.gasUsedForCodeDeposit, runType)
);
if (_showDifference && !codeGasDiff.empty() && _useActualCost)
os << " [" << codeGasDiff << "]";
}
}
return os.str();
}
void TestFunctionCall::reset()
{
m_rawBytes = bytes{};
m_failure = true;
m_contractABI = Json();
m_calledNonExistingFunction = false;
}
bool TestFunctionCall::matchesExpectation() const
{
return m_failure == m_call.expectations.failure && m_rawBytes == m_call.expectations.rawBytes();
}
| 12,237
|
C++
|
.cpp
| 365
| 30.175342
| 148
| 0.705519
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,006
|
BytesUtilsTests.cpp
|
ethereum_solidity/test/libsolidity/util/BytesUtilsTests.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <boost/test/unit_test.hpp>
#include <test/libsolidity/util/BytesUtils.h>
#include <libsolutil/CommonData.h>
using namespace solidity::util;
using namespace solidity::test;
namespace solidity::frontend::test
{
BOOST_AUTO_TEST_SUITE(BytesUtilsTest)
BOOST_AUTO_TEST_CASE(format_fixed)
{
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{0}), true, 2),
"0.00"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{1}), true, 2),
"0.01"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{123}), true, 2),
"1.23"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-1}), true, 2),
"-0.01"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-12}), true, 2),
"-0.12"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-123}), true, 2),
"-1.23"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-1234}), true, 2),
"-12.34"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-12345}), true, 2),
"-123.45"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-123456}), true, 2),
"-1234.56"
);
BOOST_CHECK_EQUAL(
BytesUtils::formatFixedPoint(toBigEndian(u256{-1234567}), true, 2),
"-12345.67"
);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 2,028
|
C++
|
.cpp
| 67
| 28
| 69
| 0.751926
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,007
|
ContractABIUtils.cpp
|
ethereum_solidity/test/libsolidity/util/ContractABIUtils.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/libsolidity/util/ContractABIUtils.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolidity/ast/Types.h>
#include <libsolidity/ast/TypeProvider.h>
#include <libsolutil/FunctionSelector.h>
#include <libsolutil/CommonData.h>
#include <liblangutil/Common.h>
#include <boost/algorithm/string.hpp>
#include <boost/assign/list_of.hpp>
#include <range/v3/view/zip.hpp>
#include <fstream>
#include <memory>
#include <numeric>
#include <regex>
#include <stdexcept>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend::test;
namespace
{
using ParameterList = solidity::frontend::test::ParameterList;
size_t arraySize(std::string const& _arrayType)
{
auto leftBrack = _arrayType.find("[");
auto rightBrack = _arrayType.rfind("]");
soltestAssert(
leftBrack != std::string::npos &&
rightBrack != std::string::npos &&
rightBrack == _arrayType.size() - 1 &&
leftBrack < rightBrack,
""
);
std::string size = _arrayType.substr(leftBrack + 1, rightBrack - leftBrack - 1);
return static_cast<size_t>(stoi(size));
}
bool isBool(std::string const& _type)
{
return _type == "bool";
}
bool isUint(std::string const& _type)
{
return regex_match(_type, std::regex{"uint\\d*"});
}
bool isInt(std::string const& _type)
{
return regex_match(_type, std::regex{"int\\d*"});
}
bool isFixedBytes(std::string const& _type)
{
return regex_match(_type, std::regex{"bytes\\d+"});
}
bool isBytes(std::string const& _type)
{
return regex_match(_type, std::regex{"\\bbytes\\b"});
}
bool isString(std::string const& _type)
{
return _type == "string";
}
bool isFixedBoolArray(std::string const& _type)
{
return regex_match(_type, std::regex{"bool\\[\\d+\\]"});
}
bool isFixedUintArray(std::string const& _type)
{
return regex_match(_type, std::regex{"uint\\d*\\[\\d+\\]"});
}
bool isFixedIntArray(std::string const& _type)
{
return regex_match(_type, std::regex{"int\\d*\\[\\d+\\]"});
}
bool isFixedStringArray(std::string const& _type)
{
return regex_match(_type, std::regex{"string\\[\\d+\\]"});
}
bool isTuple(std::string const& _type)
{
return _type == "tuple";
}
bool isFixedTupleArray(std::string const& _type)
{
return regex_match(_type, std::regex{"tuple\\[\\d+\\]"});
}
std::optional<ABIType> isFixedPoint(std::string const& type)
{
std::optional<ABIType> fixedPointType;
std::smatch matches;
if (regex_match(type, matches, std::regex{"(u?)fixed(\\d+)x(\\d+)"}))
{
ABIType abiType(ABIType::SignedFixedPoint);
if (matches[1].str() == "u")
abiType.type = ABIType::UnsignedFixedPoint;
abiType.fractionalDigits = static_cast<unsigned>(std::stoi(matches[3].str()));
fixedPointType = abiType;
}
return fixedPointType;
}
std::string functionSignatureFromABI(Json const& _functionABI)
{
soltestAssert(_functionABI.contains("name"));
auto inputs = _functionABI["inputs"];
std::string signature = {_functionABI["name"].get<std::string>() + "("};
size_t parameterCount = 0;
for (auto const& input: inputs)
{
parameterCount++;
signature += input["type"].get<std::string>();
if (parameterCount < inputs.size())
signature += ",";
}
return signature + ")";
}
}
std::optional<solidity::frontend::test::ParameterList> ContractABIUtils::parametersFromJsonOutputs(
ErrorReporter& _errorReporter,
Json const& _contractABI,
std::string const& _functionSignature
)
{
if (_contractABI.empty())
return std::nullopt;
for (auto const& function: _contractABI)
// ABI may contain functions without names (constructor, fallback, receive). Since name is
// necessary to calculate the signature, these cannot possibly match and can be safely ignored.
if (function.contains("name") && _functionSignature == functionSignatureFromABI(function))
{
ParameterList inplaceTypeParams;
ParameterList dynamicTypeParams;
ParameterList finalParams;
for (auto const& output: function["outputs"])
{
std::string type = output["type"].get<std::string>();
ABITypes inplaceTypes;
ABITypes dynamicTypes;
if (appendTypesFromName(output, inplaceTypes, dynamicTypes))
{
for (auto const& type: inplaceTypes)
inplaceTypeParams.push_back(Parameter{bytes(), "", type, FormatInfo{}});
for (auto const& type: dynamicTypes)
dynamicTypeParams.push_back(Parameter{bytes(), "", type, FormatInfo{}});
}
else
{
_errorReporter.warning(
"Could not convert \"" + type +
"\" to internal ABI type representation. Falling back to default encoding."
);
return std::nullopt;
}
finalParams += inplaceTypeParams;
inplaceTypeParams.clear();
}
return std::optional<ParameterList>(finalParams + dynamicTypeParams);
}
return std::nullopt;
}
bool ContractABIUtils::appendTypesFromName(
Json const& _functionOutput,
ABITypes& _inplaceTypes,
ABITypes& _dynamicTypes,
bool _isCompoundType
)
{
std::string type = _functionOutput["type"].get<std::string>();
if (isBool(type))
_inplaceTypes.push_back(ABIType{ABIType::Boolean});
else if (isUint(type))
_inplaceTypes.push_back(ABIType{ABIType::UnsignedDec});
else if (isInt(type))
_inplaceTypes.push_back(ABIType{ABIType::SignedDec});
else if (isFixedBytes(type))
_inplaceTypes.push_back(ABIType{ABIType::Hex});
else if (isString(type))
{
_inplaceTypes.push_back(ABIType{ABIType::Hex});
if (_isCompoundType)
_dynamicTypes.push_back(ABIType{ABIType::Hex});
_dynamicTypes.push_back(ABIType{ABIType::UnsignedDec});
_dynamicTypes.push_back(ABIType{ABIType::String, ABIType::AlignLeft});
}
else if (isTuple(type))
{
ABITypes inplaceTypes;
ABITypes dynamicTypes;
for (auto const& component: _functionOutput["components"])
appendTypesFromName(component, inplaceTypes, dynamicTypes, true);
_dynamicTypes += inplaceTypes + dynamicTypes;
}
else if (isFixedBoolArray(type))
_inplaceTypes += std::vector<ABIType>(arraySize(type), ABIType{ABIType::Boolean});
else if (isFixedUintArray(type))
_inplaceTypes += std::vector<ABIType>(arraySize(type), ABIType{ABIType::UnsignedDec});
else if (isFixedIntArray(type))
_inplaceTypes += std::vector<ABIType>(arraySize(type), ABIType{ABIType::SignedDec});
else if (isFixedStringArray(type))
{
_inplaceTypes.push_back(ABIType{ABIType::Hex});
_dynamicTypes += std::vector<ABIType>(arraySize(type), ABIType{ABIType::Hex});
for (size_t i = 0; i < arraySize(type); i++)
{
_dynamicTypes.push_back(ABIType{ABIType::UnsignedDec});
_dynamicTypes.push_back(ABIType{ABIType::String, ABIType::AlignLeft});
}
}
else if (std::optional<ABIType> fixedPointType = isFixedPoint(type))
_inplaceTypes.push_back(*fixedPointType);
else if (isBytes(type))
return false;
else if (isFixedTupleArray(type))
return false;
else
return false;
return true;
}
void ContractABIUtils::overwriteParameters(
ErrorReporter& _errorReporter,
solidity::frontend::test::ParameterList& _targetParameters,
solidity::frontend::test::ParameterList const& _sourceParameters
)
{
using namespace std::placeholders;
for (auto&& [source, target]: ranges::views::zip(_sourceParameters, _targetParameters))
if (
source.abiType.size != target.abiType.size ||
source.abiType.type != target.abiType.type ||
source.abiType.fractionalDigits != target.abiType.fractionalDigits
)
{
_errorReporter.warning("Type or size of parameter(s) does not match.");
target = source;
}
}
solidity::frontend::test::ParameterList ContractABIUtils::preferredParameters(
ErrorReporter& _errorReporter,
solidity::frontend::test::ParameterList const& _targetParameters,
solidity::frontend::test::ParameterList const& _sourceParameters,
bytes const& _bytes
)
{
if (_targetParameters.size() != _sourceParameters.size())
{
_errorReporter.warning(
"Encoding does not match byte range. The call returned " +
std::to_string(_bytes.size()) + " bytes, but " +
std::to_string(encodingSize(_targetParameters)) + " bytes were expected."
);
return _sourceParameters;
}
else
return _targetParameters;
}
solidity::frontend::test::ParameterList ContractABIUtils::defaultParameters(size_t count)
{
ParameterList parameters;
fill_n(
back_inserter(parameters),
count,
Parameter{bytes(), "", ABIType{ABIType::UnsignedDec}, FormatInfo{}}
);
return parameters;
}
solidity::frontend::test::ParameterList ContractABIUtils::failureParameters(bytes const& _bytes)
{
if (_bytes.empty())
return {};
else if (_bytes.size() < 4)
return {Parameter{bytes(), "", ABIType{ABIType::HexString, ABIType::AlignNone, _bytes.size()}, FormatInfo{}}};
else
{
ParameterList parameters;
parameters.push_back(Parameter{bytes(), "", ABIType{ABIType::HexString, ABIType::AlignNone, 4}, FormatInfo{}});
uint64_t selector = fromBigEndian<uint64_t>(bytes{_bytes.begin(), _bytes.begin() + 4});
if (selector == selectorFromSignatureU32("Panic(uint256)"))
parameters.push_back(Parameter{bytes(), "", ABIType{ABIType::Hex}, FormatInfo{}});
else if (selector == selectorFromSignatureU32("Error(string)"))
{
parameters.push_back(Parameter{bytes(), "", ABIType{ABIType::Hex}, FormatInfo{}});
parameters.push_back(Parameter{bytes(), "", ABIType{ABIType::UnsignedDec}, FormatInfo{}});
/// If _bytes contains at least a 1 byte message (function selector + tail pointer + message length + message)
/// append an additional string parameter to represent that message.
if (_bytes.size() > 68)
parameters.push_back(Parameter{bytes(), "", ABIType{ABIType::String}, FormatInfo{}});
}
else
for (size_t i = 4; i < _bytes.size(); i += 32)
parameters.push_back(Parameter{bytes(), "", ABIType{ABIType::HexString, ABIType::AlignNone, 32}, FormatInfo{}});
return parameters;
}
}
size_t ContractABIUtils::encodingSize(
solidity::frontend::test::ParameterList const& _parameters
)
{
auto sizeFold = [](size_t const _a, Parameter const& _b) { return _a + _b.abiType.size; };
return accumulate(_parameters.begin(), _parameters.end(), size_t{0}, sizeFold);
}
| 10,721
|
C++
|
.cpp
| 311
| 31.932476
| 116
| 0.733771
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,009
|
TestFileParserTests.cpp
|
ethereum_solidity/test/libsolidity/util/TestFileParserTests.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Unit tests for Solidity's test expectation parser.
*/
#include <functional>
#include <string>
#include <tuple>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <liblangutil/Exceptions.h>
#include <test/ExecutionFramework.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/libsolidity/util/TestFileParser.h>
using namespace solidity::util;
using namespace solidity::test;
namespace solidity::frontend::test
{
using fmt = ExecutionFramework;
using Mode = FunctionCall::DisplayMode;
namespace
{
std::vector<FunctionCall> parse(std::string const& _source, std::map<std::string, Builtin> const& _builtins = {})
{
std::istringstream stream{_source, std::ios_base::out};
return TestFileParser{stream, _builtins}.parseFunctionCalls(0);
}
void testFunctionCall(
FunctionCall const& _call,
FunctionCall::DisplayMode _mode,
std::string _signature = "",
bool _failure = true,
bytes _arguments = bytes{},
bytes _expectations = bytes{},
FunctionValue _value = { 0 },
std::string _argumentComment = "",
std::string _expectationComment = "",
std::vector<std::string> _rawArguments = std::vector<std::string>{},
bool _isConstructor = false,
bool _isLibrary = false
)
{
BOOST_REQUIRE_EQUAL(_call.expectations.failure, _failure);
BOOST_REQUIRE_EQUAL(_call.signature, _signature);
ABI_CHECK(_call.arguments.rawBytes(), _arguments);
ABI_CHECK(_call.expectations.rawBytes(), _expectations);
BOOST_REQUIRE_EQUAL(_call.displayMode, _mode);
BOOST_REQUIRE_EQUAL(_call.value.value, _value.value);
BOOST_REQUIRE_EQUAL(static_cast<size_t>(_call.value.unit), static_cast<size_t>(_value.unit));
BOOST_REQUIRE_EQUAL(_call.arguments.comment, _argumentComment);
BOOST_REQUIRE_EQUAL(_call.expectations.comment, _expectationComment);
if (!_rawArguments.empty())
{
BOOST_REQUIRE_EQUAL(_call.arguments.parameters.size(), _rawArguments.size());
size_t index = 0;
for (Parameter const& param: _call.arguments.parameters)
{
BOOST_REQUIRE_EQUAL(param.rawString, _rawArguments[index]);
++index;
}
}
BOOST_REQUIRE_EQUAL(_call.kind == FunctionCall::Kind::Constructor, _isConstructor);
BOOST_REQUIRE_EQUAL(_call.kind == FunctionCall::Kind::Library, _isLibrary);
}
}
BOOST_AUTO_TEST_SUITE(TestFileParserTest)
BOOST_AUTO_TEST_CASE(smoke_test)
{
char const* source = R"()";
BOOST_REQUIRE_EQUAL(parse(source).size(), 0);
}
BOOST_AUTO_TEST_CASE(call_success)
{
char const* source = R"(
// success() ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::SingleLine, "success()", false);
}
BOOST_AUTO_TEST_CASE(non_existent_call_revert_single_line)
{
char const* source = R"(
// i_am_not_there() -> FAILURE
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::SingleLine, "i_am_not_there()", true);
}
BOOST_AUTO_TEST_CASE(call_arguments_success)
{
char const* source = R"(
// f(uint256): 1
// ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::MultiLine, "f(uint256)", false, fmt::encodeArgs(u256{1}));
}
BOOST_AUTO_TEST_CASE(call_arguments_comments_success)
{
char const* source = R"(
// f(uint256, uint256): 1, 1
// # Comment on the parameters. #
// ->
// # This call should not return a value, but still succeed. #
// f()
// # Comment on no parameters. #
// -> 1
// # This comment should be parsed. #
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"f(uint256,uint256)",
false,
fmt::encodeArgs(1, 1),
fmt::encodeArgs(),
{0},
" Comment on the parameters. ",
" This call should not return a value, but still succeed. "
);
testFunctionCall(
calls.at(1),
Mode::MultiLine,
"f()",
false,
fmt::encodeArgs(),
fmt::encodeArgs(1),
{0},
" Comment on no parameters. ",
" This comment should be parsed. "
);
}
BOOST_AUTO_TEST_CASE(simple_single_line_call_comment_success)
{
char const* source = R"(
// f(uint256): 1 -> # f(uint256) does not return a value. #
// f(uint256): 1 -> 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(uint256)",
false,
fmt::encodeArgs(1),
fmt::encodeArgs(),
{0},
"",
" f(uint256) does not return a value. "
);
testFunctionCall(calls.at(1), Mode::SingleLine, "f(uint256)", false, fmt::encode(1), fmt::encode(1));
}
BOOST_AUTO_TEST_CASE(multiple_single_line)
{
char const* source = R"(
// f(uint256): 1 -> 1
// g(uint256): 1 ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(calls.at(0), Mode::SingleLine, "f(uint256)", false, fmt::encodeArgs(1), fmt::encodeArgs(1));
testFunctionCall(calls.at(1), Mode::SingleLine, "g(uint256)", false, fmt::encodeArgs(1));
}
BOOST_AUTO_TEST_CASE(multiple_single_line_swapped)
{
char const* source = R"(
// f(uint256): 1 ->
// g(uint256): 1 -> 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(calls.at(0), Mode::SingleLine, "f(uint256)", false, fmt::encodeArgs(1));
testFunctionCall(calls.at(1), Mode::SingleLine, "g(uint256)", false, fmt::encodeArgs(1), fmt::encodeArgs(1));
}
BOOST_AUTO_TEST_CASE(non_existent_call_revert)
{
char const* source = R"(
// i_am_not_there()
// -> FAILURE
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::MultiLine, "i_am_not_there()", true);
}
BOOST_AUTO_TEST_CASE(call_revert_message)
{
char const* source = R"(
// f() -> FAILURE, hex"08c379a0", 0x20, 6, "Revert"
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f()",
true,
fmt::encodeArgs(),
fromHex("08c379a0") + fmt::encodeDyn(std::string{"Revert"})
);
}
BOOST_AUTO_TEST_CASE(call_expectations_empty_single_line)
{
char const* source = R"(
// _exp_() ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::SingleLine, "_exp_()", false);
}
BOOST_AUTO_TEST_CASE(call_expectations_empty_multiline)
{
char const* source = R"(
// _exp_()
// ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::MultiLine, "_exp_()", false);
}
BOOST_AUTO_TEST_CASE(call_comments)
{
char const* source = R"(
// f() # Parameter comment # -> 1 # Expectation comment #
// f() # Parameter comment #
// -> 1 # Expectation comment #
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f()",
false,
fmt::encodeArgs(),
fmt::encodeArgs(1),
{0},
" Parameter comment ",
" Expectation comment "
);
testFunctionCall(
calls.at(1),
Mode::MultiLine,
"f()",
false,
fmt::encodeArgs(),
fmt::encodeArgs(1),
{0},
" Parameter comment ",
" Expectation comment "
);
}
BOOST_AUTO_TEST_CASE(call_arguments)
{
char const* source = R"(
// f(uint256), 314 wei: 5 # optional wei value #
// -> 4
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"f(uint256)",
false,
fmt::encodeArgs(5),
fmt::encodeArgs(4),
{314},
" optional wei value "
);
}
BOOST_AUTO_TEST_CASE(call_arguments_ether)
{
char const* source = R"(
// f(uint256), 1 ether: 5 # optional ether value #
// -> 4
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"f(uint256)",
false,
fmt::encodeArgs(5),
fmt::encodeArgs(4),
{exp256(u256(10), u256(18)) , FunctionValueUnit::Ether},
" optional ether value "
);
}
BOOST_AUTO_TEST_CASE(call_arguments_bool)
{
char const* source = R"(
// f(bool): true -> false
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(bool)",
false,
fmt::encodeArgs(true),
fmt::encodeArgs(false)
);
}
BOOST_AUTO_TEST_CASE(scanner_hex_values)
{
char const* source = R"(
// f(uint256): "\x20\x00\xFf" ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::SingleLine, "f(uint256)", false, fmt::encodeArgs(std::string("\x20\x00\xff", 3)));
}
BOOST_AUTO_TEST_CASE(scanner_hex_values_invalid1)
{
char const* source = R"(
// f(uint256): "\x" ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(scanner_hex_values_invalid2)
{
char const* source = R"(
// f(uint256): "\x1" ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(calls.at(0), Mode::SingleLine, "f(uint256)", false, fmt::encodeArgs(std::string("\x1", 1)));
}
BOOST_AUTO_TEST_CASE(scanner_hex_values_invalid3)
{
char const* source = R"(
// f(uint256): "\xZ" ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(scanner_hex_values_invalid4)
{
char const* source = R"(
// f(uint256): "\xZZ" ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_hex_string)
{
char const* source = R"(
// f(bytes): hex"4200ef" -> hex"ab0023"
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(bytes)",
false,
fromHex("4200ef"),
fromHex("ab0023")
);
}
BOOST_AUTO_TEST_CASE(call_arguments_hex_string_lowercase)
{
char const* source = R"(
// f(bytes): hex"4200ef" -> hex"23ef00"
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(bytes)",
false,
fromHex("4200EF"),
fromHex("23EF00")
);
}
BOOST_AUTO_TEST_CASE(call_arguments_string)
{
char const* source = R"(
// f(string): 0x20, 3, "any" ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(string)",
false,
fmt::encodeDyn(std::string{"any"})
);
}
BOOST_AUTO_TEST_CASE(call_hex_number)
{
char const* source = R"(
// f(bytes32, bytes32): 0x616, 0x1042 -> 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(bytes32,bytes32)",
false,
fmt::encodeArgs(
fromHex("0x616"),
fromHex("0x1042")
),
fmt::encodeArgs(1)
);
}
BOOST_AUTO_TEST_CASE(call_return_string)
{
char const* source = R"(
// f() -> 0x20, 3, "any"
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f()",
false,
fmt::encodeArgs(),
fmt::encodeDyn(std::string{"any"})
);
}
BOOST_AUTO_TEST_CASE(call_arguments_tuple)
{
char const* source = R"(
// f((uint256, bytes32), uint256) ->
// f((uint8), uint8) ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(calls.at(0), Mode::SingleLine, "f((uint256,bytes32),uint256)", false);
testFunctionCall(calls.at(1), Mode::SingleLine, "f((uint8),uint8)", false);
}
BOOST_AUTO_TEST_CASE(call_arguments_left_aligned)
{
char const* source = R"(
// f(bytes32, bytes32): 0x6161, 0x420000EF -> 1
// g(bytes32, bytes32): 0x0616, 0x0042EF00 -> 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(bytes32,bytes32)",
false,
fmt::encodeArgs(
fromHex("0x6161"),
fromHex("0x420000EF")
),
fmt::encodeArgs(1)
);
testFunctionCall(
calls.at(1),
Mode::SingleLine,
"g(bytes32,bytes32)",
false,
fmt::encodeArgs(
fromHex("0x0616"),
fromHex("0x0042EF00")
),
fmt::encodeArgs(1)
);
}
BOOST_AUTO_TEST_CASE(call_arguments_tuple_of_tuples)
{
char const* source = R"(
// f(((uint256, bytes32), bytes32), uint256)
// # f(S memory s, uint256 b) #
// ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"f(((uint256,bytes32),bytes32),uint256)",
false,
fmt::encodeArgs(),
fmt::encodeArgs(),
{0},
" f(S memory s, uint256 b) "
);
}
BOOST_AUTO_TEST_CASE(call_arguments_recursive_tuples)
{
char const* source = R"(
// f(((((bytes, bytes, bytes), bytes), bytes), bytes), bytes) ->
// f(((((bytes, bytes, (bytes)), bytes), bytes), (bytes, bytes)), (bytes, bytes)) ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f(((((bytes,bytes,bytes),bytes),bytes),bytes),bytes)",
false
);
testFunctionCall(
calls.at(1),
Mode::SingleLine,
"f(((((bytes,bytes,(bytes)),bytes),bytes),(bytes,bytes)),(bytes,bytes))",
false
);
}
BOOST_AUTO_TEST_CASE(call_arguments_mismatch)
{
char const* source = R"(
// f(uint256):
// 1, 2
// # This only throws at runtime #
// -> 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"f(uint256)",
false,
fmt::encodeArgs(1, 2),
fmt::encodeArgs(1),
{0},
" This only throws at runtime "
);
}
BOOST_AUTO_TEST_CASE(call_multiple_arguments)
{
char const* source = R"(
// test(uint256, uint256):
// 1,
// 2
// -> 1,
// 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"test(uint256,uint256)",
false,
fmt::encodeArgs(1, 2),
fmt::encodeArgs(1, 1)
);
}
BOOST_AUTO_TEST_CASE(call_multiple_arguments_mixed_format)
{
char const* source = R"(
// test(uint256, uint256), 314 wei:
// 1, -2
// -> -1, 2
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::MultiLine,
"test(uint256,uint256)",
false,
fmt::encodeArgs(1, -2),
fmt::encodeArgs(-1, 2),
{314}
);
}
BOOST_AUTO_TEST_CASE(call_signature_array)
{
char const* source = R"(
// f(uint256[]) ->
// f(uint256[3]) ->
// f(uint256[3][][], uint8[9]) ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 3);
testFunctionCall(calls.at(0), Mode::SingleLine, "f(uint256[])", false);
testFunctionCall(calls.at(1), Mode::SingleLine, "f(uint256[3])", false);
testFunctionCall(calls.at(2), Mode::SingleLine, "f(uint256[3][][],uint8[9])", false);
}
BOOST_AUTO_TEST_CASE(call_signature_struct_array)
{
char const* source = R"(
// f((uint256)[]) ->
// f((uint256)[3]) ->
// f((uint256, uint8)[3]) ->
// f((uint256)[3][][], (uint8, bool)[9]) ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 4);
testFunctionCall(calls.at(0), Mode::SingleLine, "f((uint256)[])", false);
testFunctionCall(calls.at(1), Mode::SingleLine, "f((uint256)[3])", false);
testFunctionCall(calls.at(2), Mode::SingleLine, "f((uint256,uint8)[3])", false);
testFunctionCall(calls.at(3), Mode::SingleLine, "f((uint256)[3][][],(uint8,bool)[9])", false);
}
BOOST_AUTO_TEST_CASE(call_signature_valid)
{
char const* source = R"(
// f(uint256, uint8, string) -> FAILURE
// f(invalid, xyz, foo) -> FAILURE
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 2);
testFunctionCall(calls.at(0), Mode::SingleLine, "f(uint256,uint8,string)", true);
testFunctionCall(calls.at(1), Mode::SingleLine, "f(invalid,xyz,foo)", true);
}
BOOST_AUTO_TEST_CASE(call_raw_arguments)
{
char const* source = R"(
// f(): 1, -2, -3 ->
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f()",
false,
fmt::encodeArgs(1, -2, -3),
fmt::encodeArgs(),
{0},
"",
"",
{"1", "-2", "-3"}
);
}
BOOST_AUTO_TEST_CASE(call_builtin_left_decimal)
{
char const* source = R"(
// f(): left(1), left(0x20) -> left(-2), left(true)
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f()",
false,
fmt::encodeArgs(
fmt::encode(toCompactBigEndian(u256{1}), false),
fmt::encode(fromHex("0x20"), false)
),
fmt::encodeArgs(
fmt::encode(toCompactBigEndian(u256{-2}), false),
fmt::encode(bytes{true}, false)
)
);
}
BOOST_AUTO_TEST_CASE(call_builtin_right_decimal)
{
char const* source = R"(
// f(): right(1), right(0x20) -> right(-2), right(true)
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"f()",
false,
fmt::encodeArgs(1, fromHex("0x20")),
fmt::encodeArgs(-2, true)
);
}
BOOST_AUTO_TEST_CASE(call_arguments_hex_string_left_align)
{
char const* source = R"(
// f(bytes): left(hex"4200ef") ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_hex_string_right_align)
{
char const* source = R"(
// f(bytes): right(hex"4200ef") ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_newline_invalid)
{
char const* source = R"(
/
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_invalid)
{
char const* source = R"(
/ f() ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_signature_invalid)
{
char const* source = R"(
// f(uint8,) -> FAILURE
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_tuple_invalid)
{
char const* source = R"(
// f((uint8,) -> FAILURE
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_tuple_invalid_empty)
{
char const* source = R"(
// f(uint8, ()) -> FAILURE
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_tuple_invalid_parantheses)
{
char const* source = R"(
// f((uint8,() -> FAILURE
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_ether_value_expectations_missing)
{
char const* source = R"(
// f(), 0)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_invalid)
{
char const* source = R"(
// f(uint256): abc -> 1
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_invalid_decimal)
{
char const* source = R"(
// sig(): 0.h3 ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_ether_value_invalid)
{
char const* source = R"(
// f(uint256), abc : 1 -> 1
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_ether_value_invalid_decimal)
{
char const* source = R"(
// sig(): 0.1hd ether ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_ether_type_invalid)
{
char const* source = R"(
// f(uint256), 2 btc : 1 -> 1
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_signed_bool_invalid)
{
char const* source = R"(
// f() -> -true
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_signed_failure_invalid)
{
char const* source = R"(
// f() -> -FAILURE
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_signed_hex_number_invalid)
{
char const* source = R"(
// f() -> -0x42
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_colon)
{
char const* source = R"(
// h256():
// -> 1
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arguments_newline_colon)
{
char const* source = R"(
// h256()
// :
// -> 1
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_arrow_missing)
{
char const* source = R"(
// h256() FAILURE
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(call_unexpected_character)
{
char const* source = R"(
// f() -> ??
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(constructor)
{
char const* source = R"(
// constructor()
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"constructor()",
false,
{},
{},
{0},
"",
"",
{},
true
);
}
BOOST_AUTO_TEST_CASE(library)
{
char const* source = R"(
// library: L
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
testFunctionCall(
calls.at(0),
Mode::SingleLine,
"L",
false,
{},
{},
{0},
"",
"",
{},
false,
true
);
}
BOOST_AUTO_TEST_CASE(call_effects)
{
std::map<std::string, Builtin> builtins;
builtins["builtin_returning_call_effect"] = [](FunctionCall const&) -> std::optional<bytes>
{
return toBigEndian(u256(0x1234));
};
builtins["builtin_returning_call_effect_no_ret"] = [](FunctionCall const&) -> std::optional<bytes>
{
return {};
};
char const* source = R"(
// builtin_returning_call_effect -> 1
// ~ bla
// ~ bla bla
// ~ bla bla bla
)";
std::vector<FunctionCall> calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 3);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "bla");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[1]), "bla bla");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[2]), "bla bla bla");
source = R"(
// builtin_returning_call_effect -> 1
// ~ bla
// ~ bla bla
// builtin_returning_call_effect -> 2
// ~ bla bla bla
// builtin_returning_call_effect -> 3
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 3);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 2);
BOOST_REQUIRE_EQUAL(calls[1].expectedSideEffects.size(), 1);
BOOST_REQUIRE_EQUAL(calls[2].expectedSideEffects.size(), 0);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "bla");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[1]), "bla bla");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[1].expectedSideEffects[0]), "bla bla bla");
source = R"(
// builtin_returning_call_effect -> 1
// ~ bla
// ~ bla bla bla
// ~ abc ~ def ~ ghi
// ~ ~ ~
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 4);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "bla");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[1]), "bla bla bla");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[2]), "abc ~ def ~ ghi");
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[3]), "~ ~");
source = R"(
// builtin_returning_call_effect_no_ret ->
// ~ hello world
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 1);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "hello world");
source = R"(
// builtin_returning_call_effect -> 1
// ~
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 1);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "");
source = R"(
// builtin_returning_call_effect -> 1 # a comment #
// ~ hello world
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 1);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "hello world");
source = R"(
// builtin_returning_call_effect_no_ret -> # another comment #
// ~ hello world
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 1);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "hello world");
source = R"(
// builtin_returning_call_effect_no_ret # another comment #
// ~ hello world
)";
calls = parse(source, builtins);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectedSideEffects.size(), 1);
BOOST_REQUIRE_EQUAL(boost::trim_copy(calls[0].expectedSideEffects[0]), "hello world");
source = R"(
// builtin_returning_call_effect_no_ret # another comment #
// ~ hello/world
)";
BOOST_CHECK_THROW(parse(source, builtins), std::exception);
source = R"(
// builtin_returning_call_effect_no_ret # another comment #
// ~ hello//world
)";
BOOST_CHECK_THROW(parse(source, builtins), std::exception);
}
BOOST_AUTO_TEST_CASE(gas)
{
char const* source = R"(
// f() ->
// gas ir: 3245
// gas legacy: 5000
// gas legacyOptimized: 0
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectations.failure, false);
BOOST_TEST(calls[0].expectations.gasUsedExcludingCode == (std::map<std::string, u256>{
{"ir", 3245},
{"legacy", 5000},
{"legacyOptimized", 0},
}));
BOOST_TEST(calls[0].expectations.gasUsedForCodeDeposit == (std::map<std::string, u256>{
{"ir", 0},
{"legacy", 0},
{"legacyOptimized", 0},
}));
}
BOOST_AUTO_TEST_CASE(gas_before_call)
{
char const* source = R"(
// gas ir: 3245
// f() ->
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_invalid_run_type)
{
char const* source = R"(
// f() ->
// gas ir: 3245
// gas experimental: 5000
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_duplicate_run_type)
{
char const* source = R"(
// f() ->
// gas ir: 3245
// gas ir: 3245
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost)
{
char const* source = R"(
// f() ->
// gas legacyOptimized code: 1
// gas ir: 13000
// gas irOptimized: 6000
// gas irOptimized code: 666
// gas legacy code: 0
// gas legacyOptimized: 1
)";
auto const calls = parse(source);
BOOST_REQUIRE_EQUAL(calls.size(), 1);
BOOST_REQUIRE_EQUAL(calls[0].expectations.failure, false);
BOOST_TEST(calls[0].expectations.gasUsedExcludingCode == (std::map<std::string, u256>{
{"ir", 13000},
{"irOptimized", 6000},
{"legacy", 0},
{"legacyOptimized", 1},
}));
BOOST_TEST(calls[0].expectations.gasUsedForCodeDeposit == (std::map<std::string, u256>{
{"ir", 0},
{"irOptimized", 666},
{"legacy", 0},
{"legacyOptimized", 1},
}));
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost_invalid_suffix)
{
char const* source = R"(
// f() ->
// gas ir data: 3245
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost_tokens_after_suffix)
{
char const* source = R"(
// f() ->
// gas ir code code: 3245
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost_double_code_gas)
{
char const* source = R"(
// f() ->
// gas ir: 3245
// gas ir code: 1
// gas ir code: 1
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost_negative_non_code_cost)
{
// NOTE: This arrangement is unlikely but may still be possible due to refunds.
// We'll deal with it when we actually have a test case like that.
char const* source = R"(
// f() ->
// gas ir: -10
// gas ir code: 20
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost_negative_total_cost)
{
char const* source = R"(
// f() ->
// gas ir: -30
// gas ir code: 20
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_CASE(gas_with_code_deposit_cost_negative_code_cost)
{
char const* source = R"(
// f() ->
// gas ir: 10
// gas ir code: -10
)";
BOOST_REQUIRE_THROW(parse(source), TestParserError);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 28,863
|
C++
|
.cpp
| 1,111
| 23.748875
| 119
| 0.684675
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,010
|
FunctionCallGraph.cpp
|
ethereum_solidity/test/libsolidity/analysis/FunctionCallGraph.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/// Unit tests for libsolidity/analysis/FunctionCallGraph.h
#include <libsolidity/analysis/FunctionCallGraph.h>
#include <test/Common.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolutil/CommonData.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/interface/CompilerStack.h>
#include <boost/test/unit_test.hpp>
#include <range/v3/action/sort.hpp>
#include <range/v3/algorithm/all_of.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/join.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/remove_if.hpp>
#include <range/v3/view/set_algorithm.hpp>
#include <range/v3/view/transform.hpp>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <tuple>
#include <vector>
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace std::string_literals;
using EdgeMap = std::map<
CallGraph::Node,
std::set<CallGraph::Node, CallGraph::CompareByID>,
CallGraph::CompareByID
>;
using EdgeNames = std::set<std::tuple<std::string, std::string>>;
using CallGraphMap = std::map<std::string, CallGraph const*>;
namespace
{
std::unique_ptr<CompilerStack> parseAndAnalyzeContracts(std::string _sourceCode)
{
ReadCallback::Callback fileReader = [](std::string const&, std::string const&)
{
soltestAssert(false, "For simplicity this test suite supports only files without imports.");
return ReadCallback::Result{true, ""};
};
auto compilerStack = std::make_unique<CompilerStack>(fileReader);
compilerStack->setSources({{"", _sourceCode}});
// NOTE: The code in test cases is expected to be correct so we can keep error handling simple
// here and just assert that there are no errors.
bool success = compilerStack->parseAndAnalyze();
soltestAssert(success, "");
soltestAssert(
ranges::all_of(
compilerStack->ast("").nodes(),
[](auto const& _node){ return !dynamic_cast<ImportDirective const*>(_node.get()); }
),
"For simplicity this test suite supports only files without imports."
);
return compilerStack;
}
EdgeNames edgeNames(EdgeMap const& _edgeMap)
{
EdgeNames names;
for (auto const& [edgeStart, allEnds]: _edgeMap)
for (auto const& edgeEnd: allEnds)
names.emplace(toString(edgeStart), toString(edgeEnd));
return names;
}
std::tuple<CallGraphMap, CallGraphMap> collectGraphs(CompilerStack const& _compilerStack)
{
soltestAssert(_compilerStack.state() >= CompilerStack::State::AnalysisSuccessful);
std::tuple<CallGraphMap, CallGraphMap> graphs;
for (std::string const& fullyQualifiedContractName: _compilerStack.contractNames())
{
soltestAssert(std::get<0>(graphs).count(fullyQualifiedContractName) == 0 && std::get<1>(graphs).count(fullyQualifiedContractName) == 0, "");
// This relies on two assumptions: (1) CompilerStack received an empty string as a path for
// the contract and (2) contracts used in test cases have no imports.
soltestAssert(fullyQualifiedContractName.size() > 0 && fullyQualifiedContractName[0] == ':', "");
std::string contractName = fullyQualifiedContractName.substr(1);
std::get<0>(graphs).emplace(contractName, _compilerStack.contractDefinition(fullyQualifiedContractName).annotation().creationCallGraph->get());
std::get<1>(graphs).emplace(contractName, _compilerStack.contractDefinition(fullyQualifiedContractName).annotation().deployedCallGraph->get());
}
return graphs;
}
void checkCallGraphExpectations(
CallGraphMap const& _callGraphs,
std::map<std::string, EdgeNames> const& _expectedEdges,
std::map<std::string, std::set<std::string>> const& _expectedCreatedContractSets = {},
std::map<std::string, std::set<std::string>> const& _expectedEmittedEventSets = {}
)
{
auto getContractName = [](ContractDefinition const* _contract){ return _contract->name(); };
auto eventToString = [](EventDefinition const* _event){ return toString(CallGraph::Node(_event)); };
auto notEmpty = [](std::set<std::string> const& _set){ return !_set.empty(); };
soltestAssert(
(_expectedCreatedContractSets | ranges::views::values | ranges::views::remove_if(notEmpty)).empty(),
"Contracts that are not expected to create other contracts should not be included in _expectedCreatedContractSets."
);
soltestAssert(
(_expectedEdges | ranges::views::keys | ranges::to<std::set>()) == (_callGraphs | ranges::views::keys | ranges::to<std::set>()) &&
(ranges::views::set_difference(_expectedCreatedContractSets | ranges::views::keys, _expectedEdges | ranges::views::keys)).empty(),
"Contracts listed in expectations do not match contracts actually found in the source file or in other expectations."
);
for (std::string const& contractName: _expectedEdges | ranges::views::keys)
{
soltestAssert(
(ranges::views::set_difference(valueOrDefault(_expectedCreatedContractSets, contractName, {}), _expectedEdges | ranges::views::keys)).empty(),
"Inconsistent expectations: contract expected to be created but not to be present in the source file."
);
}
std::map<std::string, EdgeNames> edges;
std::map<std::string, std::set<std::string>> createdContractSets;
std::map<std::string, std::set<std::string>> emittedEventSets;
for (std::string const& contractName: _expectedEdges | ranges::views::keys)
{
soltestAssert(_callGraphs.at(contractName) != nullptr, "");
CallGraph const& callGraph = *_callGraphs.at(contractName);
edges[contractName] = edgeNames(callGraph.edges);
if (!callGraph.bytecodeDependency.empty())
createdContractSets[contractName] = callGraph.bytecodeDependency |
ranges::views::keys |
ranges::views::transform(getContractName) |
ranges::to<std::set<std::string>>();
if (!callGraph.emittedEvents.empty())
emittedEventSets[contractName] = callGraph.emittedEvents |
ranges::views::transform(eventToString) |
ranges::to<std::set<std::string>>();
}
BOOST_CHECK_EQUAL(edges, _expectedEdges);
BOOST_CHECK_EQUAL(createdContractSets, _expectedCreatedContractSets);
BOOST_CHECK_EQUAL(emittedEventSets, _expectedEmittedEventSets);
}
std::ostream& operator<<(std::ostream& _out, EdgeNames const& _edgeNames)
{
for (auto const& [from, to]: _edgeNames)
_out << " " << from << " -> " << to << std::endl;
return _out;
}
std::ostream& operator<<(std::ostream& _out, std::set<std::string> const& _set)
{
_out << "{" << (_set | ranges::views::join(", ") | ranges::to<std::string>()) << "}";
return _out;
}
std::ostream& operator<<(std::ostream& _out, std::map<std::string, EdgeNames> const& _edgeSets)
{
// Extra newline for error report readability. Otherwise the first line does not start at the first column.
_out << std::endl;
for (auto const &[contractName, edges]: _edgeSets)
{
_out << contractName << ":" << std::endl;
_out << edges;
}
return _out;
}
std::ostream& operator<<(std::ostream& _out, std::map<std::string, std::set<std::string>> const& _map)
{
// Extra newline for error report readability. Otherwise the first line does not start at the first column.
_out << std::endl;
for (auto const &[key, value]: _map)
_out << key << ": " << value << std::endl;
return _out;
}
} // namespace
namespace boost::test_tools::tt_detail
{
// Boost won't find the << operator unless we put it in the std namespace which is illegal.
// The recommended solution is to overload print_log_value<> struct and make it use our operator.
template<>
struct print_log_value<EdgeNames>
{
void operator()(std::ostream& _output, EdgeNames const& _edgeNames) { ::operator<<(_output, _edgeNames); }
};
template<>
struct print_log_value<std::set<std::string>>
{
void operator()(std::ostream& _output, std::set<std::string> const& _set) { ::operator<<(_output, _set); }
};
template<>
struct print_log_value<std::map<std::string, EdgeNames>>
{
void operator()(std::ostream& _output, std::map<std::string, EdgeNames> const& _edgeSets) { ::operator<<(_output, _edgeSets); }
};
template<>
struct print_log_value<std::map<std::string, std::set<std::string>>>
{
void operator()(std::ostream& _output, std::map<std::string, std::set<std::string>> const& _map) { ::operator<<(_output, _map); }
};
} // namespace boost::test_tools::tt_detail
namespace solidity::frontend::test
{
BOOST_AUTO_TEST_SUITE(FunctionCallGraphTest)
BOOST_AUTO_TEST_CASE(only_definitions)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() {}
library L {
function ext() external {}
function pub() public {}
function inr() internal {}
function prv() private {}
}
contract C {
function ext() external {}
function pub() public {}
function inr() internal {}
function prv() private {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
{"Entry", "function C.pub()"},
}},
{"L", {
{"Entry", "function L.ext()"},
{"Entry", "function L.pub()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(ordinary_calls)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() {}
library L {
function ext() external { pub(); inr(); }
function pub() public { inr(); }
function inr() internal { prv(); }
function prv() private { free(); free(); }
}
contract C {
function ext() external { pub(); }
function pub() public { inr(); prv(); free(); }
function inr() internal { prv(); L.inr(); }
function prv() private { free(); free(); }
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
{"Entry", "function C.pub()"},
{"function C.ext()", "function C.pub()"},
{"function C.pub()", "function C.inr()"},
{"function C.pub()", "function C.prv()"},
{"function C.pub()", "function free()"},
{"function C.inr()", "function C.prv()"},
{"function C.inr()", "function L.inr()"},
{"function C.prv()", "function free()"},
{"function L.inr()", "function L.prv()"},
{"function L.prv()", "function free()"},
}},
{"L", {
{"Entry", "function L.ext()"},
{"Entry", "function L.pub()"},
{"function L.ext()", "function L.pub()"},
{"function L.ext()", "function L.inr()"},
{"function L.pub()", "function L.inr()"},
{"function L.inr()", "function L.prv()"},
{"function L.prv()", "function free()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(call_chains_through_externals)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
library L {
function ext() external { C(address(0x0)).ext(); }
function pub() public {}
function inr() internal {}
function prv() private {}
}
contract C {
function ext() external {}
function pub() public {}
function inr() internal {}
function prv() private {}
function ext2() external { this.ext(); this.pub(); L.ext(); L.pub(); }
function pub2() public { this.ext(); this.pub(); L.ext(); L.pub(); }
function pub3() public { C(address(0x0)).ext(); }
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
{"Entry", "function C.ext2()"},
{"Entry", "function C.pub()"},
{"Entry", "function C.pub2()"},
{"Entry", "function C.pub3()"},
}},
{"L", {
{"Entry", "function L.ext()"},
{"Entry", "function L.pub()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(calls_from_constructors)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() returns (uint) {}
library L {
function ext() external {}
}
contract C {
constructor() { this.ext(); inr(); L.ext(); free(); }
function ext() external {}
function inr() internal {}
}
contract D {
uint a = this.ext();
uint b = inr();
uint c = free();
function ext() external returns (uint) {}
function inr() internal returns (uint) {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {
{"Entry", "constructor of C"},
{"constructor of C", "function C.inr()"},
{"constructor of C", "function free()"},
}},
{"D", {
{"Entry", "function D.inr()"},
{"Entry", "function free()"},
}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
}},
{"D", {
{"Entry", "function D.ext()"},
}},
{"L", {
{"Entry", "function L.ext()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(calls_to_constructors)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() { new D(); }
library L {
function ext() external { new C(); new D(); inr(); }
function inr() internal { new C(); new D(); free(); }
}
contract C {
constructor() { new D(); }
function ext() external { new D(); inr(); }
function inr() internal { new D(); free(); }
}
contract D {}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {
{"Entry", "constructor of C"},
}},
{"D", {}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
{"function C.ext()", "function C.inr()"},
{"function C.inr()", "function free()"},
}},
{"D", {}},
{"L", {
{"Entry", "function L.ext()"},
{"function L.ext()", "function L.inr()"},
{"function L.inr()", "function free()"},
}},
};
std::map<std::string, std::set<std::string>> expectedCreatedContractsAtCreation = {
{"C", {"D"}},
};
std::map<std::string, std::set<std::string>> expectedCreatedContractsAfterDeployment = {
{"C", {"D"}},
{"L", {"C", "D"}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges, expectedCreatedContractsAtCreation);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges, expectedCreatedContractsAfterDeployment);
}
BOOST_AUTO_TEST_CASE(inherited_constructors)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() {}
library L {
function ext() external { inr(); }
function inr() internal { free(); }
}
contract C {
constructor() { inrC(); free(); }
function extC() external returns (uint) { inrC(); }
function inrC() internal returns (uint) { free(); }
}
contract D {
constructor() { L.ext(); }
}
contract E is C {
uint e2 = this.extE();
uint i2 = inrE();
function extE() external returns (uint) { inrE(); }
function inrE() internal returns (uint) { free(); }
}
contract F is C, D(), E {
uint e3 = this.extF();
uint i3 = inrF();
constructor() E() C() {}
function extF() external returns (uint) { inrF(); }
function inrF() internal returns (uint) { free(); }
}
contract G is E() {
function extG() external returns (uint) { new F(); }
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {
{"Entry", "constructor of C"},
{"constructor of C", "function C.inrC()"},
{"constructor of C", "function free()"},
{"function C.inrC()", "function free()"},
}},
{"D", {
{"Entry", "constructor of D"},
}},
{"E", {
{"Entry", "constructor of C"},
{"Entry", "function E.inrE()"},
{"constructor of C", "function C.inrC()"},
{"constructor of C", "function free()"},
{"function C.inrC()", "function free()"},
{"function E.inrE()", "function free()"},
}},
{"F", {
{"Entry", "constructor of C"},
{"Entry", "constructor of D"},
{"Entry", "constructor of F"},
{"Entry", "function E.inrE()"},
{"Entry", "function F.inrF()"},
{"constructor of C", "function C.inrC()"},
{"constructor of C", "function free()"},
{"function C.inrC()", "function free()"},
{"function E.inrE()", "function free()"},
{"function F.inrF()", "function free()"},
}},
{"G", {
{"Entry", "constructor of C"},
{"Entry", "function E.inrE()"},
{"constructor of C", "function C.inrC()"},
{"constructor of C", "function free()"},
{"function C.inrC()", "function free()"},
{"function E.inrE()", "function free()"},
}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.extC()"},
{"function C.extC()", "function C.inrC()"},
{"function C.inrC()", "function free()"},
}},
{"D", {}},
{"E", {
{"Entry", "function C.extC()"},
{"Entry", "function E.extE()"},
{"function C.extC()", "function C.inrC()"},
{"function E.extE()", "function E.inrE()"},
{"function C.inrC()", "function free()"},
{"function E.inrE()", "function free()"},
}},
{"F", {
{"Entry", "function C.extC()"},
{"Entry", "function E.extE()"},
{"Entry", "function F.extF()"},
{"function C.extC()", "function C.inrC()"},
{"function E.extE()", "function E.inrE()"},
{"function F.extF()", "function F.inrF()"},
{"function C.inrC()", "function free()"},
{"function E.inrE()", "function free()"},
{"function F.inrF()", "function free()"},
}},
{"G", {
{"Entry", "function C.extC()"},
{"Entry", "function E.extE()"},
{"Entry", "function G.extG()"},
{"function C.extC()", "function C.inrC()"},
{"function E.extE()", "function E.inrE()"},
{"function C.inrC()", "function free()"},
{"function E.inrE()", "function free()"},
}},
{"L", {
{"Entry", "function L.ext()"},
{"function L.ext()", "function L.inr()"},
{"function L.inr()", "function free()"},
}},
};
std::map<std::string, std::set<std::string>> expectedCreatedContractsAtCreation = {};
std::map<std::string, std::set<std::string>> expectedCreatedContractsAfterDeployment = {
{"G", {"F"}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges, expectedCreatedContractsAtCreation);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges, expectedCreatedContractsAfterDeployment);
}
BOOST_AUTO_TEST_CASE(inheritance_specifiers)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function fD() returns (uint) {}
function fE() returns (uint) {}
function fFD() returns (uint) {}
function fFE() returns (uint) {}
function fG() returns (uint) {}
function fVarC() returns (uint) {}
function fVarD() returns (uint) {}
function fVarE() returns (uint) {}
function fVarF() returns (uint) {}
contract C {
uint c = fVarC();
constructor (uint) {}
}
contract D is C(fD()) {
uint d = fVarD();
constructor (uint) {}
}
abstract contract E is C {
uint e = fVarE();
constructor (uint) {}
}
contract F is D(fFD()), E {
uint f = fVarF();
constructor (uint) E(fFE()) {}
}
contract G is D(fG()), E(fG()) {}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {
{"Entry", "constructor of C"},
{"Entry", "function fVarC()"},
}},
{"D", {
{"Entry", "constructor of C"},
{"Entry", "constructor of D"},
{"Entry", "function fVarC()"},
{"Entry", "function fVarD()"},
{"constructor of D", "function fD()"},
}},
{"E", {
{"Entry", "constructor of C"},
{"Entry", "constructor of E"},
{"Entry", "function fVarC()"},
{"Entry", "function fVarE()"},
}},
{"F", {
{"Entry", "constructor of C"},
{"Entry", "constructor of D"},
{"Entry", "constructor of E"},
{"Entry", "constructor of F"},
{"Entry", "function fVarC()"},
{"Entry", "function fVarD()"},
{"Entry", "function fVarE()"},
{"Entry", "function fVarF()"},
{"constructor of D", "function fD()"},
{"constructor of F", "function fFD()"},
{"constructor of F", "function fFE()"},
}},
{"G", {
{"Entry", "constructor of C"},
{"Entry", "constructor of D"},
{"Entry", "constructor of E"},
// G, unlike F, has no constructor so fG() gets an edge from Entry.
{"Entry", "function fG()"},
{"Entry", "function fVarC()"},
{"Entry", "function fVarD()"},
{"Entry", "function fVarE()"},
{"constructor of D", "function fD()"},
}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {}},
{"D", {}},
{"E", {}},
{"F", {}},
{"G", {}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(inherited_functions_virtual_and_super)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
function f() internal {}
function g() internal virtual {}
function h() internal virtual {}
function ext() external virtual {}
}
contract D {
function h() internal virtual {}
function ext() external virtual {}
}
contract E is C, D {
function g() internal override {}
function h() internal override(C, D) {}
function i() internal {}
function ext() external override(C, D) {}
function callF() external { f(); }
function callG() external { g(); }
function callH() external { h(); }
function callI() external { i(); }
function callCF() external { C.f(); }
function callCG() external { C.g(); }
function callCH() external { C.h(); }
function callDH() external { D.h(); }
function callEI() external { E.i(); }
function callSuperF() external { super.f(); }
function callSuperG() external { super.g(); }
function callSuperH() external { super.h(); }
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
{"E", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
}},
{"D", {
{"Entry", "function D.ext()"},
}},
{"E", {
{"Entry", "function E.callF()"},
{"Entry", "function E.callG()"},
{"Entry", "function E.callH()"},
{"Entry", "function E.callI()"},
{"Entry", "function E.callCF()"},
{"Entry", "function E.callCG()"},
{"Entry", "function E.callCH()"},
{"Entry", "function E.callDH()"},
{"Entry", "function E.callEI()"},
{"Entry", "function E.callSuperF()"},
{"Entry", "function E.callSuperG()"},
{"Entry", "function E.callSuperH()"},
{"Entry", "function E.ext()"},
{"function E.callF()", "function C.f()"},
{"function E.callG()", "function E.g()"},
{"function E.callH()", "function E.h()"},
{"function E.callI()", "function E.i()"},
{"function E.callCF()", "function C.f()"},
{"function E.callCG()", "function C.g()"},
{"function E.callCH()", "function C.h()"},
{"function E.callDH()", "function D.h()"},
{"function E.callEI()", "function E.i()"},
{"function E.callSuperF()", "function C.f()"},
{"function E.callSuperG()", "function C.g()"},
{"function E.callSuperH()", "function D.h()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(overloaded_functions)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
enum E {E1, E2, E3}
function free() {}
function free(uint) {}
function free(bytes memory) {}
function free(E) {}
contract C {
function f(E) internal {}
function f(bool) external {}
}
contract D is C {
function ext1() external { free(); free(123); free("123"); }
function ext2() external { f(); f(123); f("123"); }
function ext3() external { free(E.E2); f(E.E2); }
function ext4() external { this.f(false); }
function f() internal {}
function f(uint) internal {}
function f(bytes memory) internal {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.f(bool)"},
}},
{"D", {
{"Entry", "function C.f(bool)"},
{"Entry", "function D.ext1()"},
{"Entry", "function D.ext2()"},
{"Entry", "function D.ext3()"},
{"Entry", "function D.ext4()"},
{"function D.ext1()", "function free()"},
{"function D.ext1()", "function free(uint256)"},
{"function D.ext1()", "function free(bytes)"},
{"function D.ext2()", "function D.f()"},
{"function D.ext2()", "function D.f(uint256)"},
{"function D.ext2()", "function D.f(bytes)"},
{"function D.ext3()", "function free(enum E)"},
{"function D.ext3()", "function C.f(enum E)"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(modifiers)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
library L {
modifier m() { g(); _; }
function f() m internal {}
function g() internal {}
}
contract C {
modifier m1() virtual { _; }
function q() m1 internal virtual { L.f(); }
}
contract D is C {
modifier m2() { q(); _; new C(); }
function p() m2 internal { C.q(); }
function q() m2 internal override virtual {}
}
contract E is D {
modifier m1() override { _; }
modifier m3() { p(); _; }
constructor() D() m1 E.m3 {}
function ext() external m1 E.m3 { inr(); }
function inr() internal m1 E.m3 { L.f(); }
function q() internal override {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
{"L", {}},
{"E", {
{"Entry", "constructor of E"},
{"constructor of E", "modifier E.m1"},
{"constructor of E", "modifier E.m3"},
{"function C.q()", "modifier E.m1"},
{"function C.q()", "function L.f()"},
{"function D.p()", "modifier D.m2"},
{"function D.p()", "function C.q()"},
{"function L.f()", "modifier L.m"},
{"modifier L.m", "function L.g()"},
{"modifier D.m2", "function E.q()"},
{"modifier E.m3", "function D.p()"},
}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {}},
{"D", {}},
{"L", {}},
{"E", {
{"Entry", "function E.ext()"},
{"function C.q()", "modifier E.m1"},
{"function C.q()", "function L.f()"},
{"function D.p()", "modifier D.m2"},
{"function D.p()", "function C.q()"},
{"function L.f()", "modifier L.m"},
{"function E.ext()", "function E.inr()"},
{"function E.ext()", "modifier E.m1"},
{"function E.ext()", "modifier E.m3"},
{"function E.inr()", "modifier E.m1"},
{"function E.inr()", "modifier E.m3"},
{"function E.inr()", "function L.f()"},
{"modifier L.m", "function L.g()"},
{"modifier D.m2", "function E.q()"},
{"modifier E.m3", "function D.p()"},
}},
};
std::map<std::string, std::set<std::string>> expectedCreatedContractsAtCreation = {{"E", {"C"}}};
std::map<std::string, std::set<std::string>> expectedCreatedContractsAfterDeployment = {{"E", {"C"}}};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges, expectedCreatedContractsAtCreation);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges, expectedCreatedContractsAfterDeployment);
}
BOOST_AUTO_TEST_CASE(events)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() { emit L.Ev(); }
library L {
event Ev();
event Ev(bytes4, string indexed);
function ext() external { emit Ev(); }
function inr() internal { emit Ev(0x12345678, "a"); emit L.Ev(); }
}
contract C {
event EvC(uint) anonymous;
modifier m() { emit EvC(1); _; }
}
contract D is C {
event EvD1(uint);
event EvD2(uint);
function ext() m external { emit D.EvD1(1); emit EvC(f()); inr(); }
function inr() m internal { emit EvD1(1); emit C.EvC(f()); L.inr(); free(); EvD2; }
function f() internal returns (uint) {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {}},
{"D", {
{"Entry", "function D.ext()"},
{"function D.ext()", "function D.inr()"},
{"function D.ext()", "modifier C.m"},
{"function D.ext()", "function D.f()"},
{"function D.inr()", "function L.inr()"},
{"function D.inr()", "function free()"},
{"function D.inr()", "modifier C.m"},
{"function D.inr()", "function D.f()"},
}},
{"L", {
{"Entry", "function L.ext()"},
}},
};
std::map<std::string, std::set<std::string>> expectedCreationEvents = {};
std::map<std::string, std::set<std::string>> expectedDeployedEvents = {
{"D", {
"event D.EvD1(uint256)",
"event C.EvC(uint256)",
"event L.Ev(bytes4,string)",
"event L.Ev()",
}},
{"L", {
"event L.Ev()",
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges, {}, expectedCreationEvents);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges, {}, expectedDeployedEvents);
}
BOOST_AUTO_TEST_CASE(cycles)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free1() { free1(); }
function free2() { free3(); }
function free3() { free2(); }
library L {
function inr1() internal { inr1(); }
function inr2() internal { inr3(); }
function inr3() internal { inr2(); }
}
contract C {
function virt() internal virtual { virt(); }
}
contract D is C {
function init() external { this.ext1(); inr1(); inr2(); L.inr1(); L.inr2(); free1(); free2(); virt(); }
function ext1() external { this.ext1(); }
function ext2() external { this.ext3(); }
function ext3() external { this.ext2(); }
function inr1() internal { inr1(); }
function inr2() internal { inr3(); }
function inr3() internal { inr2(); }
function inr3(uint) internal {}
function virt() internal override { C.virt(); }
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"L", {}},
{"C", {}},
{"D", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"L", {}},
{"C", {}},
{"D", {
{"Entry", "function D.init()"},
{"Entry", "function D.ext1()"},
{"Entry", "function D.ext2()"},
{"Entry", "function D.ext3()"},
{"function D.init()", "function D.inr1()"},
{"function D.init()", "function D.inr2()"},
{"function D.init()", "function D.virt()"},
{"function D.init()", "function L.inr1()"},
{"function D.init()", "function L.inr2()"},
{"function D.init()", "function free1()"},
{"function D.init()", "function free2()"},
{"function D.inr1()", "function D.inr1()"},
{"function D.inr2()", "function D.inr3()"},
{"function D.inr3()", "function D.inr2()"},
{"function D.virt()", "function C.virt()"},
{"function C.virt()", "function D.virt()"},
{"function L.inr1()", "function L.inr1()"},
{"function L.inr2()", "function L.inr3()"},
{"function L.inr3()", "function L.inr2()"},
{"function free1()", "function free1()"},
{"function free2()", "function free3()"},
{"function free3()", "function free2()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(interfaces_and_abstract_contracts)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
interface I {
event Ev(uint);
function ext1() external;
function ext2() external;
}
interface J is I {
function ext2() external override;
function ext3() external;
}
abstract contract C is J {
modifier m() virtual;
function ext3() external override virtual;
function ext4() external { inr2();}
function inr1() internal virtual;
function inr2() m internal { inr1(); this.ext1(); this.ext2(); this.ext3(); }
}
contract D is C {
function ext1() public override { emit I.Ev(1); inr1(); inr2(); }
function ext2() external override { I(this).ext1(); }
function ext3() external override {}
function inr1() internal override {}
modifier m() override { _; }
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"I", {}},
{"J", {}},
{"C", {}},
{"D", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"I", {
{"Entry", "function I.ext1()"},
{"Entry", "function I.ext2()"},
}},
{"J", {
{"Entry", "function I.ext1()"},
{"Entry", "function J.ext2()"},
{"Entry", "function J.ext3()"},
}},
{"C", {
{"Entry", "function I.ext1()"},
{"Entry", "function J.ext2()"},
{"Entry", "function C.ext3()"},
{"Entry", "function C.ext4()"},
{"function C.ext4()", "function C.inr2()"},
{"function C.inr2()", "function C.inr1()"},
{"function C.inr2()", "modifier C.m"},
}},
{"D", {
{"Entry", "function D.ext1()"},
{"Entry", "function D.ext2()"},
{"Entry", "function D.ext3()"},
{"Entry", "function C.ext4()"},
{"function C.ext4()", "function C.inr2()"},
{"function C.inr2()", "function D.inr1()"},
{"function C.inr2()", "modifier D.m"},
{"function D.ext1()", "function D.inr1()"},
{"function D.ext1()", "function C.inr2()"},
}},
};
std::map<std::string, std::set<std::string>> expectedCreationEvents = {};
std::map<std::string, std::set<std::string>> expectedDeployedEvents = {
{"D", {
"event I.Ev(uint256)",
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges, {}, expectedCreationEvents);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges, {}, expectedDeployedEvents);
}
BOOST_AUTO_TEST_CASE(indirect_calls)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free1() {}
function free2() {}
function free3() {}
library L {
function ext() external {}
function inr1() internal {}
function inr2() internal {}
function inr3() internal {}
function access() public {
free1;
inr1;
L.ext;
}
function expression() public {
(free2)();
(inr2)();
}
}
contract C {
function ext1() external {}
function ext2() external {}
function ext3() external {}
function inr1() internal {}
function inr2() internal {}
function inr3() internal {}
function access() public {
this.ext1;
inr1;
free1;
L.inr1;
L.ext;
}
function expression() public {
(this.ext2)();
(inr2)();
(free2)();
(L.inr2)();
(L.ext)();
}
}
contract D is C {
constructor() {
access();
expression();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"L", {}},
{"C", {}},
{"D", {
{"InternalDispatch", "function L.inr2()"},
{"InternalDispatch", "function C.inr1()"},
{"InternalDispatch", "function C.inr2()"},
{"InternalDispatch", "function free1()"},
{"InternalDispatch", "function free2()"},
{"InternalDispatch", "function L.inr1()"},
{"InternalDispatch", "function L.inr2()"},
{"Entry", "constructor of D"},
{"constructor of D", "function C.access()"},
{"constructor of D", "function C.expression()"},
{"function C.expression()", "InternalDispatch"},
}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"L", {
{"InternalDispatch", "function L.inr1()"},
{"InternalDispatch", "function L.inr2()"},
{"InternalDispatch", "function free1()"},
{"InternalDispatch", "function free2()"},
{"Entry", "function L.ext()"},
{"Entry", "function L.access()"},
{"Entry", "function L.expression()"},
{"function L.expression()", "InternalDispatch"},
}},
{"C", {
{"InternalDispatch", "function C.inr1()"},
{"InternalDispatch", "function C.inr2()"},
{"InternalDispatch", "function free1()"},
{"InternalDispatch", "function free2()"},
{"InternalDispatch", "function L.inr1()"},
{"InternalDispatch", "function L.inr2()"},
{"Entry", "function C.ext1()"},
{"Entry", "function C.ext2()"},
{"Entry", "function C.ext3()"},
{"Entry", "function C.access()"},
{"Entry", "function C.expression()"},
{"function C.expression()", "InternalDispatch"},
}},
{"D", {
{"InternalDispatch", "function L.inr2()"},
{"InternalDispatch", "function C.inr1()"},
{"InternalDispatch", "function C.inr2()"},
{"InternalDispatch", "function free1()"},
{"InternalDispatch", "function free2()"},
{"InternalDispatch", "function L.inr1()"},
{"InternalDispatch", "function L.inr2()"},
{"Entry", "function C.ext1()"},
{"Entry", "function C.ext2()"},
{"Entry", "function C.ext3()"},
{"Entry", "function C.access()"},
{"Entry", "function C.expression()"},
{"function C.expression()", "InternalDispatch"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(calls_via_pointers)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free1() {}
function free2() {}
function free3() {}
library L {
function inr1() internal {}
function inr2() internal {}
function inr3() internal {}
function callPtrs(
function () external e,
function () internal i,
function () internal f,
function () internal l
) internal
{
e();
i();
f();
l();
}
}
contract C {
function ext1() external {}
function ext2() external {}
function ext3() external {}
function inr1() internal {}
function inr2() internal {}
function inr3() internal {}
function getPtrs2() internal returns (
function () external,
function () internal,
function () internal,
function () internal
)
{
return (this.ext2, inr2, free2, L.inr2);
}
function testLocalVars() public {
(function () external e, function () i, function () f, function () l) = getPtrs2();
L.callPtrs(e, i, f, l);
}
}
contract D is C {
function () external m_e = this.ext1;
function () internal m_i = inr1;
function () internal m_f = free1;
function () internal m_l = L.inr1;
function () internal immutable m_imm = inr1;
function callStatePtrs() internal {
m_e();
m_i();
m_f();
m_l();
}
function updateStatePtrs(
function () external e,
function () internal i,
function () internal f,
function () internal l
) internal
{
m_e = e;
m_i = i;
m_f = f;
m_l = l;
}
function testStateVars() public {
(function () external e, function () i, function () f, function () l) = getPtrs2();
updateStatePtrs(e, i, f, l);
callStatePtrs();
}
function testImmutablePtr() public {
m_imm();
}
constructor() {
testStateVars();
testLocalVars();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"L", {}},
{"C", {}},
{"D", {
{"InternalDispatch", "function C.inr1()"},
{"InternalDispatch", "function C.inr2()"},
{"InternalDispatch", "function L.inr1()"},
{"InternalDispatch", "function L.inr2()"},
{"InternalDispatch", "function free1()"},
{"InternalDispatch", "function free2()"},
{"Entry", "constructor of D"},
{"constructor of D", "function C.testLocalVars()"},
{"constructor of D", "function D.testStateVars()"},
{"function C.testLocalVars()", "function C.getPtrs2()"},
{"function C.testLocalVars()", "function L.callPtrs(function () external,function (),function (),function ())"},
{"function D.testStateVars()", "function C.getPtrs2()"},
{"function D.testStateVars()", "function D.updateStatePtrs(function () external,function (),function (),function ())"},
{"function D.testStateVars()", "function D.callStatePtrs()"},
{"function D.callStatePtrs()", "InternalDispatch"},
{"function L.callPtrs(function () external,function (),function (),function ())", "InternalDispatch"},
}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"L", {}},
{"C", {
{"InternalDispatch", "function C.inr2()"},
{"InternalDispatch", "function L.inr2()"},
{"InternalDispatch", "function free2()"},
{"Entry", "function C.ext1()"},
{"Entry", "function C.ext2()"},
{"Entry", "function C.ext3()"},
{"Entry", "function C.testLocalVars()"},
{"function C.testLocalVars()", "function C.getPtrs2()"},
{"function C.testLocalVars()", "function L.callPtrs(function () external,function (),function (),function ())"},
{"function L.callPtrs(function () external,function (),function (),function ())", "InternalDispatch"},
}},
{"D", {
{"InternalDispatch", "function C.inr1()"},
{"InternalDispatch", "function C.inr2()"},
{"InternalDispatch", "function L.inr1()"},
{"InternalDispatch", "function L.inr2()"},
{"InternalDispatch", "function free1()"},
{"InternalDispatch", "function free2()"},
{"Entry", "function C.ext1()"},
{"Entry", "function C.ext2()"},
{"Entry", "function C.ext3()"},
{"Entry", "function C.testLocalVars()"},
{"Entry", "function D.testStateVars()"},
{"Entry", "function D.testImmutablePtr()"},
{"function C.testLocalVars()", "function C.getPtrs2()"},
{"function C.testLocalVars()", "function L.callPtrs(function () external,function (),function (),function ())"},
{"function D.testStateVars()", "function C.getPtrs2()"},
{"function D.testStateVars()", "function D.updateStatePtrs(function () external,function (),function (),function ())"},
{"function D.testStateVars()", "function D.callStatePtrs()"},
{"function D.testImmutablePtr()", "InternalDispatch"},
{"function D.callStatePtrs()", "InternalDispatch"},
{"function L.callPtrs(function () external,function (),function (),function ())", "InternalDispatch"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(pointer_to_overridden_function)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
function f() internal virtual {}
}
contract D is C {
function f() internal override {}
function getF() internal returns (function ()) {
return C.f;
}
function getSuperF() internal returns (function ()) {
return super.f;
}
function test1() public {
getF()();
}
function test2() public {
getSuperF()();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {}},
{"D", {
{"InternalDispatch", "function C.f()"},
{"Entry", "function D.test1()"},
{"Entry", "function D.test2()"},
{"function D.test1()", "function D.getF()"},
{"function D.test1()", "InternalDispatch"},
{"function D.test2()", "function D.getSuperF()"},
{"function D.test2()", "InternalDispatch"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(pointer_to_nonexistent_function)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
interface I {
function f() external;
}
abstract contract C is I {
function g() internal virtual;
function getF() internal returns (function () external) { return this.f; }
function getG() internal returns (function () internal) { return g; }
function testInterface() public {
getF()();
getG()();
}
function testBadPtr() public {
function () ptr;
ptr();
}
}
contract D is C {
function f() public override {}
function g() internal override {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"I", {}},
{"C", {}},
{"D", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"I", {
{"Entry", "function I.f()"},
}},
{"C", {
{"InternalDispatch", "function C.g()"},
{"Entry", "function C.testInterface()"},
{"Entry", "function C.testBadPtr()"},
{"Entry", "function I.f()"},
{"function C.testInterface()", "function C.getF()"},
{"function C.testInterface()", "function C.getG()"},
{"function C.testInterface()", "InternalDispatch"},
{"function C.testBadPtr()", "InternalDispatch"},
}},
{"D", {
{"InternalDispatch", "function D.g()"},
{"Entry", "function C.testInterface()"},
{"Entry", "function C.testBadPtr()"},
{"Entry", "function D.f()"},
{"function C.testInterface()", "function C.getF()"},
{"function C.testInterface()", "function C.getG()"},
{"function C.testInterface()", "InternalDispatch"},
{"function C.testBadPtr()", "InternalDispatch"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(function_self_reference)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
function f() public returns (bool ret) {
return f == f;
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.f()"},
{"InternalDispatch", "function C.f()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(pointer_cycle)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
function () ptr = f;
function f() internal { ptr(); }
function test() public {
ptr();
}
}
)"s);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {
{"InternalDispatch", "function C.f()"},
{"function C.f()", "InternalDispatch"},
}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"InternalDispatch", "function C.f()"},
{"Entry", "function C.test()"},
{"function C.test()", "InternalDispatch"},
{"function C.f()", "InternalDispatch"},
}},
};
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(using_for)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
struct S {
uint x;
}
library L {
function ext(S memory _s) external {}
function inr(S memory _s) internal {}
}
contract C {
using L for S;
function pub() public {
S memory s = S(42);
s.ext();
s.inr();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"L", {}},
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"L", {
{"Entry", "function L.ext(struct S)"},
}},
{"C", {
{"Entry", "function C.pub()"},
{"function C.pub()", "function L.inr(struct S)"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(user_defined_binary_operator)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
type Int is int128;
using {add as +} for Int global;
function add(Int, Int) pure returns (Int) {
return Int.wrap(0);
}
contract C {
function pub() public {
Int.wrap(0) + Int.wrap(1);
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.pub()"},
{"function C.pub()", "function add(Int,Int)"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(user_defined_unary_operator)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
type Int is int128;
using {sub as -} for Int global;
function sub(Int) pure returns (Int) {
return Int.wrap(0);
}
contract C {
function pub() public {
-Int.wrap(1);
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.pub()"},
{"function C.pub()", "function sub(Int)"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(getters)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
uint public variable;
uint[][] public array;
mapping(bytes => bytes) public map;
function test() public {
this.variable();
this.array(1, 2);
this.map("value");
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {{"Entry", "function C.test()"}}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(fallback_and_receive)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
function ext() external {}
function inr() internal {}
fallback() external {
this.ext();
inr();
}
receive() external payable {
this.ext();
inr();
}
}
contract D {
fallback(bytes calldata) external returns (bytes memory) {}
function test() public {
(bool success, bytes memory result) = address(this).call("abc");
}
}
contract E is C {}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
{"E", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "function C.ext()"},
{"Entry", "receive of C"},
{"Entry", "fallback of C"},
{"fallback of C", "function C.inr()"},
{"receive of C", "function C.inr()"},
}},
{"D", {
{"Entry", "function D.test()"},
{"Entry", "fallback of D"},
}},
{"E", {
{"Entry", "function C.ext()"},
{"Entry", "fallback of C"},
{"Entry", "receive of C"},
{"fallback of C", "function C.inr()"},
{"receive of C", "function C.inr()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(virtual_fallback_and_receive)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
contract C {
fallback() external virtual {}
receive() external payable virtual {}
}
contract D is C {}
contract E is D {
fallback() external virtual override {}
receive() external payable virtual override {}
}
contract F is E {
fallback() external override {}
receive() external payable override {}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"C", {}},
{"D", {}},
{"E", {}},
{"F", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"C", {
{"Entry", "receive of C"},
{"Entry", "fallback of C"},
}},
{"D", {
{"Entry", "receive of C"},
{"Entry", "fallback of C"},
}},
{"E", {
{"Entry", "receive of E"},
{"Entry", "fallback of E"},
}},
{"F", {
{"Entry", "receive of F"},
{"Entry", "fallback of F"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(builtins)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
interface I {}
contract C {
function accessBuiltin() public payable {
abi.decode;
abi.encode;
abi.encodePacked;
abi.encodeWithSelector;
abi.encodeWithSignature;
block.basefee;
block.chainid;
block.coinbase;
block.difficulty;
block.prevrandao;
block.gaslimit;
block.number;
block.timestamp;
gasleft;
msg.data;
msg.sender;
msg.value;
tx.gasprice;
tx.origin;
blockhash;
keccak256;
sha256;
ripemd160;
ecrecover;
addmod;
mulmod;
this;
super;
selfdestruct;
address(0).balance;
address(0).code;
address(0).codehash;
payable(0).send;
payable(0).transfer;
address(0).call;
address(0).delegatecall;
address(0).staticcall;
type(C).name;
type(I).interfaceId;
type(uint).min;
type(uint).max;
assert;
}
function callBuiltin() public payable {
bytes memory data;
abi.decode(data, (uint));
abi.encode(0);
abi.encodePacked(data);
abi.encodeWithSelector(0x12345678);
abi.encodeWithSignature("abc");
gasleft();
blockhash(0);
keccak256(data);
sha256(data);
ripemd160(data);
ecrecover(0x0, 0, 0, 0);
addmod(1, 2, 3);
mulmod(1, 2, 3);
selfdestruct(payable(0));
payable(0).send(0);
payable(0).transfer(0);
address(0).call(data);
address(0).delegatecall(data);
address(0).staticcall(data);
assert(true);
require(true);
revert();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"I", {}},
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"I", {}},
{"C", {
{"Entry", "function C.accessBuiltin()"},
{"Entry", "function C.callBuiltin()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(conversions_and_struct_array_constructors)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
interface I {}
enum E {A, B, C}
struct S {
uint a;
E b;
}
contract C is I {
uint[] u;
function convert() public payable {
uint(0);
int(0);
bool(true);
bytes16(0);
payable(address(0));
E(0);
C(address(C(address(0))));
I(C(address(0)));
bytes memory b;
string(b);
bytes(b);
}
function create() public payable {
S(1, E.A);
uint[3] memory u3;
uint[3](u3);
uint[](new uint[](3));
}
function pushPop() public payable {
u.push();
u.push(1);
u.pop();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"I", {}},
{"C", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"I", {}},
{"C", {
{"Entry", "function C.convert()"},
{"Entry", "function C.create()"},
{"Entry", "function C.pushPop()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(immutable_initialization)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() pure returns (uint) { return 42; }
contract Base {
function ext() external pure returns (uint) { free(); }
function inr() internal pure returns (uint) { free(); }
}
contract C is Base {
uint immutable extImmutable = this.ext();
uint immutable inrImmutable = inr();
}
contract D is Base {
uint immutable extImmutable;
uint immutable inrImmutable;
constructor () {
extImmutable = this.ext();
inrImmutable = inr();
}
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"Base", {}},
{"C", {
{"Entry", "function Base.inr()"},
{"function Base.inr()", "function free()"},
}},
{"D", {
{"Entry", "constructor of D"},
{"constructor of D", "function Base.inr()"},
{"function Base.inr()", "function free()"},
}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"Base", {
{"Entry", "function Base.ext()"},
{"function Base.ext()", "function free()"},
}},
{"C", {
{"Entry", "function Base.ext()"},
{"function Base.ext()", "function free()"},
}},
{"D", {
{"Entry", "function Base.ext()"},
{"function Base.ext()", "function free()"},
}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_CASE(function_selector_access)
{
std::unique_ptr<CompilerStack> compilerStack = parseAndAnalyzeContracts(R"(
function free() pure {}
bytes4 constant extFreeConst = Base.ext.selector;
bytes4 constant pubFreeConst = Base.pub.selector;
contract Base {
function ext() external pure { free(); extFreeConst; }
function pub() public pure { free(); pubFreeConst; }
}
contract C is Base {
bytes4 constant extConst = Base.ext.selector;
bytes4 constant pubConst = Base.pub.selector;
}
contract D is Base {
bytes4 immutable extImmutable = Base.ext.selector;
bytes4 immutable pubImmutable = Base.pub.selector;
}
contract E is Base {
bytes4 extVar = Base.ext.selector;
bytes4 pubVar = Base.pub.selector;
}
contract F is Base {
function f() public pure returns (bytes4, bytes4) {
return (Base.ext.selector, Base.pub.selector);
}
}
library L {
bytes4 constant extConst = Base.ext.selector;
bytes4 constant pubConst = Base.pub.selector;
}
)"s);
std::tuple<CallGraphMap, CallGraphMap> graphs = collectGraphs(*compilerStack);
std::map<std::string, EdgeNames> expectedCreationEdges = {
{"Base", {}},
{"C", {}},
{"D", {
{"InternalDispatch", "function Base.pub()"},
{"function Base.pub()", "function free()"},
}},
{"E", {
{"InternalDispatch", "function Base.pub()"},
{"function Base.pub()", "function free()"},
}},
{"F", {}},
{"L", {}},
};
std::map<std::string, EdgeNames> expectedDeployedEdges = {
{"Base", {
{"Entry", "function Base.ext()"},
{"Entry", "function Base.pub()"},
{"function Base.ext()", "function free()"},
{"function Base.pub()", "function free()"},
}},
{"C", {
{"Entry", "function Base.ext()"},
{"Entry", "function Base.pub()"},
{"function Base.ext()", "function free()"},
{"function Base.pub()", "function free()"},
}},
{"D", {
{"InternalDispatch", "function Base.pub()"},
{"Entry", "function Base.ext()"},
{"Entry", "function Base.pub()"},
{"function Base.ext()", "function free()"},
{"function Base.pub()", "function free()"},
}},
{"E", {
{"InternalDispatch", "function Base.pub()"},
{"Entry", "function Base.ext()"},
{"Entry", "function Base.pub()"},
{"function Base.ext()", "function free()"},
{"function Base.pub()", "function free()"},
}},
{"F", {
{"InternalDispatch", "function Base.pub()"},
{"Entry", "function Base.ext()"},
{"Entry", "function Base.pub()"},
{"Entry", "function F.f()"},
{"function Base.ext()", "function free()"},
{"function Base.pub()", "function free()"},
}},
{"L", {}},
};
checkCallGraphExpectations(std::get<0>(graphs), expectedCreationEdges);
checkCallGraphExpectations(std::get<1>(graphs), expectedDeployedEdges);
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::frontend::test
| 62,361
|
C++
|
.cpp
| 1,922
| 29.083247
| 145
| 0.647507
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,011
|
FileReader.cpp
|
ethereum_solidity/test/libsolidity/interface/FileReader.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/// Unit tests for libsolidity/interface/FileReader.h
#include <libsolidity/interface/FileReader.h>
#include <test/Common.h>
#include <test/FilesystemUtils.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolutil/TemporaryDirectory.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
using namespace solidity::util;
using namespace solidity::test;
#define TEST_CASE_NAME (boost::unit_test::framework::current_test_case().p_name)
namespace solidity::frontend::test
{
using SymlinkResolution = FileReader::SymlinkResolution;
BOOST_AUTO_TEST_SUITE(FileReaderTest)
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_absolute_path)
{
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/.", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/./", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/./.", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a", resolveSymlinks), "/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/", resolveSymlinks), "/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/.", resolveSymlinks), "/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/./a", resolveSymlinks), "/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/./a/", resolveSymlinks), "/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/./a/.", resolveSymlinks), "/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b", resolveSymlinks), "/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b/", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/./b/", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/../a/b/", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b/c/..", resolveSymlinks), "/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b/c/../", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b/c/../../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b/c/../../../", resolveSymlinks), "/");
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_relative_path)
{
TemporaryDirectory tempDir({"x/y/z"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir.path() / "x/y/z");
// NOTE: If path to work dir contains symlinks (often the case on macOS), boost might resolve
// them, making the path different from tempDirPath.
boost::filesystem::path expectedPrefix = boost::filesystem::current_path().parent_path().parent_path().parent_path();
// On Windows tempDir.path() normally contains the drive letter while the normalized path should not.
expectedPrefix = "/" / expectedPrefix.relative_path();
soltestAssert(expectedPrefix.is_absolute() || expectedPrefix.root_path() == "/", "");
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS(".", resolveSymlinks), expectedPrefix / "x/y/z/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./", resolveSymlinks), expectedPrefix / "x/y/z/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS(".//", resolveSymlinks), expectedPrefix / "x/y/z/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("..", resolveSymlinks), expectedPrefix / "x/y");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../", resolveSymlinks), expectedPrefix / "x/y/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("..//", resolveSymlinks), expectedPrefix / "x/y/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a", resolveSymlinks), expectedPrefix / "x/y/z/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/.", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a", resolveSymlinks), expectedPrefix / "x/y/z/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/.", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/./", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/.//", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/./.", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/././", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/././/", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b", resolveSymlinks), expectedPrefix / "x/y/z/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/", resolveSymlinks), expectedPrefix / "x/y/z/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../a/b", resolveSymlinks), expectedPrefix / "x/y/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../../a/b", resolveSymlinks), expectedPrefix / "x/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("./a/b", resolveSymlinks), expectedPrefix / "x/y/z/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("././a/b", resolveSymlinks), expectedPrefix / "x/y/z/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/./b/", resolveSymlinks), expectedPrefix / "x/y/z/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/../a/b/", resolveSymlinks), expectedPrefix / "x/y/z/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/c/..", resolveSymlinks), expectedPrefix / "x/y/z/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/c/../", resolveSymlinks), expectedPrefix / "x/y/z/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/c/..//", resolveSymlinks), expectedPrefix / "x/y/z/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/c/../..", resolveSymlinks), expectedPrefix / "x/y/z/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/c/../../", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/b/c/../..//", resolveSymlinks), expectedPrefix / "x/y/z/a/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../../a/.././../p/../q/../a/b", resolveSymlinks), expectedPrefix / "a/b");
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_redundant_slashes)
{
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("///", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("////", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("////a/b/", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a//b/", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a////b/", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b//", resolveSymlinks), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/b////", resolveSymlinks), "/a/b/");
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_unc_path)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
// On Windows tempDir.path() normally contains the drive letter while the normalized path should not.
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
// UNC paths start with // or \\ followed by a name. They are used for network shares on Windows.
// On UNIX systems they are not supported but still treated in a special way.
// TODO: Re-enable these once the boost 1.86 change has been addressed
//BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("//host/", resolveSymlinks), "//host/");
//BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("//host/a/b", resolveSymlinks), "//host/a/b");
//BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("//host/a/b/", resolveSymlinks), "//host/a/b/");
#if defined(_WIN32)
// On Windows an UNC path can also start with \\ instead of //
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("\\\\host/", resolveSymlinks), "//host/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("\\\\host/a/b", resolveSymlinks), "//host/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("\\\\host/a/b/", resolveSymlinks), "//host/a/b/");
#else
// On UNIX systems it's just a fancy relative path instead
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("\\\\host/", resolveSymlinks), expectedWorkDir / "\\\\host/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("\\\\host/a/b", resolveSymlinks), expectedWorkDir / "\\\\host/a/b");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("\\\\host/a/b/", resolveSymlinks), expectedWorkDir / "\\\\host/a/b/");
#endif
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_root_name_only)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
// A root **path** consists of a directory name (typically / or \) and the root name (drive
// letter (C:), UNC host name (//host), etc.). Either can be empty. Root path as a whole may be
// an absolute path but root name on its own is considered relative. For example on Windows
// C:\ represents the root directory of drive C: but C: on its own refers to the current working
// directory.
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
// UNC paths
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("//", resolveSymlinks), "//" / expectedWorkDir);
// TODO: Re-enable these once the boost 1.86 change has been addressed
//BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("//host", resolveSymlinks), "//host" / expectedWorkDir);
// On UNIX systems root name is empty.
// TODO: Re-enable these once the boost 1.86 change has been addressed
//BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("", resolveSymlinks), expectedWorkDir);
#if defined(_WIN32)
boost::filesystem::path driveLetter = boost::filesystem::current_path().root_name();
soltestAssert(!driveLetter.empty(), "");
soltestAssert(driveLetter.is_relative(), "");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS(driveLetter, resolveSymlinks), expectedWorkDir);
#endif
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_stripping_root_name)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
soltestAssert(boost::filesystem::current_path().is_absolute(), "");
#if defined(_WIN32)
soltestAssert(!boost::filesystem::current_path().root_name().empty(), "");
#endif
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
boost::filesystem::path workDir = boost::filesystem::current_path();
boost::filesystem::path normalizedPath = FileReader::normalizeCLIPathForVFS(
workDir,
resolveSymlinks
);
BOOST_CHECK_EQUAL(normalizedPath, "/" / workDir.relative_path());
BOOST_TEST(normalizedPath.root_name().empty());
BOOST_CHECK_EQUAL(normalizedPath.root_directory(), "/");
#if defined(_WIN32)
std::string root = workDir.root_path().string();
soltestAssert(root.length() == 3 && root[1] == ':' && root[2] == '\\', "");
for (auto convert: {boost::to_lower_copy<std::string>, boost::to_upper_copy<std::string>})
{
boost::filesystem::path workDirWin = convert(root, std::locale()) / workDir.relative_path();
normalizedPath = FileReader::normalizeCLIPathForVFS(
workDirWin,
resolveSymlinks
);
BOOST_CHECK_EQUAL(normalizedPath, "/" / workDir.relative_path());
BOOST_TEST(normalizedPath.root_name().empty());
BOOST_CHECK_EQUAL(normalizedPath.root_directory(), "/");
}
#endif
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_path_beyond_root)
{
TemporaryWorkingDirectory tempWorkDir("/");
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../.", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../a", resolveSymlinks), "/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../a/..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../a/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../../a", resolveSymlinks), "/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../../a/..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/../../a/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("/a/../../b/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../.", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../a", resolveSymlinks), "/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../a/..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../a/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../../a", resolveSymlinks), "/a");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../../a/..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("../../a/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/../..", resolveSymlinks), "/");
BOOST_CHECK_EQUAL(FileReader::normalizeCLIPathForVFS("a/../../b/../..", resolveSymlinks), "/");
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_case_sensitivity)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
boost::filesystem::path workDirNoSymlinks = boost::filesystem::weakly_canonical(tempDir);
boost::filesystem::path expectedPrefix = "/" / workDirNoSymlinks.relative_path();
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
BOOST_TEST(FileReader::normalizeCLIPathForVFS(workDirNoSymlinks / "abc", resolveSymlinks) == expectedPrefix / "abc");
BOOST_TEST(FileReader::normalizeCLIPathForVFS(workDirNoSymlinks / "abc", resolveSymlinks) != expectedPrefix / "ABC");
BOOST_TEST(FileReader::normalizeCLIPathForVFS(workDirNoSymlinks / "ABC", resolveSymlinks) != expectedPrefix / "abc");
BOOST_TEST(FileReader::normalizeCLIPathForVFS(workDirNoSymlinks / "ABC", resolveSymlinks) == expectedPrefix / "ABC");
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_path_separators)
{
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
// Even on Windows we want / as a separator.
BOOST_TEST((
FileReader::normalizeCLIPathForVFS("/a/b/c", resolveSymlinks).native() ==
boost::filesystem::path("/a/b/c").native()
));
}
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_should_not_resolve_symlinks_unless_requested)
{
TemporaryDirectory tempDir({"abc/"}, TEST_CASE_NAME);
soltestAssert(tempDir.path().is_absolute(), "");
if (!createSymlinkIfSupportedByFilesystem(tempDir.path() / "abc", tempDir.path() / "sym", true))
return;
boost::filesystem::path expectedRootPath = FileReader::normalizeCLIRootPathForVFS(tempDir);
boost::filesystem::path expectedPrefixWithSymlinks = expectedRootPath / tempDir.path().relative_path();
boost::filesystem::path expectedPrefixWithoutSymlinks = expectedRootPath / boost::filesystem::weakly_canonical(tempDir).relative_path();
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "sym/contract.sol", SymlinkResolution::Disabled),
expectedPrefixWithSymlinks / "sym/contract.sol"
);
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "abc/contract.sol", SymlinkResolution::Disabled),
expectedPrefixWithSymlinks / "abc/contract.sol"
);
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "sym/contract.sol", SymlinkResolution::Enabled),
expectedPrefixWithoutSymlinks / "abc/contract.sol"
);
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "abc/contract.sol", SymlinkResolution::Enabled),
expectedPrefixWithoutSymlinks / "abc/contract.sol"
);
}
BOOST_AUTO_TEST_CASE(normalizeCLIPathForVFS_should_resolve_symlinks_in_workdir_when_path_is_relative)
{
TemporaryDirectory tempDir({"abc/"}, TEST_CASE_NAME);
soltestAssert(tempDir.path().is_absolute(), "");
if (!createSymlinkIfSupportedByFilesystem(tempDir.path() / "abc", tempDir.path() / "sym", true))
return;
TemporaryWorkingDirectory tempWorkDir(tempDir.path() / "sym");
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::weakly_canonical(boost::filesystem::current_path()).relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
boost::filesystem::path expectedPrefix = "/" / tempDir.path().relative_path();
soltestAssert(expectedPrefix.is_absolute() || expectedPrefix.root_path() == "/", "");
for (SymlinkResolution resolveSymlinks: {SymlinkResolution::Enabled, SymlinkResolution::Disabled})
{
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS("contract.sol", resolveSymlinks),
expectedWorkDir / "contract.sol"
);
}
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "sym/contract.sol", SymlinkResolution::Disabled),
expectedPrefix / "sym/contract.sol"
);
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "abc/contract.sol", SymlinkResolution::Disabled),
expectedPrefix / "abc/contract.sol"
);
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "sym/contract.sol", SymlinkResolution::Enabled),
expectedWorkDir / "contract.sol"
);
BOOST_CHECK_EQUAL(
FileReader::normalizeCLIPathForVFS(tempDir.path() / "abc/contract.sol", SymlinkResolution::Enabled),
expectedWorkDir / "contract.sol"
);
}
BOOST_AUTO_TEST_CASE(isPathPrefix_file_prefix)
{
BOOST_TEST(FileReader::isPathPrefix("/", "/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/contract.sol", "/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/contract.sol/", "/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/contract.sol/.", "/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a/", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a/bc", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a/bc/def/contract.sol", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a/", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a/bc", "/a/bc/def/contract.sol"));
BOOST_TEST(FileReader::isPathPrefix("/a/bc/def/contract.sol", "/a/bc/def/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/contract.sol", "/token.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/contract", "/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/contract.sol", "/contract"));
BOOST_TEST(!FileReader::isPathPrefix("/contract.so", "/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/contract.sol", "/contract.so"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/contract.sol", "/a/b/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/contract.sol", "/a/b/c/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/contract.sol", "/a/b/c/d/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/d/contract.sol", "/a/b/c/contract.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/contract.sol", "/contract.sol"));
}
BOOST_AUTO_TEST_CASE(isPathPrefix_directory_prefix)
{
BOOST_TEST(FileReader::isPathPrefix("/", "/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/", "/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c", "/"));
BOOST_TEST(FileReader::isPathPrefix("/", "/a/bc/"));
BOOST_TEST(FileReader::isPathPrefix("/a", "/a/bc/"));
BOOST_TEST(FileReader::isPathPrefix("/a/", "/a/bc/"));
BOOST_TEST(FileReader::isPathPrefix("/a/bc", "/a/bc/"));
BOOST_TEST(FileReader::isPathPrefix("/a/bc/", "/a/bc/"));
BOOST_TEST(!FileReader::isPathPrefix("/a", "/b/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/", "/b/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/contract.sol", "/a/b/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/", "/a/b/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c", "/a/b/"));
}
BOOST_AUTO_TEST_CASE(isPathPrefix_unc_path)
{
BOOST_TEST(FileReader::isPathPrefix("//host/a/b/", "//host/a/b/"));
BOOST_TEST(FileReader::isPathPrefix("//host/a/b", "//host/a/b/"));
BOOST_TEST(FileReader::isPathPrefix("//host/a/", "//host/a/b/"));
BOOST_TEST(FileReader::isPathPrefix("//host/a", "//host/a/b/"));
BOOST_TEST(FileReader::isPathPrefix("//host/", "//host/a/b/"));
// NOTE: //host and // cannot be passed to isPathPrefix() because they are considered relative.
BOOST_TEST(!FileReader::isPathPrefix("//host1/", "//host2/"));
BOOST_TEST(!FileReader::isPathPrefix("//host1/a/b/", "//host2/a/b/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/b/c/", "//a/b/c/"));
BOOST_TEST(!FileReader::isPathPrefix("//a/b/c/", "/a/b/c/"));
}
BOOST_AUTO_TEST_CASE(isPathPrefix_case_sensitivity)
{
BOOST_TEST(!FileReader::isPathPrefix("/a.sol", "/A.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/A.sol", "/a.sol"));
BOOST_TEST(!FileReader::isPathPrefix("/A/", "/a/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/", "/A/"));
BOOST_TEST(!FileReader::isPathPrefix("/a/BC/def/", "/a/bc/def/contract.sol"));
}
BOOST_AUTO_TEST_CASE(stripPrefixIfPresent_file_prefix)
{
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/", "/contract.sol"), "contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/contract.sol", "/contract.sol"), ".");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/contract.sol/", "/contract.sol"), ".");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/contract.sol/.", "/contract.sol"), ".");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/", "/a/bc/def/contract.sol"), "a/bc/def/contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a", "/a/bc/def/contract.sol"), "bc/def/contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/", "/a/bc/def/contract.sol"), "bc/def/contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/bc", "/a/bc/def/contract.sol"), "def/contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/bc/def/", "/a/bc/def/contract.sol"), "contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/bc/def/contract.sol", "/a/bc/def/contract.sol"), ".");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/contract.sol", "/token.sol"), "/token.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/contract", "/contract.sol"), "/contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/contract.sol", "/contract"), "/contract");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/b/c/contract.sol", "/a/b/contract.sol"), "/a/b/contract.sol");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/b/contract.sol", "/a/b/c/contract.sol"), "/a/b/c/contract.sol");
}
BOOST_AUTO_TEST_CASE(stripPrefixIfPresent_directory_prefix)
{
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/", "/"), ".");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/", "/a/bc/def/"), "a/bc/def/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a", "/a/bc/def/"), "bc/def/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/", "/a/bc/def/"), "bc/def/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/bc", "/a/bc/def/"), "def/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/bc/def/", "/a/bc/def/"), ".");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a", "/b/"), "/b/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/", "/b/"), "/b/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/b/c/", "/a/b/"), "/a/b/");
BOOST_CHECK_EQUAL(FileReader::stripPrefixIfPresent("/a/b/c", "/a/b/"), "/a/b/");
}
BOOST_AUTO_TEST_CASE(isUNCPath)
{
BOOST_TEST(FileReader::isUNCPath("//"));
BOOST_TEST(FileReader::isUNCPath("//root"));
BOOST_TEST(FileReader::isUNCPath("//root/"));
#if defined(_WIN32)
// On Windows boost sees these as ///, which is equivalent to /
BOOST_TEST(!FileReader::isUNCPath("//\\"));
BOOST_TEST(!FileReader::isUNCPath("\\\\/"));
BOOST_TEST(!FileReader::isUNCPath("\\/\\"));
BOOST_TEST(FileReader::isUNCPath("\\\\"));
BOOST_TEST(FileReader::isUNCPath("\\\\root"));
BOOST_TEST(FileReader::isUNCPath("\\\\root/"));
#else
// On UNIX it's actually an UNC path
BOOST_TEST(FileReader::isUNCPath("//\\"));
// On UNIX these are just weird relative directory names consisting only of backslashes.
BOOST_TEST(!FileReader::isUNCPath("\\\\/"));
BOOST_TEST(!FileReader::isUNCPath("\\/\\"));
BOOST_TEST(!FileReader::isUNCPath("\\\\"));
BOOST_TEST(!FileReader::isUNCPath("\\\\root"));
BOOST_TEST(!FileReader::isUNCPath("\\\\root/"));
#endif
BOOST_TEST(!FileReader::isUNCPath("\\/"));
BOOST_TEST(!FileReader::isUNCPath("/\\"));
BOOST_TEST(!FileReader::isUNCPath(""));
BOOST_TEST(!FileReader::isUNCPath("."));
BOOST_TEST(!FileReader::isUNCPath(".."));
BOOST_TEST(!FileReader::isUNCPath("/"));
BOOST_TEST(!FileReader::isUNCPath("a"));
BOOST_TEST(!FileReader::isUNCPath("a/b/c"));
BOOST_TEST(!FileReader::isUNCPath("contract.sol"));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::frontend::test
| 27,917
|
C++
|
.cpp
| 451
| 59.498891
| 137
| 0.731806
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,014
|
LEB128.cpp
|
ethereum_solidity/test/libsolutil/LEB128.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Unit tests for LEB128.
*/
#include <libsolutil/LEB128.h>
#include <boost/test/unit_test.hpp>
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(LEB128Test)
BOOST_AUTO_TEST_CASE(encode_unsigned)
{
bytes zero = solidity::util::lebEncode(0);
BOOST_REQUIRE(zero.size() == 1);
BOOST_REQUIRE(zero[0] == 0x00);
bytes one = solidity::util::lebEncode(1);
BOOST_REQUIRE(one.size() == 1);
BOOST_REQUIRE(one[0] == 0x01);
bytes large = solidity::util::lebEncode(624485);
BOOST_REQUIRE(large.size() == 3);
BOOST_REQUIRE(large[0] == 0xE5);
BOOST_REQUIRE(large[1] == 0x8E);
BOOST_REQUIRE(large[2] == 0x26);
bytes larger = solidity::util::lebEncodeSigned(123456123456);
BOOST_REQUIRE(larger.size() == 6);
BOOST_REQUIRE(larger[0] == 0xC0);
BOOST_REQUIRE(larger[1] == 0xE4);
BOOST_REQUIRE(larger[2] == 0xBB);
BOOST_REQUIRE(larger[3] == 0xF4);
BOOST_REQUIRE(larger[4] == 0xCB);
BOOST_REQUIRE(larger[5] == 0x03);
}
BOOST_AUTO_TEST_CASE(encode_signed)
{
bytes zero = solidity::util::lebEncodeSigned(0);
BOOST_REQUIRE(zero.size() == 1);
BOOST_REQUIRE(zero[0] == 0x00);
bytes one = solidity::util::lebEncodeSigned(1);
BOOST_REQUIRE(one.size() == 1);
BOOST_REQUIRE(one[0] == 0x01);
bytes negative_one = solidity::util::lebEncodeSigned(-1);
BOOST_REQUIRE(negative_one.size() == 1);
BOOST_REQUIRE(negative_one[0] == 0x7f);
bytes negative_two = solidity::util::lebEncodeSigned(-2);
BOOST_REQUIRE(negative_two.size() == 1);
BOOST_REQUIRE(negative_two[0] == 0x7e);
bytes large = solidity::util::lebEncodeSigned(624485);
BOOST_REQUIRE(large.size() == 3);
BOOST_REQUIRE(large[0] == 0xE5);
BOOST_REQUIRE(large[1] == 0x8E);
BOOST_REQUIRE(large[2] == 0x26);
bytes negative_large = solidity::util::lebEncodeSigned(-123456);
BOOST_REQUIRE(negative_large.size() == 3);
BOOST_REQUIRE(negative_large[0] == 0xC0);
BOOST_REQUIRE(negative_large[1] == 0xBB);
BOOST_REQUIRE(negative_large[2] == 0x78);
bytes negative_larger = solidity::util::lebEncodeSigned(-123456123456);
BOOST_REQUIRE(negative_larger.size() == 6);
BOOST_REQUIRE(negative_larger[0] == 0xC0);
BOOST_REQUIRE(negative_larger[1] == 0x9B);
BOOST_REQUIRE(negative_larger[2] == 0xC4);
BOOST_REQUIRE(negative_larger[3] == 0x8B);
BOOST_REQUIRE(negative_larger[4] == 0xB4);
BOOST_REQUIRE(negative_larger[5] == 0x7C);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 3,027
|
C++
|
.cpp
| 79
| 36.265823
| 72
| 0.731466
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,016
|
StringUtils.cpp
|
ethereum_solidity/test/libsolutil/StringUtils.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Unit tests for the StringUtils routines.
*/
#include <libsolutil/CommonData.h>
#include <libsolutil/FixedHash.h>
#include <libsolutil/StringUtils.h>
#include <libsolidity/ast/Types.h> // for IntegerType
#include <test/Common.h>
#include <boost/test/unit_test.hpp>
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(StringUtils, *boost::unit_test::label("nooptions"))
BOOST_AUTO_TEST_CASE(test_similarity)
{
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hello", 0), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hello", 1), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hellw", 1), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "helol", 1), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "helo", 1), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "helllo", 1), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hlllo", 1), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hllllo", 1), false);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hllllo", 2), true);
BOOST_CHECK_EQUAL(stringWithinDistance("hello", "hlllo", 2), true);
BOOST_CHECK_EQUAL(stringWithinDistance("a", "", 2), false);
BOOST_CHECK_EQUAL(stringWithinDistance("abc", "ba", 2), false);
BOOST_CHECK_EQUAL(stringWithinDistance("abc", "abcdef", 2), false);
BOOST_CHECK_EQUAL(stringWithinDistance("abcd", "wxyz", 2), false);
BOOST_CHECK_EQUAL(stringWithinDistance("", "", 2), true);
BOOST_CHECK_EQUAL(stringWithinDistance("YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY", "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZ", 2, 6400), false);
}
BOOST_AUTO_TEST_CASE(test_dldistance)
{
BOOST_CHECK_EQUAL(stringDistance("hello", "hellw"), 1);
BOOST_CHECK_EQUAL(stringDistance("hello", "helol"), 1);
BOOST_CHECK_EQUAL(stringDistance("hello", "helo"), 1);
BOOST_CHECK_EQUAL(stringDistance("hello", "helllo"), 1);
BOOST_CHECK_EQUAL(stringDistance("hello", "hlllo"), 1);
BOOST_CHECK_EQUAL(stringDistance("hello", "hllllo"), 2);
BOOST_CHECK_EQUAL(stringDistance("a", ""), 1);
BOOST_CHECK_EQUAL(stringDistance("abc", "ba"), 2);
BOOST_CHECK_EQUAL(stringDistance("abc", "abcdef"), 3);
BOOST_CHECK_EQUAL(stringDistance("abcd", "wxyz"), 4);
BOOST_CHECK_EQUAL(stringDistance("", ""), 0);
BOOST_CHECK_EQUAL(stringDistance("abcdefghijklmnopqrstuvwxyz", "abcabcabcabcabcabcabcabca"), 23);
}
BOOST_AUTO_TEST_CASE(test_alternatives_list)
{
std::vector<std::string> strings;
BOOST_CHECK_EQUAL(quotedAlternativesList(strings), "");
strings.emplace_back("a");
BOOST_CHECK_EQUAL(quotedAlternativesList(strings), "\"a\"");
strings.emplace_back("b");
BOOST_CHECK_EQUAL(quotedAlternativesList(strings), "\"a\" or \"b\"");
strings.emplace_back("c");
BOOST_CHECK_EQUAL(quotedAlternativesList(strings), "\"a\", \"b\" or \"c\"");
strings.emplace_back("d");
BOOST_CHECK_EQUAL(quotedAlternativesList(strings), "\"a\", \"b\", \"c\" or \"d\"");
}
BOOST_AUTO_TEST_CASE(test_human_readable_join)
{
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({})), "");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a"})), "a");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a", "b"})), "a, b");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a", "b", "c"})), "a, b, c");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({}), "; "), "");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a"}), "; "), "a");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a", "b"}), "; "), "a; b");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a", "b", "c"}), "; "), "a; b; c");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({}), "; ", " or "), "");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a"}), "; ", " or "), "a");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a", "b"}), "; ", " or "), "a or b");
BOOST_CHECK_EQUAL(joinHumanReadable(std::vector<std::string>({"a", "b", "c"}), "; ", " or "), "a; b or c");
}
BOOST_AUTO_TEST_CASE(test_format_number_readable)
{
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x10000000)), "2**28");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x100000000)), "2**32");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x8000000)), "2**27");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x80000000)), "2**31");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x800000000)), "2**35");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x8000000000)), "2**39");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x80000000000)), "2**43");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x7ffffff)), "2**27 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x7fffffff)), "2**31 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x7ffffffff)), "2**35 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x7fffffffff)), "2**39 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x7ffffffffff)), "2**43 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xfffffff)), "2**28 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xffffffff)), "2**32 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x88000000)), "0x88 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x8888888888000000)), "0x8888888888 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x100000000)), "2**32");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xFFFFffff)), "2**32 - 1");
u256 b = 0;
for (int i = 0; i < 32; i++)
{
b <<= 8;
b |= 0x55;
}
u256 c = (u256)FixedHash<32>(
fromHex("0xabcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789")
);
u256 d = u256(0xAAAAaaaaAAAAaaaa) << 192;
u256 e = u256(0xAAAAaaaaAAAAaaaa) << 192 |
u256(0xFFFFffffFFFFffff) << 128 |
u256(0xFFFFffffFFFFffff) << 64 |
u256(0xFFFFffffFFFFffff);
BOOST_CHECK_EQUAL(formatNumberReadable(b, true), "0x5555...{+56 more}...5555");
BOOST_CHECK_EQUAL(formatNumberReadable(c, true), "0xABCD...{+56 more}...6789");
BOOST_CHECK_EQUAL(formatNumberReadable(d, true), "0xAAAAaaaaAAAAaaaa * 2**192");
BOOST_CHECK_EQUAL(formatNumberReadable(e, true), "0xAAAAaaaaAAAAaaab * 2**192 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x20000000)), "2**29");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x200000000)), "2**33");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x2000000000)), "2**37");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x20000000000)), "2**41");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x200000000000)), "2**45");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x1FFFFFFF)), "2**29 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x1FFFFFFFF)), "2**33 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x1FFFFFFFFF)), "2**37 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x1FFFFFFFFFF)), "2**41 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x1FFFFFFFFFFF)), "2**45 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3000000)), "0x03 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x30000000)), "0x30 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x300000000)), "0x03 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3000000000)), "0x30 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x2FFFFFF)), "0x03 * 2**24 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x2FFFFFFF)), "0x30 * 2**24 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x2FFFFFFFF)), "0x03 * 2**32 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x2FFFFFFFFF)), "0x30 * 2**32 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA3000000)), "0xa3 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA30000000)), "0x0a30 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA300000000)), "0xa3 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA3000000000)), "0x0a30 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA2FFFFFF)), "0xa3 * 2**24 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA2FFFFFFF)), "0x0a30 * 2**24 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA2FFFFFFFF)), "0xa3 * 2**32 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xA2FFFFFFFFF)), "0x0a30 * 2**32 - 1");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 128, true), "0x03 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 129, true), "0x06 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 130, true), "0x0c * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 131, true), "0x18 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 248, true), "0x03 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 249, true), "0x06 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 250, true), "0x0c * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x3) << 251, true), "0x18 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 128, true), "0x09 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 129, true), "0x12 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 130, true), "0x24 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 131, true), "0x48 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 248, true), "0x09 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 249, true), "0x12 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 250, true), "0x24 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x9) << 251, true), "0x48 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0)), "0");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x10000)), "65536");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xFFFF)), "65535");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0x1000000)), "16777216");
BOOST_CHECK_EQUAL(formatNumberReadable(u256(0xFFFFFF)), "16777215");
//for codegen/ExpressionCompiler
BOOST_CHECK_EQUAL(formatNumberReadable(u256(-1)), "2**256 - 1");
// for formal/SMTChecker
BOOST_CHECK_EQUAL(
formatNumberReadable(frontend::IntegerType(256).minValue()), "0");
BOOST_CHECK_EQUAL(
formatNumberReadable(frontend::IntegerType(256).maxValue()), "2**256 - 1");
}
BOOST_AUTO_TEST_CASE(test_format_number_readable_signed)
{
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x10000000)), "-2**28");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x100000000)), "-2**32");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x8000000)), "-2**27");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x80000000)), "-2**31");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x800000000)), "-2**35");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x8000000000)), "-2**39");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x80000000000)), "-2**43");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x7ffffff)), "-2**27 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x7fffffff)), "-2**31 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x7ffffffff)), "-2**35 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x7fffffffff)), "-2**39 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x7ffffffffff)), "-2**43 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xfffffff)), "-2**28 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xffffffff)), "-2**32 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x88000000)), "-0x88 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x8888888888000000)), "-0x8888888888 * 2**24");
s256 b = 0;
for (int i = 0; i < 32; i++)
{
b <<= 8;
b |= 0x55;
}
b = b * (-1);
s256 c = (-1) * u2s((u256)FixedHash<32>(
fromHex("0x0bcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789")
));
s256 d = (-1) * u2s(
u256(0x5555555555555555) << 192 |
u256(0xFFFFffffFFFFffff) << 128 |
u256(0xFFFFffffFFFFffff) << 64 |
u256(0xFFFFffffFFFFffff)
);
BOOST_CHECK_EQUAL(formatNumberReadable(b, true), "-0x5555...{+56 more}...5555");
BOOST_CHECK_EQUAL(formatNumberReadable(c, true), "-0x0BCD...{+56 more}...6789");
BOOST_CHECK_EQUAL(formatNumberReadable(d, true), "-0x5555555555555556 * 2**192 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x20000000)), "-2**29");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x200000000)), "-2**33");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x2000000000)), "-2**37");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x20000000000)), "-2**41");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x200000000000)), "-2**45");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x1FFFFFFF)), "-2**29 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x1FFFFFFFF)), "-2**33 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x1FFFFFFFFF)), "-2**37 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x1FFFFFFFFFF)), "-2**41 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x1FFFFFFFFFFF)), "-2**45 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x3000000)), "-0x03 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x30000000)), "-0x30 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x300000000)), "-0x03 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x3000000000)), "-0x30 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x2FFFFFF)), "-0x03 * 2**24 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x2FFFFFFF)), "-0x30 * 2**24 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x2FFFFFFFF)), "-0x03 * 2**32 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x2FFFFFFFFF)), "-0x30 * 2**32 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA3000000)), "-0xa3 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA30000000)), "-0x0a30 * 2**24");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA300000000)), "-0xa3 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA3000000000)), "-0x0a30 * 2**32");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA2FFFFFF)), "-0xa3 * 2**24 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA2FFFFFFF)), "-0x0a30 * 2**24 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA2FFFFFFFF)), "-0xa3 * 2**32 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xA2FFFFFFFFF)), "-0x0a30 * 2**32 + 1");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 128, true), "-0x03 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 129, true), "-0x06 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 130, true), "-0x0c * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 131, true), "-0x18 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 248, true), "-0x03 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 249, true), "-0x06 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 250, true), "-0x0c * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x3)) << 251, true), "-0x18 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 128, true), "-0x09 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 129, true), "-0x12 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 130, true), "-0x24 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 131, true), "-0x48 * 2**128");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 248, true), "-0x09 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 249, true), "-0x12 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 250, true), "-0x24 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(((-1) * s256(0x9)) << 251, true), "-0x48 * 2**248");
BOOST_CHECK_EQUAL(formatNumberReadable(s256(-1)), "-1");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x10000)), "-65536");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xFFFF)), "-65535");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0x1000000)), "-16777216");
BOOST_CHECK_EQUAL(formatNumberReadable((-1) * s256(0xFFFFFF)), "-16777215");
BOOST_CHECK_EQUAL(
formatNumberReadable(
frontend::IntegerType(256, frontend::IntegerType::Modifier::Signed).minValue()
),
"-2**255"
);
BOOST_CHECK_EQUAL(
formatNumberReadable(
frontend::IntegerType(256, frontend::IntegerType::Modifier::Signed).maxValue()
),
"2**255 - 1"
);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 17,253
|
C++
|
.cpp
| 280
| 59.425
| 243
| 0.709868
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,017
|
TemporaryDirectoryTest.cpp
|
ethereum_solidity/test/libsolutil/TemporaryDirectoryTest.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolutil/TemporaryDirectory.h>
#include <libsolidity/util/SoltestErrors.h>
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <fstream>
using namespace boost::test_tools;
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(TemporaryDirectoryTest)
BOOST_AUTO_TEST_CASE(TemporaryDirectory_should_create_and_delete_a_unique_and_empty_directory)
{
boost::filesystem::path dirPath;
{
TemporaryDirectory tempDir("temporary-directory-test");
dirPath = tempDir.path();
BOOST_TEST(dirPath.stem().string().find("temporary-directory-test") == 0);
BOOST_TEST(boost::filesystem::equivalent(dirPath.parent_path(), boost::filesystem::temp_directory_path()));
BOOST_TEST(boost::filesystem::is_directory(dirPath));
BOOST_TEST(boost::filesystem::is_empty(dirPath));
}
BOOST_TEST(!boost::filesystem::exists(dirPath));
}
BOOST_AUTO_TEST_CASE(TemporaryDirectory_should_delete_its_directory_even_if_not_empty)
{
boost::filesystem::path dirPath;
{
TemporaryDirectory tempDir("temporary-directory-test");
dirPath = tempDir.path();
BOOST_TEST(boost::filesystem::is_directory(dirPath));
{
std::ofstream tmpFile((dirPath / "test-file.txt").string());
tmpFile << "Delete me!" << std::endl;
}
soltestAssert(boost::filesystem::is_regular_file(dirPath / "test-file.txt"), "");
}
BOOST_TEST(!boost::filesystem::exists(dirPath / "test-file.txt"));
}
BOOST_AUTO_TEST_CASE(TemporaryDirectory_should_create_subdirectories)
{
boost::filesystem::path dirPath;
{
TemporaryDirectory tempDir({"a", "a/", "a/b/c", "x.y/z"}, "temporary-directory-test");
dirPath = tempDir.path();
BOOST_TEST(boost::filesystem::is_directory(dirPath / "a"));
BOOST_TEST(boost::filesystem::is_directory(dirPath / "a/b/c"));
BOOST_TEST(boost::filesystem::is_directory(dirPath / "x.y/z"));
}
}
BOOST_AUTO_TEST_CASE(TemporaryWorkingDirectory_should_change_and_restore_working_directory)
{
boost::filesystem::path originalWorkingDirectory = boost::filesystem::current_path();
try
{
{
TemporaryDirectory tempDir("temporary-directory-test");
soltestAssert(boost::filesystem::equivalent(boost::filesystem::current_path(), originalWorkingDirectory), "");
soltestAssert(!boost::filesystem::equivalent(tempDir.path(), originalWorkingDirectory), "");
TemporaryWorkingDirectory tempWorkDir(tempDir.path());
BOOST_TEST(boost::filesystem::equivalent(boost::filesystem::current_path(), tempDir.path()));
}
BOOST_TEST(boost::filesystem::equivalent(boost::filesystem::current_path(), originalWorkingDirectory));
boost::filesystem::current_path(originalWorkingDirectory);
}
catch (...)
{
boost::filesystem::current_path(originalWorkingDirectory);
}
}
BOOST_AUTO_TEST_SUITE_END()
}
| 3,430
|
C++
|
.cpp
| 84
| 38.428571
| 113
| 0.7646
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,019
|
FunctionSelector.cpp
|
ethereum_solidity/test/libsolutil/FunctionSelector.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Unit tests for FunctionSelector.
*/
#include <libsolutil/FunctionSelector.h>
#include <boost/test/unit_test.hpp>
#include <cstdint>
#include <sstream>
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(FunctionSelectorTest)
BOOST_AUTO_TEST_CASE(conversions)
{
BOOST_CHECK_EQUAL(
util::selectorFromSignatureH32("test()"),
util::FixedHash<4>(0xf8a8fd6d)
);
BOOST_CHECK_EQUAL(
util::selectorFromSignatureU32("test()"),
0xf8a8fd6d
);
BOOST_CHECK_EQUAL(
util::selectorFromSignatureU256("test()"),
u256("0xf8a8fd6d00000000000000000000000000000000000000000000000000000000")
);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 1,290
|
C++
|
.cpp
| 40
| 30.175
| 76
| 0.788368
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,022
|
JSON.cpp
|
ethereum_solidity/test/libsolutil/JSON.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @date 2018
* Unit tests for JSON.h.
*/
#include <libsolutil/JSON.h>
#include <test/Common.h>
#include <boost/test/unit_test.hpp>
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(JsonTest, *boost::unit_test::label("nooptions"))
BOOST_AUTO_TEST_CASE(json_types)
{
auto check = [](Json value, std::string const& expectation) {
BOOST_CHECK(jsonCompactPrint(value) == expectation);
};
Json value;
BOOST_CHECK(value.empty());
value = {};
BOOST_CHECK(value.empty());
value = Json();
BOOST_CHECK(value.empty());
value = Json();
BOOST_CHECK(value.empty());
check(value, "null");
check({}, "null");
check(Json(), "null");
check(Json(), "null");
check(Json::object(), "{}");
check(Json::array(), "[]");
check(1, "1");
check(static_cast<uint32_t>(-1), "4294967295");
check(1, "1");
check(static_cast<uint64_t>(-1), "18446744073709551615");
check(1, "1");
check(static_cast<uint64_t>(-1), "18446744073709551615");
check(0xffffffff, "4294967295");
check(Json("test"), "\"test\"");
check("test", "\"test\"");
check(true, "true");
value = Json::object();
value["key"] = "value";
check(value, "{\"key\":\"value\"}");
value = Json::array();
value.push_back(1);
value.push_back(2);
check(value, "[1,2]");
}
BOOST_AUTO_TEST_CASE(json_pretty_print)
{
Json json;
Json jsonChild;
jsonChild["3.1"] = "3.1";
jsonChild["3.2"] = 2;
json["1"] = 1;
json["2"] = "2";
json["3"] = jsonChild;
json["4"] = "ऑ ऒ ओ औ क ख";
json["5"] = "\\xff\\xfe";
BOOST_CHECK(
"{\n"
" \"1\": 1,\n"
" \"2\": \"2\",\n"
" \"3\": {\n"
" \"3.1\": \"3.1\",\n"
" \"3.2\": 2\n"
" },\n"
" \"4\": \"\\u0911 \\u0912 \\u0913 \\u0914 \\u0915 \\u0916\",\n"
" \"5\": \"\\\\xff\\\\xfe\"\n"
"}" == jsonPrettyPrint(json));
}
BOOST_AUTO_TEST_CASE(json_compact_print)
{
Json json;
Json jsonChild;
jsonChild["3.1"] = "3.1";
jsonChild["3.2"] = 2;
json["1"] = 1;
json["2"] = "2";
json["3"] = jsonChild;
json["4"] = "ऑ ऒ ओ औ क ख";
json["5"] = "\x10";
json["6"] = "\u4e2d";
BOOST_CHECK(R"({"1":1,"2":"2","3":{"3.1":"3.1","3.2":2},"4":"\u0911 \u0912 \u0913 \u0914 \u0915 \u0916","5":"\u0010","6":"\u4e2d"})" == jsonCompactPrint(json));
}
BOOST_AUTO_TEST_CASE(parse_json_strict)
{
// In this test we check conformance against JSON.parse (https://tc39.es/ecma262/multipage/structured-data.html#sec-json.parse)
// and ECMA-404 (https://www.ecma-international.org/publications-and-standards/standards/ecma-404/)
Json json;
std::string errors;
// Just parse a valid json input
BOOST_CHECK(jsonParseStrict("{\"1\":1,\"2\":\"2\",\"3\":{\"3.1\":\"3.1\",\"3.2\":2}}", json, &errors));
BOOST_CHECK(json["1"] == 1);
BOOST_CHECK(json["2"] == "2");
BOOST_CHECK(json["3"]["3.1"] == "3.1");
BOOST_CHECK(json["3"]["3.2"] == 2);
// Trailing garbage is not allowed in ECMA-262
BOOST_CHECK(!jsonParseStrict("{\"1\":2,\"2\":\"2\",\"3\":{\"3.1\":\"3.1\",\"3.2\":3}}}}}}}}}}", json, &errors));
// According to ECMA-404 object, array, number, string, true, false, null are allowed
// ... but JSONCPP disallows value types
BOOST_CHECK(jsonParseStrict("[]", json, &errors));
BOOST_CHECK(json.is_array());
BOOST_CHECK(jsonParseStrict("{}", json, &errors));
BOOST_CHECK(json.is_object());
BOOST_CHECK(jsonParseStrict("1", json, &errors));
BOOST_CHECK(json.is_number());
BOOST_CHECK(jsonParseStrict("\"hello\"", json, &errors));
BOOST_CHECK(json.is_string());
BOOST_CHECK(jsonParseStrict("true", json, &errors));
BOOST_CHECK(json.is_boolean());
BOOST_CHECK(jsonParseStrict("null", json, &errors));
BOOST_CHECK(json.is_null());
// Single quotes are also disallowed by ECMA-404
BOOST_CHECK(!jsonParseStrict("'hello'", json, &errors));
// BOOST_CHECK(json.is_string());
// Only string keys in objects are allowed in ECMA-404
BOOST_CHECK(!jsonParseStrict("{ 42: \"hello\" }", json, &errors));
// According to ECMA-404 hex escape sequences are not allowed, only unicode (\uNNNN) and
// a few control characters (\b, \f, \n, \r, \t)
BOOST_CHECK(jsonParseStrict("[ \"\xF0\x9F\x98\x8A\" ]", json, &errors));
BOOST_CHECK(json.is_array());
BOOST_CHECK(json[0] == "😊");
BOOST_CHECK(json[0] == "\xF0\x9F\x98\x8A");
}
BOOST_AUTO_TEST_CASE(json_isOfType)
{
Json json;
json["float"] = 3.1f;
json["double"] = 3.1;
json["int"] = 2;
json["int64"] = 0x4000000000000000;
json["string"] = "Hello World!";
BOOST_CHECK(isOfType<float>(json["float"]));
BOOST_CHECK(isOfType<double>(json["double"]));
BOOST_CHECK(isOfType<int>(json["int"]));
BOOST_CHECK(isOfType<int>(json["int"]));
BOOST_CHECK(isOfType<uint64_t>(json["int"]));
BOOST_CHECK(isOfType<uint64_t>(json["int"]));
BOOST_CHECK(isOfType<int>(json["int"]));
BOOST_CHECK(isOfType<int64_t>(json["int64"]));
BOOST_CHECK(isOfType<uint64_t>(json["int64"]));
BOOST_CHECK(isOfType<uint64_t >(json["int64"]));
BOOST_CHECK(isOfType<std::string>(json["string"]));
BOOST_CHECK(!isOfType<int>(json["int64"]));
BOOST_CHECK(!isOfType<int>(json["double"]));
BOOST_CHECK(!isOfType<float>(json["string"]));
BOOST_CHECK(!isOfType<double>(json["string"]));
BOOST_CHECK(!isOfType<int>(json["string"]));
BOOST_CHECK(!isOfType<int64_t>(json["string"]));
BOOST_CHECK(!isOfType<unsigned >(json["string"]));
BOOST_CHECK(!isOfType<uint64_t >(json["string"]));
}
BOOST_AUTO_TEST_CASE(json_isisOfTypeIfExists)
{
Json json;
json["float"] = 3.1f;
json["double"] = 3.1;
json["int"] = 2;
json["uint"] = 2u;
json["int64"] = 0x4000000000000000;
json["uint64"] = 0x4000000000000000u;
json["string"] = "Hello World!";
BOOST_CHECK(isOfTypeIfExists<float>(json, "float"));
BOOST_CHECK(isOfTypeIfExists<double>(json, "double"));
BOOST_CHECK(isOfTypeIfExists<int>(json, "int"));
BOOST_CHECK(isOfTypeIfExists<int>(json, "int"));
BOOST_CHECK(isOfTypeIfExists<unsigned>(json, "uint"));
BOOST_CHECK(isOfTypeIfExists<int64_t>(json, "int"));
BOOST_CHECK(isOfTypeIfExists<int64_t >(json, "int64"));
BOOST_CHECK(isOfTypeIfExists<uint64_t>(json, "uint64"));
BOOST_CHECK(isOfTypeIfExists<std::string>(json, "string"));
BOOST_CHECK(!isOfTypeIfExists<int>(json, "int64"));
BOOST_CHECK(!isOfTypeIfExists<int>(json, "double"));
BOOST_CHECK(!isOfTypeIfExists<float>(json, "string"));
BOOST_CHECK(!isOfTypeIfExists<double>(json, "string"));
BOOST_CHECK(!isOfTypeIfExists<int>(json, "string"));
BOOST_CHECK(!isOfTypeIfExists<int64_t>(json, "string"));
BOOST_CHECK(!isOfTypeIfExists<unsigned>(json, "string"));
BOOST_CHECK(!isOfTypeIfExists<uint64_t>(json, "string"));
BOOST_CHECK(isOfTypeIfExists<uint64_t>(json, "NOT_EXISTING"));
}
BOOST_AUTO_TEST_CASE(json_getOrDefault)
{
Json json;
json["float"] = 3.1f;
json["double"] = 3.1;
json["int"] = 2;
json["int64"] = 0x4000000000000000;
json["uint64"] = 0x5000000000000000;
json["string"] = "Hello World!";
BOOST_CHECK(getOrDefault<float>(json, "float") == 3.1f);
BOOST_CHECK(getOrDefault<float>(json, "float", -1.1f) == 3.1f);
BOOST_CHECK(getOrDefault<float>(json, "no_float", -1.1f) == -1.1f);
BOOST_CHECK(getOrDefault<double>(json, "double") == 3.1);
BOOST_CHECK(getOrDefault<double>(json, "double", -1) == 3.1);
BOOST_CHECK(getOrDefault<double>(json, "no_double", -1.1) == -1.1);
BOOST_CHECK(getOrDefault<int>(json, "int") == 2);
BOOST_CHECK(getOrDefault<int>(json, "int", -1) == 2);
BOOST_CHECK(getOrDefault<int>(json, "no_int", -1) == -1);
BOOST_CHECK(getOrDefault<int>(json, "int") == 2);
BOOST_CHECK(getOrDefault<int>(json, "int", -1) == 2);
BOOST_CHECK(getOrDefault<int>(json, "no_int", -1) == -1);
BOOST_CHECK(getOrDefault<unsigned>(json, "int") == 2);
BOOST_CHECK(getOrDefault<unsigned>(json, "int", 1) == 2);
BOOST_CHECK(getOrDefault<unsigned>(json, "no_int", 1) == 1);
BOOST_CHECK(getOrDefault<int64_t>(json, "int") == 2);
BOOST_CHECK(getOrDefault<int64_t>(json, "int", -1) == 2);
BOOST_CHECK(getOrDefault<int64_t>(json, "no_int", -1) == -1);
BOOST_CHECK(getOrDefault<int64_t>(json, "int64") == 0x4000000000000000);
BOOST_CHECK(getOrDefault<int64_t>(json, "int64", -1) == 0x4000000000000000);
BOOST_CHECK(getOrDefault<int64_t>(json, "no_int64", -1) == -1);
BOOST_CHECK(getOrDefault<uint64_t>(json, "int64") == 0x4000000000000000);
BOOST_CHECK(getOrDefault<uint64_t>(json, "int64", 1) == 0x4000000000000000);
BOOST_CHECK(getOrDefault<uint64_t>(json, "no_int64", 1) == 1);
BOOST_CHECK(getOrDefault<uint64_t>(json, "uint64") == 0x5000000000000000);
BOOST_CHECK(getOrDefault<uint64_t>(json, "uint64", 1) == 0x5000000000000000);
BOOST_CHECK(getOrDefault<uint64_t>(json, "no_uint64", 1) == 1);
BOOST_CHECK(getOrDefault<std::string>(json, "string", "ERROR") == "Hello World!");
BOOST_CHECK(getOrDefault<std::string>(json, "no_string").empty());
BOOST_CHECK(getOrDefault<std::string>(json, "no_string", "ERROR") == "ERROR");
}
BOOST_AUTO_TEST_CASE(json_get)
{
Json json;
json["float"] = 3.1f;
json["double"] = 3.1;
json["int"] = 2;
json["int64"] = 0x4000000000000000;
json["uint64"] = 0x5000000000000000;
json["string"] = "Hello World!";
BOOST_CHECK(get<float>(json["float"]) == 3.1f);
BOOST_CHECK(get<double>(json["double"]) == 3.1);
BOOST_CHECK(get<int>(json["int"]) == 2);
BOOST_CHECK(get<int>(json["int"]) == 2);
BOOST_CHECK(get<unsigned>(json["int"]) == 2);
BOOST_CHECK(get<int64_t>(json["int"]) == 2);
BOOST_CHECK(get<int64_t>(json["int64"]) == 0x4000000000000000);
BOOST_CHECK(get<uint64_t>(json["int64"]) == 0x4000000000000000);
BOOST_CHECK(get<uint64_t>(json["uint64"]) == 0x5000000000000000);
BOOST_CHECK(get<std::string>(json["string"]) == "Hello World!");
}
template<typename T>
void json_test_int_range()
{
Json max = {{"v", std::numeric_limits<T>::max()}};
Json min = {{"v", std::numeric_limits<T>::min()}};
Json overflow = {{"v", static_cast<int64_t>(std::numeric_limits<T>::max()) + 1}};
Json underflow = {{"v", static_cast<int64_t>(std::numeric_limits<T>::min()) - 1}};
BOOST_CHECK(getOrDefault<T>(max, "v", 0) == std::numeric_limits<T>::max());
BOOST_CHECK(getOrDefault<T>(min, "v", 0) == std::numeric_limits<T>::min());
BOOST_CHECK(getOrDefault<T>(overflow, "v", 0) == 0);
BOOST_CHECK(getOrDefault<T>(underflow, "v", 0) == 0);
BOOST_CHECK(get<T>(max["v"]) == std::numeric_limits<T>::max());
BOOST_CHECK(get<T>(min["v"]) == std::numeric_limits<T>::min());
BOOST_CHECK_THROW(get<T>(overflow["v"]), InvalidType);
BOOST_CHECK_THROW(get<T>(underflow["v"]), InvalidType);
}
BOOST_AUTO_TEST_CASE(json_range_checks)
{
json_test_int_range<int32_t>();
json_test_int_range<uint32_t>();
json_test_int_range<int16_t>();
json_test_int_range<uint16_t>();
json_test_int_range<int8_t>();
json_test_int_range<uint8_t>();
Json overflow = {{"v", static_cast<double>(std::numeric_limits<float>::max()) * 2}};
Json underflow = {{"v", static_cast<double>(std::numeric_limits<float>::min()) / 2}};
BOOST_CHECK(getOrDefault<float>({{"v", std::numeric_limits<float>::max()}}, "v", 0) == std::numeric_limits<float>::max());
BOOST_CHECK(getOrDefault<float>({{"v", std::numeric_limits<float>::min()}}, "v", 0) == std::numeric_limits<float>::min());
BOOST_CHECK(getOrDefault<float>(overflow, "v", 0) == 0);
BOOST_CHECK(getOrDefault<float>(underflow, "v", 0) == 0);
BOOST_CHECK_THROW(get<float>(overflow["v"]), InvalidType);
BOOST_CHECK_THROW(get<float>(underflow["v"]), InvalidType);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 11,943
|
C++
|
.cpp
| 290
| 39.168966
| 161
| 0.667184
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,023
|
IterateReplacing.cpp
|
ethereum_solidity/test/libsolutil/IterateReplacing.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Unit tests for the iterateReplacing function
*/
#include <libsolutil/CommonData.h>
#include <test/Common.h>
#include <boost/test/unit_test.hpp>
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(IterateReplacing, *boost::unit_test::label("nooptions"))
BOOST_AUTO_TEST_CASE(no_replacement)
{
std::vector<std::string> v{"abc", "def", "ghi"};
std::function<std::optional<std::vector<std::string>>(std::string&)> f = [](std::string&) -> std::optional<std::vector<std::string>> { return {}; };
iterateReplacing(v, f);
std::vector<std::string> expectation{"abc", "def", "ghi"};
BOOST_CHECK(v == expectation);
}
BOOST_AUTO_TEST_CASE(empty_input)
{
std::vector<std::string> v;
std::function<std::optional<std::vector<std::string>>(std::string&)> f = [](std::string&) -> std::optional<std::vector<std::string>> { return {}; };
iterateReplacing(v, f);
std::vector<std::string> expectation;
BOOST_CHECK(v == expectation);
}
BOOST_AUTO_TEST_CASE(delete_some)
{
std::vector<std::string> v{"abc", "def", "ghi"};
std::function<std::optional<std::vector<std::string>>(std::string&)> f = [](std::string& _s) -> std::optional<std::vector<std::string>> {
if (_s == "def")
return std::vector<std::string>();
else
return {};
};
iterateReplacing(v, f);
std::vector<std::string> expectation{"abc", "ghi"};
BOOST_CHECK(v == expectation);
}
BOOST_AUTO_TEST_CASE(inject_some_start)
{
std::vector<std::string> v{"abc", "def", "ghi"};
std::function<std::optional<std::vector<std::string>>(std::string&)> f = [](std::string& _s) -> std::optional<std::vector<std::string>> {
if (_s == "abc")
return std::vector<std::string>{"x", "y"};
else
return {};
};
iterateReplacing(v, f);
std::vector<std::string> expectation{"x", "y", "def", "ghi"};
BOOST_CHECK(v == expectation);
}
BOOST_AUTO_TEST_CASE(inject_some_end)
{
std::vector<std::string> v{"abc", "def", "ghi"};
std::function<std::optional<std::vector<std::string>>(std::string&)> f = [](std::string& _s) -> std::optional<std::vector<std::string>> {
if (_s == "ghi")
return std::vector<std::string>{"x", "y"};
else
return {};
};
iterateReplacing(v, f);
std::vector<std::string> expectation{"abc", "def", "x", "y"};
BOOST_CHECK(v == expectation);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 2,966
|
C++
|
.cpp
| 80
| 34.9875
| 149
| 0.689199
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,027
|
DisjointSet.cpp
|
ethereum_solidity/test/libsolutil/DisjointSet.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Unit tests for DisjointSet.
*/
#include <libsolutil/DisjointSet.h>
#include <boost/test/unit_test.hpp>
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(DisjointSetTest)
BOOST_AUTO_TEST_CASE(full_union)
{
ContiguousDisjointSet ds(10);
for (size_t i = 1; i < 10; ++i)
{
BOOST_CHECK(!ds.sameSubset(0, i));
ds.merge(0, i);
BOOST_CHECK(ds.sameSubset(0, i));
}
BOOST_CHECK_EQUAL(ds.numSets(), 1);
auto const& subsets = ds.subsets();
BOOST_CHECK_EQUAL(subsets.size(), 1);
std::set<size_t> fullSet{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
BOOST_CHECK_EQUAL_COLLECTIONS(subsets[0].begin(), subsets[0].end(), fullSet.begin(), fullSet.end());
for (size_t i = 1; i < 10; ++i) BOOST_CHECK_EQUAL(ds.find(0), ds.find(i));
}
BOOST_AUTO_TEST_CASE(pairs)
{
ContiguousDisjointSet ds(10);
BOOST_CHECK_EQUAL(ds.numSets(), 10);
BOOST_CHECK_EQUAL(ds.subsets().size(), 10);
auto const checkPair = [&](size_t expectedNumSubsets, size_t x, size_t y)
{
BOOST_CHECK_EQUAL(ds.numSets(), expectedNumSubsets);
BOOST_CHECK_EQUAL(ds.subsets().size(), expectedNumSubsets);
BOOST_CHECK(ds.sameSubset(x, y));
auto const subset = ds.subset(x);
std::set<size_t> subsetRef{x, y};
BOOST_CHECK_EQUAL_COLLECTIONS(subset.begin(), subset.end(), subsetRef.begin(), subsetRef.end());
};
ds.merge(5, 3);
checkPair(9, 5, 3);
ds.merge(1, 6);
checkPair(8, 1, 6);
ds.merge(0, 2);
checkPair(7, 0, 2);
ds.merge(1, 5);
BOOST_CHECK_EQUAL(ds.sizeOfSubset(3), 4);
ds.merge(1, 0);
// now we should have a subset with {0, 1, 2, 3, 5, 6}
std::set<size_t> subsetRef{0, 1, 2, 3, 5, 6};
BOOST_CHECK_EQUAL(ds.sizeOfSubset(6), subsetRef.size());
auto const subset = ds.subset(2);
BOOST_CHECK_EQUAL_COLLECTIONS(subset.begin(), subset.end(), subsetRef.begin(), subsetRef.end());
}
BOOST_AUTO_TEST_CASE(merge_with_fixed_representative)
{
ContiguousDisjointSet ds(10);
ds.merge(5, 3, false);
BOOST_CHECK_EQUAL(ds.find(5), 5);
ds.merge(1, 2);
ds.merge(7, 8);
ds.merge(0, 9);
ds.merge(5, 1, false);
BOOST_CHECK_EQUAL(ds.find(5), 5);
ds.merge(5, 0, false);
BOOST_CHECK_EQUAL(ds.find(5), 5);
ds.merge(5, 7, false);
BOOST_CHECK_EQUAL(ds.find(5), 5);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 2,838
|
C++
|
.cpp
| 83
| 32.072289
| 101
| 0.709689
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,029
|
CommonIO.cpp
|
ethereum_solidity/test/libsolutil/CommonIO.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/// Unit tests for the CommonIO routines.
#include <libsolutil/CommonIO.h>
#include <libsolutil/TemporaryDirectory.h>
#include <test/Common.h>
#include <test/FilesystemUtils.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <string>
using namespace solidity::test;
#define TEST_CASE_NAME (boost::unit_test::framework::current_test_case().p_name)
namespace solidity::util::test
{
BOOST_AUTO_TEST_SUITE(CommonIOTest)
BOOST_AUTO_TEST_CASE(readFileAsString_regular_file)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
createFileWithContent(tempDir.path() / "test.txt", "ABC\ndef\n");
BOOST_TEST(readFileAsString(tempDir.path() / "test.txt") == "ABC\ndef\n");
}
BOOST_AUTO_TEST_CASE(readFileAsString_directory)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
BOOST_CHECK_THROW(readFileAsString(tempDir), NotAFile);
}
BOOST_AUTO_TEST_CASE(readFileAsString_symlink)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
createFileWithContent(tempDir.path() / "test.txt", "ABC\ndef\n");
if (!createSymlinkIfSupportedByFilesystem("test.txt", tempDir.path() / "symlink.txt", false))
return;
BOOST_TEST(readFileAsString(tempDir.path() / "symlink.txt") == "ABC\ndef\n");
}
BOOST_AUTO_TEST_CASE(readUntilEnd_no_ending_newline)
{
std::istringstream inputStream("ABC\ndef");
BOOST_TEST(readUntilEnd(inputStream) == "ABC\ndef");
}
BOOST_AUTO_TEST_CASE(readUntilEnd_with_ending_newline)
{
std::istringstream inputStream("ABC\ndef\n");
BOOST_TEST(readUntilEnd(inputStream) == "ABC\ndef\n");
}
BOOST_AUTO_TEST_CASE(readUntilEnd_cr_lf_newline)
{
std::istringstream inputStream("ABC\r\ndef");
BOOST_TEST(readUntilEnd(inputStream) == "ABC\r\ndef");
}
BOOST_AUTO_TEST_CASE(readUntilEnd_empty)
{
std::istringstream inputStream("");
BOOST_TEST(readUntilEnd(inputStream) == "");
}
BOOST_AUTO_TEST_CASE(readBytes_past_end)
{
std::istringstream inputStream("abc");
BOOST_CHECK_EQUAL(readBytes(inputStream, 0), "");
BOOST_CHECK_EQUAL(readBytes(inputStream, 1), "a");
BOOST_CHECK_EQUAL(readBytes(inputStream, 20), "bc");
BOOST_CHECK_EQUAL(readBytes(inputStream, 20), "");
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::util::test
| 2,926
|
C++
|
.cpp
| 78
| 35.74359
| 94
| 0.775062
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,030
|
DominatorFinderTest.cpp
|
ethereum_solidity/test/libsolutil/DominatorFinderTest.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Unit tests for the algorithm to find dominators from a graph.
*/
#include <libsolutil/DominatorFinder.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <boost/test/unit_test.hpp>
#include <fmt/format.h>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/join.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/transform.hpp>
using namespace solidity::util;
namespace solidity::util::test
{
typedef size_t TestVertexId;
typedef std::string TestVertexLabel;
typedef std::pair<TestVertexLabel, TestVertexLabel> Edge;
struct TestVertex {
using Id = TestVertexId;
TestVertexId id;
TestVertexLabel label;
std::vector<TestVertex const*> successors;
};
struct ForEachVertexSuccessorMock {
template<typename Callable>
void operator()(TestVertex const& _v, Callable&& _callable) const
{
for (auto const& w: _v.successors)
_callable(*w);
}
};
typedef DominatorFinder<TestVertex, ForEachVertexSuccessorMock> TestDominatorFinder;
class DominatorFinderTest
{
public:
DominatorFinderTest(
std::vector<TestVertexLabel> const& _vertices,
std::vector<Edge> const& _edges,
std::map<TestVertexLabel, TestVertexLabel> const& _expectedImmediateDominators,
std::map<TestVertexLabel, TestDominatorFinder::DfsIndex> const& _expectedDFSIndices,
std::map<TestVertexLabel, std::vector<TestVertexLabel>> const& _expectedDominatorTree
)
{
soltestAssert(!_vertices.empty());
// NOTE: We use the indices of the vertices in the ``_vertices`` vector as vertex IDs.
TestVertexId id = 0;
vertices = _vertices | ranges::views::transform([&](TestVertexLabel const& label) -> TestVertex {
vertexIdMap[label] = id;
return {id++, label, {}};
}) | ranges::to<std::vector<TestVertex>>;
soltestAssert(vertices.size() == _vertices.size());
soltestAssert(vertexIdMap.size() == _vertices.size());
soltestAssert(id == _vertices.size());
// Populate the successors of the vertices.
for (auto const& [from, to]: _edges)
vertices[vertexIdMap[from]].successors.emplace_back(&vertices[vertexIdMap[to]]);
// Validate that all vertices used in the expected results are part of the graph.
std::set<TestVertexLabel> verticesSet = _vertices | ranges::to<std::set<TestVertexLabel>>;
auto validateVertices = [&](std::set<TestVertexLabel> const& labels) {
if (verticesSet.size() != labels.size())
soltestAssert(std::includes(verticesSet.begin(), verticesSet.end(), labels.begin(), labels.end()));
else
soltestAssert(std::equal(verticesSet.begin(), verticesSet.end(), labels.begin(), labels.end()));
};
validateVertices(_edges
| ranges::views::transform([](Edge const& e) { return e.first; })
| ranges::to<std::set<TestVertexLabel>>
);
validateVertices(_edges
| ranges::views::transform([](Edge const& e) { return e.second; })
| ranges::to<std::set<TestVertexLabel>>
);
validateVertices(_expectedImmediateDominators | ranges::views::keys | ranges::to<std::set<TestVertexLabel>>);
// The entry vertex does not have an immediate dominator.
validateVertices(_expectedImmediateDominators
| ranges::views::values
| ranges::views::filter([](TestVertexLabel const& label) { return !label.empty(); })
| ranges::to<std::set<TestVertexLabel>>
);
validateVertices(_expectedDFSIndices | ranges::views::keys | ranges::to<std::set<TestVertexLabel>>);
bool allDFSIndexInRange = std::all_of(
_expectedDFSIndices.begin(),
_expectedDFSIndices.end(),
[&](auto const& pair) {
return pair.second < verticesSet.size();
}
);
solAssert(allDFSIndexInRange);
validateVertices(_expectedDominatorTree | ranges::views::keys | ranges::to<std::set<TestVertexLabel>>);
validateVertices(_expectedDominatorTree | ranges::views::values | ranges::views::join | ranges::to<std::set<TestVertexLabel>>);
entry = &vertices[0];
expectedImmediateDominators = labelMapToIdMap(_expectedImmediateDominators);
expectedDFSIndices = toVertexMapById(_expectedDFSIndices);
expectedDominatorTree = vertexMapToVertexId(_expectedDominatorTree);
}
// Converts a map of vertex labels to map of vertex IDs
std::map<TestVertexId, std::optional<TestVertexId>> labelMapToIdMap(std::map<TestVertexLabel, TestVertexLabel> const& _vertexLabelMap) const
{
return _vertexLabelMap
| ranges::views::transform([&](auto const& pair) -> std::pair<TestVertexId, std::optional<TestVertexId>> {
return {vertexIdMap.at(pair.first), (pair.second != "") ? std::optional<TestVertexId>(vertexIdMap.at(pair.second)) : std::nullopt};
})
| ranges::to<std::map<TestVertexId, std::optional<TestVertexId>>>;
}
// Converts a map with vertex labels as keys to a map with vertex IDs as keys.
template <typename T>
std::map<TestVertexId, T> toVertexMapById(std::map<TestVertexLabel, T> const& _verticesByLabel) const
{
return _verticesByLabel
| ranges::views::transform([&](auto const& pair) -> std::pair<TestVertexId, T> {
return {vertexIdMap.at(pair.first), pair.second};
})
| ranges::to<std::map<TestVertexId, T>>;
}
// Converts a map with vertex labels as keys to a map with vertex IDs as keys.
std::map<TestVertexId, std::vector<TestVertexId>> vertexMapToVertexId(std::map<TestVertexLabel, std::vector<TestVertexLabel>> const& _vertexMapByLabel) const
{
auto labelVectorToIdVector = [&](std::vector<TestVertexLabel> const& labels) -> std::vector<TestVertexId> {
return labels
| ranges::views::transform([&](TestVertexLabel const& label) {
soltestAssert(vertexIdMap.count(label));
return vertexIdMap.at(label);
})
| ranges::to<std::vector<TestVertexId>>;
};
return toVertexMapById(_vertexMapByLabel | ranges::views::transform([&](auto const& pair) -> std::pair<TestVertexLabel, std::vector<TestVertexId>> {
return {pair.first, labelVectorToIdVector(pair.second)};
}) | ranges::to<std::map<TestVertexLabel, std::vector<TestVertexId>>>);
}
TestVertex const* entry = nullptr;
std::vector<TestVertex> vertices;
// Reverse map from vertices labels to IDs
std::map<TestVertexLabel, TestVertexId> vertexIdMap;
std::map<TestVertexId, std::optional<TestVertexId>> expectedImmediateDominators;
std::map<TestVertexId, TestDominatorFinder::DfsIndex> expectedDFSIndices;
std::map<TestVertexId, std::vector<TestVertexId>> expectedDominatorTree;
};
BOOST_AUTO_TEST_SUITE(Dominators)
BOOST_AUTO_TEST_CASE(immediate_dominator_1)
{
// A
// │
// ▼
// ┌───B
// │ │
// ▼ │
// C ──┼───┐
// │ │ │
// ▼ │ ▼
// D◄──┘ G
// │ │
// ▼ ▼
// E H
// │ │
// └──►F◄──┘
DominatorFinderTest test(
{"A", "B", "C", "D", "E", "F", "G", "H"}, // Vertices
{ // Edges
Edge("A", "B"),
Edge("B", "C"),
Edge("B", "D"),
Edge("C", "D"),
Edge("C", "G"),
Edge("D", "E"),
Edge("E", "F"),
Edge("G", "H"),
Edge("H", "F")
},
{ // Immediate dominators
{"A", ""},
{"B", "A"},
{"C", "B"},
{"D", "B"},
{"E", "D"},
{"F", "B"},
{"G", "C"},
{"H", "G"}
},
{ // DFS indices
{"A", 0},
{"B", 1},
{"C", 2},
{"D", 3},
{"E", 4},
{"F", 5},
{"G", 6},
{"H", 7}
},
{ // Dominator tree
{"A", {"B"}},
{"B", {"C", "D", "F"}},
{"C", {"G"}},
{"D", {"E"}},
{"G", {"H"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(immediate_dominator_2)
{
// ┌────►A──────┐
// │ │ ▼
// │ B◄──┘ ┌──D──┐
// │ │ │ │
// │ ▼ ▼ ▼
// └─C◄───┐ E F
// │ │ │ │
// └───►G◄─┴─────┘
DominatorFinderTest test(
{"A", "B", "C", "D", "E", "F", "G"},
{
Edge("A", "B"),
Edge("B", "C"),
Edge("C", "G"),
Edge("C", "A"),
Edge("A", "D"),
Edge("D", "E"),
Edge("D", "F"),
Edge("E", "G"),
Edge("F", "G"),
Edge("G", "C")
},
{
{"A", ""},
{"B", "A"},
{"C", "A"},
{"D", "A"},
{"E", "D"},
{"F", "D"},
{"G", "A"}
},
{
{"A", 0},
{"B", 1},
{"C", 2},
{"G", 3},
{"D", 4},
{"E", 5},
{"F", 6}
},
{
{"A", {"B", "C", "G", "D"}},
{"D", {"E", "F"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(immediate_dominator_3)
{
// ┌─────────┐
// │ ▼
// │ ┌───A───┐
// │ │ │
// │ ▼ ▼
// │ ┌──►C◄───── B──┬──────┐
// │ │ │ ▲ │ │
// │ │ │ ┌────┘ │ │
// │ │ ▼ │ ▼ ▼
// │ │ D──┘ ┌───►E◄─────I
// │ │ ▲ │ │ │
// │ │ │ │ ├───┐ │
// │ │ │ │ │ │ │
// │ │ │ │ ▼ │ ▼
// │ └───┼─────┼────F └─►H
// │ │ │ │ │
// │ │ │ │ │
// │ │ │ │ │
// │ └─────┴─G◄─┴──────┘
// │ │
// └─────────────┘
DominatorFinderTest test(
{"A", "B", "C", "D", "E", "F", "G", "H", "I"},
{
Edge("A", "B"),
Edge("A", "C"),
Edge("B", "C"),
Edge("B", "I"),
Edge("B", "E"),
Edge("C", "D"),
Edge("D", "B"),
Edge("E", "H"),
Edge("E", "F"),
Edge("F", "G"),
Edge("F", "C"),
Edge("G", "E"),
Edge("G", "A"),
Edge("G", "D"),
Edge("H", "G"),
Edge("I", "E"),
Edge("I", "H")
},
{
{"A", ""},
{"B", "A"},
{"C", "A"},
{"D", "A"},
{"E", "B"},
{"F", "E"},
{"G", "B"},
{"H", "B"},
{"I", "B"}
},
{
{"A", 0},
{"B", 1},
{"C", 2},
{"D", 3},
{"I", 4},
{"E", 5},
{"H", 6},
{"G", 7},
{"F", 8}
},
{
{"A", {"B", "C", "D"}},
{"B", {"I", "E", "H", "G"}},
{"E", {"F"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(langauer_tarjan_p122_fig1)
{
// T. Lengauer and R. E. Tarjan pg. 122 fig. 1
// ref: https://www.cs.princeton.edu/courses/archive/spr03/cs423/download/dominators.pdf
DominatorFinderTest test(
{"R", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "K"},
{
Edge("R", "B"),
Edge("R", "A"),
Edge("R", "C"),
Edge("B", "A"),
Edge("B", "D"),
Edge("B", "E"),
Edge("A", "D"),
Edge("D", "L"),
Edge("L", "H"),
Edge("E", "H"),
Edge("H", "E"),
Edge("H", "K"),
Edge("K", "I"),
Edge("K", "R"),
Edge("C", "F"),
Edge("C", "G"),
Edge("F", "I"),
Edge("G", "I"),
Edge("G", "J"),
Edge("J", "I"),
Edge("I", "K")
},
{
{"R", ""},
{"A", "R"},
{"B", "R"},
{"C", "R"},
{"D", "R"},
{"E", "R"},
{"F", "C"},
{"G", "C"},
{"H", "R"},
{"I", "R"},
{"J", "G"},
{"L", "D"},
{"K", "R"}
},
{
{"R", 0},
{"B", 1},
{"A", 2},
{"D", 3},
{"L", 4},
{"H", 5},
{"E", 6},
{"K", 7},
{"I", 8},
{"C", 9},
{"F", 10},
{"G", 11},
{"J", 12}
},
{
{"R", {"B", "A", "D", "H", "E", "K", "I", "C"}},
{"D", {"L"}},
{"C", {"F", "G"}},
{"G", {"J"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(loukas_georgiadis)
{
// Extracted from Loukas Georgiadis Dissertation - Linear-Time Algorithms for Dominators and Related Problems
// pg. 12 Fig. 2.2
// ref: https://www.cs.princeton.edu/techreports/2005/737.pdf
DominatorFinderTest test(
{"R", "W", "X1", "X2", "X3", "X4", "X5", "X6", "X7", "Y"},
{
Edge("R", "W"),
Edge("R", "Y"),
Edge("W", "X1"),
Edge("Y", "X7"),
Edge("X1", "X2"),
Edge("X2", "X1"),
Edge("X2", "X3"),
Edge("X3", "X2"),
Edge("X3", "X4"),
Edge("X4", "X3"),
Edge("X4", "X5"),
Edge("X5", "X4"),
Edge("X5", "X6"),
Edge("X6", "X5"),
Edge("X6", "X7"),
Edge("X7", "X6")
},
{
{"R", ""},
{"W", "R"},
{"X1", "R"},
{"X2", "R"},
{"X3", "R"},
{"X4", "R"},
{"X5", "R"},
{"X6", "R"},
{"X7", "R"},
{"Y", "R"}
},
{
{"R", 0},
{"W", 1},
{"X1", 2},
{"X2", 3},
{"X3", 4},
{"X4", 5},
{"X5", 6},
{"X6", 7},
{"X7", 8},
{"Y", 9}
},
{
{"R", {"W", "X1", "X2", "X3", "X4", "X5", "X6", "X7", "Y"}},
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(itworst)
{
// Worst-case families for k = 3
// Example itworst(3) pg. 26 fig. 2.9
// ref: https://www.cs.princeton.edu/techreports/2005/737.pdf
DominatorFinderTest test(
{"R", "W1", "W2", "W3", "X1", "X2", "X3", "Y1", "Y2", "Y3", "Z1", "Z2", "Z3"},
{
Edge("R", "W1"),
Edge("R", "X1"),
Edge("R", "Z3"),
Edge("W1", "W2"),
Edge("W2", "W3"),
Edge("X1", "X2"),
Edge("X2", "X3"),
Edge("X3", "Y1"),
Edge("Y1", "W1"),
Edge("Y1", "W2"),
Edge("Y1", "W3"),
Edge("Y1", "Y2"),
Edge("Y2", "W1"),
Edge("Y2", "W2"),
Edge("Y2", "W3"),
Edge("Y2", "Y3"),
Edge("Y3", "W1"),
Edge("Y3", "W2"),
Edge("Y3", "W3"),
Edge("Y3", "Z1"),
Edge("Z1", "Z2"),
Edge("Z2", "Z1"),
Edge("Z2", "Z3"),
Edge("Z3", "Z2")
},
{
{"R", ""},
{"W1", "R"},
{"W2", "R"},
{"W3", "R"},
{"X1", "R"},
{"X2", "X1"},
{"X3", "X2"},
{"Y1", "X3"},
{"Y2", "Y1"},
{"Y3", "Y2"},
{"Z1", "R"},
{"Z2", "R"},
{"Z3", "R"}
},
{
{"R", 0},
{"W1", 1},
{"W2", 2},
{"W3", 3},
{"X1", 4},
{"X2", 5},
{"X3", 6},
{"Y1", 7},
{"Y2", 8},
{"Y3", 9},
{"Z1", 10},
{"Z2", 11},
{"Z3", 12}
},
{
{"R", {"W1", "W2", "W3", "X1", "Z1", "Z2", "Z3"}},
{"X1", {"X2"}},
{"X2", {"X3"}},
{"X3", {"Y1"}},
{"Y1", {"Y2"}},
{"Y2", {"Y3"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(idfsquad)
{
// Worst-case families for k = 3
// Example idfsquad(3) pg. 26 fig. 2.9
// ref: https://www.cs.princeton.edu/techreports/2005/737.pdf
DominatorFinderTest test(
{"R", "X1", "X2", "X3", "Y1", "Y2", "Y3", "Z1", "Z2", "Z3"},
{
Edge("R", "X1"),
Edge("R", "Z1"),
Edge("X1", "Y1"),
Edge("X1", "X2"),
Edge("X2", "X3"),
Edge("X2", "Y2"),
Edge("X3", "Y3"),
Edge("Y1", "Z1"),
Edge("Y1", "Z2"),
Edge("Z1", "Y1"),
Edge("Y2", "Z2"),
Edge("Y2", "Z3"),
Edge("Z2", "Y2"),
Edge("Y3", "Z3"),
Edge("Z3", "Y3")
},
{
{"R", ""},
{"X1", "R"},
{"X2", "X1"},
{"X3", "X2"},
{"Y1", "R"},
{"Y2", "R"},
{"Y3", "R"},
{"Z1", "R"},
{"Z2", "R"},
{"Z3", "R"}
},
{
{"R", 0},
{"X1", 1},
{"Y1", 2},
{"Z1", 3},
{"Z2", 4},
{"Y2", 5},
{"Z3", 6},
{"Y3", 7},
{"X2", 8},
{"X3", 9}
},
{
{"R", {"X1", "Y1", "Z1", "Z2", "Y2", "Z3", "Y3"}},
{"X1", {"X2"}},
{"X2", {"X3"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(ibsfquad)
{
// Worst-case families for k = 3
// Example ibfsquad(3) pg. 26 fig. 2.9
// ref: https://www.cs.princeton.edu/techreports/2005/737.pdf
DominatorFinderTest test(
{"R", "W", "X1", "X2", "X3", "Y", "Z"},
{
Edge("R", "W"),
Edge("R", "Y"),
Edge("W", "X1"),
Edge("W", "X2"),
Edge("W", "X3"),
Edge("Y", "Z"),
Edge("Z", "X3"),
Edge("X3", "X2"),
Edge("X2", "X1")
},
{
{"R", ""},
{"W", "R"},
{"X1", "R"},
{"X2", "R"},
{"X3", "R"},
{"Y", "R"},
{"Z", "Y"}
},
{
{"R", 0},
{"W", 1},
{"X1", 2},
{"X2", 3},
{"X3", 4},
{"Y", 5},
{"Z", 6}
},
{
{"R", {"W", "X1", "X2", "X3", "Y"}},
{"Y", {"Z"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(sncaworst)
{
// Worst-case families for k = 3
// Example sncaworst(3) pg. 26 fig. 2.9
// ref: https://www.cs.princeton.edu/techreports/2005/737.pdf
DominatorFinderTest test(
{"R", "X1", "X2", "X3", "Y1", "Y2", "Y3"},
{
Edge("R", "X1"),
Edge("R", "Y1"),
Edge("R", "Y2"),
Edge("R", "Y3"),
Edge("X1", "X2"),
Edge("X2", "X3"),
Edge("X3", "Y1"),
Edge("X3", "Y2"),
Edge("X3", "Y3")
},
{
{"R", ""},
{"X1", "R"},
{"X2", "X1"},
{"X3", "X2"},
{"Y1", "R"},
{"Y2", "R"},
{"Y3", "R"}
},
{
{"R", 0},
{"X1", 1},
{"X2", 2},
{"X3", 3},
{"Y1", 4},
{"Y2", 5},
{"Y3", 6}
},
{
{"R", {"X1", "Y1", "Y2", "Y3"}},
{"X1", {"X2"}},
{"X2", {"X3"}}
}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_CASE(collect_all_dominators_of_a_vertex)
{
// A
// │
// ▼
// ┌───B
// │ │
// ▼ │
// C ──┼───┐
// │ │ │
// ▼ │ ▼
// D◄──┘ G
// │ │
// ▼ ▼
// E H
// │ │
// └──►F◄──┘
DominatorFinderTest test(
{"A", "B", "C", "D", "E", "F", "G", "H"},
{
Edge("A", "B"),
Edge("B", "C"),
Edge("B", "D"),
Edge("C", "D"),
Edge("C", "G"),
Edge("D", "E"),
Edge("E", "F"),
Edge("G", "H"),
Edge("H", "F")
},
{},
{},
{}
);
// Converts a vector of vertex IDs to a vector of vertex labels.
auto toVertexLabel = [&](std::vector<TestVertexId> const& _vertices)
{
return _vertices | ranges::views::transform([&](TestVertexId id){
return test.vertices[id].label;
}) | ranges::to<std::vector<TestVertexLabel>>;
};
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["A"])) == std::vector<TestVertexLabel>());
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["B"])) == std::vector<TestVertexLabel>({"A"}));
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["C"])) == std::vector<TestVertexLabel>({"B", "A"}));
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["D"])) == std::vector<TestVertexLabel>({"B", "A"}));
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["E"])) == std::vector<TestVertexLabel>({"D", "B", "A"}));
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["F"])) == std::vector<TestVertexLabel>({"B", "A"}));
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["G"])) == std::vector<TestVertexLabel>({"C", "B", "A"}));
BOOST_TEST(toVertexLabel(dominatorFinder.dominatorsOf(test.vertexIdMap["H"])) == std::vector<TestVertexLabel>({"G", "C", "B", "A"}));
}
BOOST_AUTO_TEST_CASE(check_dominance)
{
// A
// │
// ▼
// ┌───B
// │ │
// ▼ │
// C ──┼───┐
// │ │ │
// ▼ │ ▼
// D◄──┘ G
// │ │
// ▼ ▼
// E H
// │ │
// └──►F◄──┘
DominatorFinderTest test(
{"A", "B", "C", "D", "E", "F", "G", "H"},
{
Edge("A", "B"),
Edge("B", "C"),
Edge("B", "D"),
Edge("C", "D"),
Edge("C", "G"),
Edge("D", "E"),
Edge("E", "F"),
Edge("G", "H"),
Edge("H", "F")
},
{},
{
{"A", 0},
{"B", 1},
{"C", 2},
{"D", 3},
{"E", 4},
{"F", 5},
{"G", 6},
{"H", 7}
},
{}
);
// Helper function to create a dominance relation for a vertex with all other vertices.
//
// @param _indices: The indices of the vertices that the vertex dominates.
// @return: A vector of booleans where the index represents the vertex and the value
// represents if the vertex dominates the other vertex at that index.
auto makeDominanceVertexRelation = [&](std::vector<TestDominatorFinder::DfsIndex> const& _indices = {}){
std::vector<bool> dominance(test.vertices.size(), false);
for (TestDominatorFinder::DfsIndex i: _indices)
{
soltestAssert(i < test.vertices.size());
dominance[i] = true;
}
return dominance;
};
// Dominance truth table for all vertices.
// Note that it includes self-dominance relation.
std::vector<std::vector<bool>> expectedDominanceTable = {
std::vector<bool>(test.vertices.size(), true), // A dominates all vertices, including itself
makeDominanceVertexRelation({1,2,3,4,5,6,7}), // B, C, D, E, F, G, H
makeDominanceVertexRelation({2, 6, 7}), // C, G, H
makeDominanceVertexRelation({3, 4}), // D, E
makeDominanceVertexRelation({4}), // E
makeDominanceVertexRelation({5}), // F
makeDominanceVertexRelation({6, 7}), // G, H
makeDominanceVertexRelation({7}) // H
};
soltestAssert(expectedDominanceTable.size() == test.vertices.size());
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
// Check if the dominance table is as expected.
for (TestDominatorFinder::DfsIndex i = 0; i < expectedDominanceTable.size(); ++i)
{
soltestAssert(expectedDominanceTable[i].size() == test.vertices.size());
for (TestDominatorFinder::DfsIndex j = 0; j < expectedDominanceTable[i].size(); ++j)
{
bool iDominatesJ = dominatorFinder.dominates(i, j);
BOOST_CHECK_MESSAGE(
iDominatesJ == expectedDominanceTable[i][j],
fmt::format(
"Vertex: {} expected to {} dominate vertex {} but returned: {}\n",
i,
(iDominatesJ ? "" : "not"),
j,
iDominatesJ
)
);
}
}
}
BOOST_AUTO_TEST_CASE(no_edges)
{
DominatorFinderTest test(
{"A"},
{},
{
{"A", ""},
},
{
{"A", 0},
},
{}
);
TestDominatorFinder dominatorFinder(*test.entry);
BOOST_TEST(dominatorFinder.immediateDominators() == test.expectedImmediateDominators);
BOOST_TEST(dominatorFinder.dfsIndexById() == test.expectedDFSIndices);
BOOST_TEST(dominatorFinder.dominatorTree() == test.expectedDominatorTree);
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::util::test
| 24,874
|
C++
|
.cpp
| 865
| 24.758382
| 158
| 0.562252
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,031
|
FixedHash.cpp
|
ethereum_solidity/test/libsolutil/FixedHash.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Unit tests for FixedHash.
*/
#include <libsolutil/FixedHash.h>
#include <boost/test/unit_test.hpp>
#include <cstdint>
#include <sstream>
namespace solidity::util::test
{
static_assert(std::is_same<h160, FixedHash<20>>());
static_assert(std::is_same<h256, FixedHash<32>>());
BOOST_AUTO_TEST_SUITE(FixedHashTest)
BOOST_AUTO_TEST_CASE(default_constructor)
{
BOOST_CHECK_EQUAL(
FixedHash<1>{}.hex(),
"00"
);
BOOST_CHECK_EQUAL(
FixedHash<1>{}.size,
1
);
BOOST_CHECK_EQUAL(
FixedHash<8>{}.hex(),
"0000000000000000"
);
BOOST_CHECK_EQUAL(
FixedHash<8>{}.size,
8
);
BOOST_CHECK_EQUAL(
FixedHash<20>{}.hex(),
"0000000000000000000000000000000000000000"
);
BOOST_CHECK_EQUAL(
FixedHash<20>{}.size,
20
);
BOOST_CHECK_EQUAL(
FixedHash<32>{}.hex(),
"0000000000000000000000000000000000000000000000000000000000000000"
);
BOOST_CHECK_EQUAL(
FixedHash<32>{}.size,
32
);
}
BOOST_AUTO_TEST_CASE(bytes_constructor)
{
FixedHash<8> a(bytes{});
BOOST_CHECK_EQUAL(a.size, 8);
BOOST_CHECK_EQUAL(a.hex(), "0000000000000000");
FixedHash<8> b(bytes{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88});
BOOST_CHECK_EQUAL(b.size, 8);
BOOST_CHECK_EQUAL(b.hex(), "1122334455667788");
// TODO: short input, this should fail
FixedHash<8> c(bytes{0x11, 0x22, 0x33, 0x44, 0x55, 0x66});
BOOST_CHECK_EQUAL(c.size, 8);
BOOST_CHECK_EQUAL(c.hex(), "0000000000000000");
// TODO: oversized input, this should fail
FixedHash<8> d(bytes{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99});
BOOST_CHECK_EQUAL(d.size, 8);
BOOST_CHECK_EQUAL(d.hex(), "0000000000000000");
}
// TODO: add FixedHash(bytesConstRef) constructor
BOOST_AUTO_TEST_CASE(string_constructor_fromhex)
{
// TODO: this tests the default settings ConstructFromStringType::fromHex, ConstructFromHashType::FailIfDifferent
// should test other options too
FixedHash<8> a("");
BOOST_CHECK_EQUAL(a.size, 8);
BOOST_CHECK_EQUAL(a.hex(), "0000000000000000");
FixedHash<8> b("1122334455667788");
BOOST_CHECK_EQUAL(b.size, 8);
BOOST_CHECK_EQUAL(b.hex(), "1122334455667788");
FixedHash<8> c("0x1122334455667788");
BOOST_CHECK_EQUAL(c.size, 8);
BOOST_CHECK_EQUAL(c.hex(), "1122334455667788");
// TODO: short input, this should fail
FixedHash<8> d("112233445566");
BOOST_CHECK_EQUAL(d.size, 8);
BOOST_CHECK_EQUAL(d.hex(), "0000000000000000");
// TODO: oversized input, this should fail
FixedHash<8> e("112233445566778899");
BOOST_CHECK_EQUAL(e.size, 8);
BOOST_CHECK_EQUAL(e.hex(), "0000000000000000");
}
BOOST_AUTO_TEST_CASE(string_constructor_frombytes)
{
FixedHash<8> b("", FixedHash<8>::FromBinary);
BOOST_CHECK_EQUAL(b.size, 8);
BOOST_CHECK_EQUAL(b.hex(), "0000000000000000");
FixedHash<8> c("abcdefgh", FixedHash<8>::FromBinary);
BOOST_CHECK_EQUAL(c.size, 8);
BOOST_CHECK_EQUAL(c.hex(), "6162636465666768");
// TODO: short input, this should fail
FixedHash<8> d("abcdefg", FixedHash<8>::FromBinary);
BOOST_CHECK_EQUAL(d.size, 8);
BOOST_CHECK_EQUAL(d.hex(), "0000000000000000");
// TODO: oversized input, this should fail
FixedHash<8> e("abcdefghi", FixedHash<8>::FromBinary);
BOOST_CHECK_EQUAL(e.size, 8);
BOOST_CHECK_EQUAL(e.hex(), "0000000000000000");
}
BOOST_AUTO_TEST_CASE(converting_constructor)
{
// Left-aligned truncation
FixedHash<8> a = FixedHash<8>(FixedHash<12>("112233445566778899001122"), FixedHash<8>::AlignLeft);
BOOST_CHECK_EQUAL(a.size, 8);
BOOST_CHECK_EQUAL(a.hex(), "1122334455667788");
// Right-aligned truncation
FixedHash<8> b = FixedHash<8>(FixedHash<12>("112233445566778899001122"), FixedHash<8>::AlignRight);
BOOST_CHECK_EQUAL(b.size, 8);
BOOST_CHECK_EQUAL(b.hex(), "5566778899001122");
// Left-aligned extension
FixedHash<12> c = FixedHash<12>(FixedHash<8>("1122334455667788"), FixedHash<12>::AlignLeft);
BOOST_CHECK_EQUAL(c.size, 12);
BOOST_CHECK_EQUAL(c.hex(), "112233445566778800000000");
// Right-aligned extension
FixedHash<12> d = FixedHash<12>(FixedHash<8>("1122334455667788"), FixedHash<12>::AlignRight);
BOOST_CHECK_EQUAL(d.size, 12);
BOOST_CHECK_EQUAL(d.hex(), "000000001122334455667788");
// FailIfDifferent setting
// TODO: Shouldn't this throw?
FixedHash<12> e = FixedHash<12>(FixedHash<8>("1122334455667788"), FixedHash<12>::FailIfDifferent);
BOOST_CHECK_EQUAL(e, c);
}
BOOST_AUTO_TEST_CASE(arith_constructor)
{
FixedHash<32> b(u256(0x12340000));
BOOST_CHECK_EQUAL(
b.hex(),
"0000000000000000000000000000000000000000000000000000000012340000"
);
// NOTE: size-mismatched constructor is not available
}
BOOST_AUTO_TEST_CASE(to_arith)
{
FixedHash<32> b("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
BOOST_CHECK_EQUAL(u256(b), u256("0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
}
BOOST_AUTO_TEST_CASE(comparison)
{
FixedHash<32> a("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
FixedHash<32> b("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
FixedHash<32> c("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a471");
FixedHash<32> d("233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470c5d2460186f7");
BOOST_CHECK(a == a);
BOOST_CHECK(b == b);
BOOST_CHECK(a == b);
BOOST_CHECK(b == a);
BOOST_CHECK(a != c);
BOOST_CHECK(c != a);
BOOST_CHECK(a != d);
BOOST_CHECK(d != a);
// Only equal size comparison is supported.
BOOST_CHECK(FixedHash<8>{} == FixedHash<8>{});
BOOST_CHECK(FixedHash<32>{} != b);
// Only equal size less than comparison is supported.
BOOST_CHECK(!(a < b));
BOOST_CHECK(d < c);
BOOST_CHECK(FixedHash<32>{} < a);
}
BOOST_AUTO_TEST_CASE(indexing)
{
// NOTE: uses std::array, so "Accessing a nonexistent element through this operator is undefined behavior."
FixedHash<32> a("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
BOOST_CHECK_EQUAL(a[0], 0xc5);
BOOST_CHECK_EQUAL(a[1], 0xd2);
BOOST_CHECK_EQUAL(a[31], 0x70);
a[0] = 0xff;
a[31] = 0x54;
BOOST_CHECK_EQUAL(a[0], 0xff);
BOOST_CHECK_EQUAL(a[1], 0xd2);
BOOST_CHECK_EQUAL(a[31], 0x54);
}
BOOST_AUTO_TEST_CASE(misc)
{
FixedHash<32> a("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
uint8_t* mut_a = a.data();
uint8_t const* const_a = a.data();
BOOST_CHECK_EQUAL(mut_a, const_a);
BOOST_CHECK_EQUAL(memcmp(mut_a, const_a, a.size), 0);
bytes bytes_a = a.asBytes();
bytesRef bytesref_a = a.ref();
bytesConstRef bytesconstref_a = a.ref();
// There's no printing for bytesRef/bytesConstRef
BOOST_CHECK(bytes(a.data(), a.data() + a.size) == bytes_a);
BOOST_CHECK(bytesRef(a.data(), a.size) == bytesref_a);
BOOST_CHECK(bytesConstRef(a.data(), a.size) == bytesconstref_a);
}
BOOST_AUTO_TEST_CASE(tostream)
{
std::ostringstream out;
out << FixedHash<4>("44114411");
out << FixedHash<32>{};
out << FixedHash<2>("f77f");
out << FixedHash<1>("1");
BOOST_CHECK_EQUAL(out.str(), "441144110000000000000000000000000000000000000000000000000000000000000000f77f01");
}
BOOST_AUTO_TEST_SUITE_END()
}
| 7,612
|
C++
|
.cpp
| 215
| 33.32093
| 114
| 0.74636
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,033
|
CharStream.cpp
|
ethereum_solidity/test/liblangutil/CharStream.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Rocky Bernstein <rocky.bernstein@consensys.net>
* @date 2019
* Unit tests for the CharStream class.
*/
#include <liblangutil/CharStream.h>
#include <liblangutil/Exceptions.h>
#include <test/Common.h>
#include <boost/test/unit_test.hpp>
using namespace solidity::test;
namespace boost::test_tools::tt_detail
{
template<>
struct print_log_value<std::optional<int>>
{
void operator()(std::ostream& _out, std::optional<int> const& _value) const
{
_out << (_value ? to_string(*_value) : "[std::nullopt]");
}
};
template<>
struct print_log_value<std::nullopt_t>
{
void operator()(std::ostream& _out, std::nullopt_t const&) const
{
_out << "[std::nullopt]";
}
};
} // namespace boost::test_tools::tt_detail
namespace solidity::langutil::test
{
BOOST_AUTO_TEST_SUITE(CharStreamTest)
BOOST_AUTO_TEST_CASE(test_fail)
{
auto const source = std::make_shared<CharStream>("now is the time for testing", "source");
BOOST_CHECK('n' == source->get());
BOOST_CHECK('n' == source->get());
BOOST_CHECK('o' == source->advanceAndGet());
BOOST_CHECK('n' == source->rollback(1));
BOOST_CHECK('w' == source->setPosition(2));
BOOST_REQUIRE_THROW(
source->setPosition(200),
::solidity::langutil::InternalCompilerError
);
}
namespace
{
std::optional<int> toPosition(int _line, int _column, std::string const& _text)
{
return CharStream{_text, "source"}.translateLineColumnToPosition(
LineColumn{_line, _column}
);
}
}
BOOST_AUTO_TEST_CASE(translateLineColumnToPosition)
{
BOOST_CHECK_EQUAL(toPosition(-1, 0, "ABC"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(0, -1, "ABC"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(0, 0, ""), 0);
BOOST_CHECK_EQUAL(toPosition(1, 0, ""), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(0, 1, ""), std::nullopt);
// With last line containing no LF
BOOST_CHECK_EQUAL(toPosition(0, 0, "ABC"), 0);
BOOST_CHECK_EQUAL(toPosition(0, 1, "ABC"), 1);
BOOST_CHECK_EQUAL(toPosition(0, 2, "ABC"), 2);
BOOST_CHECK_EQUAL(toPosition(0, 3, "ABC"), 3);
BOOST_CHECK_EQUAL(toPosition(0, 4, "ABC"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(1, 0, "ABC"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(0, 3, "ABC\nDEF"), 3);
BOOST_CHECK_EQUAL(toPosition(0, 4, "ABC\nDEF"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(1, 0, "ABC\nDEF"), 4);
BOOST_CHECK_EQUAL(toPosition(1, 1, "ABC\nDEF"), 5);
BOOST_CHECK_EQUAL(toPosition(1, 2, "ABC\nDEF"), 6);
BOOST_CHECK_EQUAL(toPosition(1, 3, "ABC\nDEF"), 7);
BOOST_CHECK_EQUAL(toPosition(1, 4, "ABC\nDEF"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(2, 0, "ABC\nDEF"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(2, 1, "ABC\nDEF"), std::nullopt);
// With last line containing LF
BOOST_CHECK_EQUAL(toPosition(0, 0, "ABC\nDEF\n"), 0);
BOOST_CHECK_EQUAL(toPosition(0, 1, "ABC\nDEF\n"), 1);
BOOST_CHECK_EQUAL(toPosition(0, 2, "ABC\nDEF\n"), 2);
BOOST_CHECK_EQUAL(toPosition(1, 0, "ABC\nDEF\n"), 4);
BOOST_CHECK_EQUAL(toPosition(1, 1, "ABC\nDEF\n"), 5);
BOOST_CHECK_EQUAL(toPosition(1, 2, "ABC\nDEF\n"), 6);
BOOST_CHECK_EQUAL(toPosition(1, 3, "ABC\nDEF\n"), 7);
BOOST_CHECK_EQUAL(toPosition(1, 4, "ABC\nDEF\n"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(2, 0, "ABC\nDEF\n"), 8);
BOOST_CHECK_EQUAL(toPosition(2, 1, "ABC\nDEF\n"), std::nullopt);
BOOST_CHECK_EQUAL(toPosition(2, 0, "ABC\nDEF\nGHI\n"), 8);
BOOST_CHECK_EQUAL(toPosition(2, 1, "ABC\nDEF\nGHI\n"), 9);
BOOST_CHECK_EQUAL(toPosition(2, 2, "ABC\nDEF\nGHI\n"), 10);
}
BOOST_AUTO_TEST_SUITE_END()
}
| 4,159
|
C++
|
.cpp
| 108
| 36.555556
| 91
| 0.713469
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,034
|
Scanner.cpp
|
ethereum_solidity/test/liblangutil/Scanner.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Unit tests for the solidity scanner.
*/
#include <liblangutil/Scanner.h>
#include <boost/test/unit_test.hpp>
using namespace solidity::langutil;
using namespace std::string_literals;
namespace solidity::langutil::test
{
BOOST_AUTO_TEST_SUITE(ScannerTest)
BOOST_AUTO_TEST_CASE(test_empty)
{
CharStream stream{};
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(smoke_test)
{
CharStream stream("function break;765 \t \"string1\",'string2'\nidentifier1", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Break);
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "765");
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "string1");
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "string2");
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "identifier1");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(assembly_assign)
{
CharStream stream("let a := 1", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Let);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssemblyAssign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "1");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(assembly_multiple_assign)
{
CharStream stream("let a, b, c := 1", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Let);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssemblyAssign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "1");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(string_printable)
{
for (unsigned v = 0x20; v < 0x7e; v++) {
std::string lit{static_cast<char>(v)};
// Escape \ and " (since we are quoting with ")
if (v == '\\' || v == '"')
lit = std::string{'\\'} + lit;
CharStream stream(" { \"" + lit + "\"", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string{static_cast<char>(v)});
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
// Special case of unescaped " for strings quoted with '
CharStream stream(" { '\"'", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "\"");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(string_nonprintable)
{
for (unsigned v = 0; v < 0xff; v++) {
// Skip the valid ones
if (v >= 0x20 && v <= 0x7e)
continue;
std::string lit{static_cast<char>(v)};
CharStream stream(" { \"" + lit + "\"", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
if (v == '\n' || v == '\v' || v == '\f' || v == '\r')
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalStringEndQuote);
else
BOOST_CHECK_EQUAL(scanner.currentError(),ScannerError::UnicodeCharacterInNonUnicodeString);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "");
}
}
BOOST_AUTO_TEST_CASE(string_escapes)
{
CharStream stream(" { \"a\\x61\"", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "aa");
}
BOOST_AUTO_TEST_CASE(string_escapes_all)
{
CharStream stream(" { \"a\\x61\\n\\r\\t\"", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "aa\n\r\t");
}
struct TestScanner
{
std::unique_ptr<CharStream> stream;
std::unique_ptr<Scanner> scanner;
explicit TestScanner(std::string _text) { reset(std::move(_text)); }
void reset(std::string _text)
{
stream = std::make_unique<CharStream>(std::move(_text), "");
scanner = std::make_unique<Scanner>(*stream);
}
decltype(auto) currentToken() { return scanner->currentToken(); }
decltype(auto) next() { return scanner->next(); }
decltype(auto) currentError() { return scanner->currentError(); }
decltype(auto) currentLiteral() { return scanner->currentLiteral(); }
decltype(auto) currentCommentLiteral() { return scanner->currentCommentLiteral(); }
decltype(auto) currentLocation() { return scanner->currentLocation(); }
};
BOOST_AUTO_TEST_CASE(string_escapes_legal_before_080)
{
TestScanner scanner(" { \"a\\b");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalEscapeSequence);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "");
scanner.reset(" { \"a\\f");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalEscapeSequence);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "");
scanner.reset(" { \"a\\v");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalEscapeSequence);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(string_escapes_with_zero)
{
TestScanner scanner(" { \"a\\x61\\x00abc\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("aa\0abc", 6));
}
BOOST_AUTO_TEST_CASE(string_escape_illegal)
{
CharStream stream(" bla \"\\x6rf\" (illegalescape)", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalEscapeSequence);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "");
// TODO recovery from illegal tokens should be improved
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(hex_numbers)
{
TestScanner scanner("var x = 0x765432536763762734623472346;");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Var);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Assign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "0x765432536763762734623472346");
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("0x1234");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "0x1234");
scanner.reset("0X1234");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
}
BOOST_AUTO_TEST_CASE(octal_numbers)
{
TestScanner scanner("07");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
scanner.reset("007");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
scanner.reset("-07");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
scanner.reset("-.07");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
scanner.reset("0");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
scanner.reset("0.1");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
}
BOOST_AUTO_TEST_CASE(scientific_notation)
{
CharStream stream("var x = 2e10;", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Var);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Assign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "2e10");
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(leading_dot_in_identifier)
{
TestScanner scanner("function .a(");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("function .a(");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(middle_dot_in_identifier)
{
TestScanner scanner("function a..a(");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("function a...a(");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(trailing_dot_in_identifier)
{
TestScanner scanner("function a.(");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("function a.(");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(trailing_dot_in_numbers)
{
TestScanner scanner("2.5");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("2.5e10");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset(".5");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset(".5e10");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("2.");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(leading_underscore_decimal_is_identifier)
{
// Actual error is caught by SyntaxChecker.
CharStream stream("_1.2", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(leading_underscore_decimal_after_dot_illegal)
{
// Actual error is caught by SyntaxChecker.
TestScanner scanner("1._2");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("1._");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(leading_underscore_exp_are_identifier)
{
// Actual error is caught by SyntaxChecker.
CharStream stream("_1e2", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(leading_underscore_exp_after_e_illegal)
{
// Actual error is caught by SyntaxChecker.
CharStream stream("1e_2", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "1e_2");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(leading_underscore_hex_illegal)
{
CharStream stream("0x_abc", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(fixed_number_invalid_underscore_front)
{
// Actual error is caught by SyntaxChecker.
CharStream stream("12._1234_1234", "");
Scanner scanner(stream);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(number_literals_with_trailing_underscore_at_eos)
{
// Actual error is caught by SyntaxChecker.
TestScanner scanner("0x123_");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("123_");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("12.34_");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(negative_numbers)
{
TestScanner scanner("var x = -.2 + -0x78 + -7.3 + 8.9 + 2e-2;");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Var);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Assign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), ".2");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "0x78");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "7.3");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "8.9");
BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "2e-2");
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(locations)
{
TestScanner scanner("function_identifier has ; -0x743/*comment*/\n ident //comment");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLocation().start, 0);
BOOST_CHECK_EQUAL(scanner.currentLocation().end, 19);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLocation().start, 20);
BOOST_CHECK_EQUAL(scanner.currentLocation().end, 23);
BOOST_CHECK_EQUAL(scanner.next(), Token::Semicolon);
BOOST_CHECK_EQUAL(scanner.currentLocation().start, 24);
BOOST_CHECK_EQUAL(scanner.currentLocation().end, 25);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.currentLocation().start, 27);
BOOST_CHECK_EQUAL(scanner.currentLocation().end, 32);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLocation().start, 45);
BOOST_CHECK_EQUAL(scanner.currentLocation().end, 50);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(ambiguities)
{
// test scanning of some operators which need look-ahead
TestScanner scanner("<=" "<" "+ +=a++ =>" "<<" ">>" " >>=" ">>>" ">>>=" " >>>>>=><<=");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LessThanOrEqual);
BOOST_CHECK_EQUAL(scanner.next(), Token::LessThan);
BOOST_CHECK_EQUAL(scanner.next(), Token::Add);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssignAdd);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Inc);
BOOST_CHECK_EQUAL(scanner.next(), Token::DoubleArrow);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHL);
BOOST_CHECK_EQUAL(scanner.next(), Token::SAR);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssignSar);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHR);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssignShr);
// the last "monster" token combination
BOOST_CHECK_EQUAL(scanner.next(), Token::SHR);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssignSar);
BOOST_CHECK_EQUAL(scanner.next(), Token::GreaterThan);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssignShl);
}
BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin)
{
TestScanner scanner("/// Send $(value / 1000) chocolates to the user");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed_begin)
{
TestScanner scanner("/** Send $(value / 1000) chocolates to the user*/");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(documentation_comments_parsed)
{
TestScanner scanner("some other tokens /// Send $(value / 1000) chocolates to the user");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(multiline_documentation_comments_parsed)
{
TestScanner scanner("some other tokens /**\n"
"* Send $(value / 1000) chocolates to the user\n"
"*/");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), " Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(multiline_documentation_no_stars)
{
TestScanner scanner("some other tokens /**\n"
" Send $(value / 1000) chocolates to the user\n"
"*/");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(multiline_documentation_whitespace_hell)
{
TestScanner scanner("some other tokens /** \t \r \n"
"\t \r * Send $(value / 1000) chocolates to the user\n"
"*/");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), " Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(comment_before_eos)
{
TestScanner scanner("//");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(documentation_comment_before_eos)
{
TestScanner scanner("///");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(empty_multiline_comment)
{
TestScanner scanner("/**/");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(empty_multiline_documentation_comment_before_eos)
{
TestScanner scanner("/***/");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence)
{
TestScanner scanner("hello_world ///documentation comment \n"
"//simple comment \n"
"<<");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHL);
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "documentation comment ");
}
BOOST_AUTO_TEST_CASE(ether_subdenominations)
{
TestScanner scanner("wei gwei ether");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::SubWei);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubGwei);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubEther);
}
BOOST_AUTO_TEST_CASE(time_subdenominations)
{
TestScanner scanner("seconds minutes hours days weeks years");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::SubSecond);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubMinute);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubHour);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubDay);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubWeek);
BOOST_CHECK_EQUAL(scanner.next(), Token::SubYear);
}
BOOST_AUTO_TEST_CASE(empty_comment)
{
TestScanner scanner("//\ncontract{}");
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Contract);
BOOST_CHECK_EQUAL(scanner.next(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::RBrace);
}
// Unicode string escapes
BOOST_AUTO_TEST_CASE(valid_unicode_string_escape)
{
TestScanner scanner("{ \"\\u00DAnicode\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("\xC3\x9Anicode", 8));
}
BOOST_AUTO_TEST_CASE(valid_unicode_string_escape_7f)
{
TestScanner scanner("{ \"\\u007Fnicode\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("\x7Fnicode", 7));
}
BOOST_AUTO_TEST_CASE(valid_unicode_string_escape_7ff)
{
TestScanner scanner("{ \"\\u07FFnicode\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("\xDF\xBFnicode", 8));
}
BOOST_AUTO_TEST_CASE(valid_unicode_string_escape_ffff)
{
TestScanner scanner("{ \"\\uFFFFnicode\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::StringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("\xEF\xBF\xBFnicode", 9));
}
BOOST_AUTO_TEST_CASE(invalid_short_unicode_string_escape)
{
TestScanner scanner("{ \"\\uFFnicode\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
}
// Unicode string literal
BOOST_AUTO_TEST_CASE(unicode_prefix_only)
{
TestScanner scanner("{ unicode");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
scanner.reset("{ unicode");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "unicode");
}
BOOST_AUTO_TEST_CASE(unicode_invalid_space)
{
TestScanner scanner("{ unicode ");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
}
BOOST_AUTO_TEST_CASE(unicode_invalid_token)
{
TestScanner scanner("{ unicode test");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
scanner.reset("{ unicode test");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "unicode");
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "test");
}
BOOST_AUTO_TEST_CASE(valid_unicode_literal)
{
TestScanner scanner("{ unicode\"Hello üòÉ\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::UnicodeStringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("Hello \xf0\x9f\x98\x83", 10));
}
BOOST_AUTO_TEST_CASE(valid_nonprintable_in_unicode_literal)
{
// Non-printable characters are allowed in unicode strings...
TestScanner scanner("{ unicode\"Hello \007üòÉ\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::UnicodeStringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("Hello \x07\xf0\x9f\x98\x83", 11));
}
// Hex string literal
BOOST_AUTO_TEST_CASE(hex_prefix_only)
{
TestScanner scanner("{ hex");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
scanner.reset("{ hex");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
}
BOOST_AUTO_TEST_CASE(hex_invalid_space)
{
TestScanner scanner("{ hex ");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
}
BOOST_AUTO_TEST_CASE(hex_invalid_token)
{
TestScanner scanner("{ hex test");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
scanner.reset("{ hex test");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalToken);
}
BOOST_AUTO_TEST_CASE(valid_hex_literal)
{
TestScanner scanner("{ hex\"00112233FF\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::HexStringLiteral);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), std::string("\x00\x11\x22\x33\xFF", 5));
}
BOOST_AUTO_TEST_CASE(invalid_short_hex_literal)
{
TestScanner scanner("{ hex\"00112233F\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalHexString);
}
BOOST_AUTO_TEST_CASE(invalid_hex_literal_with_space)
{
TestScanner scanner("{ hex\"00112233FF \"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalHexString);
}
BOOST_AUTO_TEST_CASE(invalid_hex_literal_with_wrong_quotes)
{
TestScanner scanner("{ hex\"00112233FF'");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalHexString);
}
BOOST_AUTO_TEST_CASE(invalid_hex_literal_nonhex_string)
{
TestScanner scanner("{ hex\"hello\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::LBrace);
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.currentError(), ScannerError::IllegalHexString);
}
// Comments
BOOST_AUTO_TEST_CASE(invalid_multiline_comment_close)
{
// This used to parse as "comment", "identifier"
TestScanner scanner("/** / x");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(multiline_doc_comment_at_eos)
{
// This used to parse as "whitespace"
TestScanner scanner("/**");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(multiline_comment_at_eos)
{
TestScanner scanner("/*");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(regular_line_break_in_single_line_comment)
{
for (auto const& nl: {"\r", "\n", "\r\n"})
{
TestScanner scanner("// abc " + std::string(nl) + " def ");
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "def");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(irregular_line_breaks_in_single_line_comment)
{
for (auto const& nl: {"\v", "\f", "\xE2\x80\xA8", "\xE2\x80\xA9"})
{
TestScanner scanner("// abc " + std::string(nl) + " def ");
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
for (size_t i = 0; i < std::string(nl).size() - 1; i++)
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "def");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(regular_line_breaks_in_single_line_doc_comment)
{
for (auto const& nl: {"\r", "\n", "\r\n"})
{
TestScanner scanner("/// abc " + std::string(nl) + " def ");
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "abc ");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "def");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(regular_line_breaks_in_multiline_doc_comment)
{
// Test CR, LF, CRLF as line valid terminators for code comments.
// Any accepted non-LF is being canonicalized to LF.
for (auto const& nl : {"\r"s, "\n"s, "\r\n"s})
{
TestScanner scanner{"/// Hello" + nl + "/// World" + nl + "ident"};
auto const& lit = scanner.currentCommentLiteral();
BOOST_CHECK_EQUAL(lit, "Hello\n World");
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "Hello\n World");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "ident");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(irregular_line_breaks_in_single_line_doc_comment)
{
for (auto const& nl: {"\v", "\f", "\xE2\x80\xA8", "\xE2\x80\xA9"})
{
TestScanner scanner("/// abc " + std::string(nl) + " def ");
BOOST_CHECK_EQUAL(scanner.currentCommentLiteral(), "abc ");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
for (size_t i = 0; i < std::string(nl).size() - 1; i++)
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "def");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(regular_line_breaks_in_strings)
{
for (auto const& nl: {"\r"s, "\n"s, "\r\n"s})
{
TestScanner scanner("\"abc " + nl + " def\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "def");
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(irregular_line_breaks_in_strings)
{
for (auto const& nl: {"\v", "\f", "\xE2\x80\xA8", "\xE2\x80\xA9"})
{
TestScanner scanner("\"abc " + std::string(nl) + " def\"");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Illegal);
for (size_t i = 0; i < std::string(nl).size(); i++)
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.currentLiteral(), "def");
BOOST_CHECK_EQUAL(scanner.next(), Token::Illegal);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
}
BOOST_AUTO_TEST_CASE(solidity_keywords)
{
// These are tokens which have a different meaning in Yul.
std::string keywords = "return byte bool address var in true false leave switch case default";
TestScanner scanner(keywords);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Return);
BOOST_CHECK_EQUAL(scanner.next(), Token::Byte);
BOOST_CHECK_EQUAL(scanner.next(), Token::Bool);
BOOST_CHECK_EQUAL(scanner.next(), Token::Address);
BOOST_CHECK_EQUAL(scanner.next(), Token::Var);
BOOST_CHECK_EQUAL(scanner.next(), Token::In);
BOOST_CHECK_EQUAL(scanner.next(), Token::TrueLiteral);
BOOST_CHECK_EQUAL(scanner.next(), Token::FalseLiteral);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Switch);
BOOST_CHECK_EQUAL(scanner.next(), Token::Case);
BOOST_CHECK_EQUAL(scanner.next(), Token::Default);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset(keywords);
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::TrueLiteral);
BOOST_CHECK_EQUAL(scanner.next(), Token::FalseLiteral);
BOOST_CHECK_EQUAL(scanner.next(), Token::Leave);
BOOST_CHECK_EQUAL(scanner.next(), Token::Switch);
BOOST_CHECK_EQUAL(scanner.next(), Token::Case);
BOOST_CHECK_EQUAL(scanner.next(), Token::Default);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(yul_keyword_like)
{
TestScanner scanner("leave.function");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("leave.function");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(yul_identifier_with_dots)
{
TestScanner scanner("mystorage.slot := 1");
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Period);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssemblyAssign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset("mystorage.slot := 1");
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::AssemblyAssign);
BOOST_CHECK_EQUAL(scanner.next(), Token::Number);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(yul_function)
{
std::string sig = "function f(a, b) -> x, y";
TestScanner scanner(sig);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::RParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::RightArrow);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset(sig);
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::RParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::RightArrow);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(yul_function_with_whitespace)
{
std::string sig = "function f (a, b) - > x, y";
TestScanner scanner(sig);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::RParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::GreaterThan);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
scanner.reset(sig);
scanner.scanner->setScannerMode(ScannerKind::Yul);
BOOST_CHECK_EQUAL(scanner.currentToken(), Token::Function);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::LParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::RParen);
BOOST_CHECK_EQUAL(scanner.next(), Token::Sub);
BOOST_CHECK_EQUAL(scanner.next(), Token::GreaterThan);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::Comma);
BOOST_CHECK_EQUAL(scanner.next(), Token::Identifier);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(special_comment_with_invalid_escapes)
{
std::string input(R"("test\x\f\g\u\g\a\u\g\a12\uö\xyoof")");
std::string expectedOutput(R"(test12öyoof)");
CharStream stream(input, "");
Scanner scanner(stream, ScannerKind::SpecialComment);
BOOST_REQUIRE(scanner.currentToken() == Token::StringLiteral);
BOOST_REQUIRE(scanner.currentLiteral() == expectedOutput);
}
BOOST_AUTO_TEST_CASE(special_comment_with_valid_and_invalid_escapes)
{
std::string input(R"("test\n\x61\t\u01A9test\f")");
std::string expectedOutput(R"(test6101A9test)");
CharStream stream(input, "");
Scanner scanner(stream, ScannerKind::SpecialComment);
BOOST_REQUIRE(scanner.currentToken() == Token::StringLiteral);
BOOST_REQUIRE(scanner.currentLiteral() == expectedOutput);
}
BOOST_AUTO_TEST_CASE(special_comment_with_unterminated_escape_sequence_at_eos)
{
CharStream stream(R"("test\)", "");
std::string expectedOutput(R"(test6101A9test)");
Scanner scanner(stream, ScannerKind::SpecialComment);
BOOST_REQUIRE(scanner.currentToken() == Token::Illegal);
BOOST_REQUIRE(scanner.currentError() == ScannerError::IllegalEscapeSequence);
}
BOOST_AUTO_TEST_CASE(special_comment_with_escaped_quotes)
{
CharStream stream(R"("test\\\"")", "");
std::string expectedOutput(R"(test)");
Scanner scanner(stream, ScannerKind::SpecialComment);
BOOST_REQUIRE(scanner.currentToken() == Token::StringLiteral);
BOOST_REQUIRE(scanner.currentLiteral() == expectedOutput);
}
BOOST_AUTO_TEST_CASE(special_comment_with_unterminated_string)
{
CharStream stream(R"("test)", "");
Scanner scanner(stream, ScannerKind::SpecialComment);
BOOST_REQUIRE(scanner.currentToken() == Token::Illegal);
BOOST_REQUIRE(scanner.currentError() == ScannerError::IllegalStringEndQuote);
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 41,505
|
C++
|
.cpp
| 976
| 40.531762
| 100
| 0.743247
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,036
|
Assembler.cpp
|
ethereum_solidity/test/libevmasm/Assembler.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Alex Beregszaszi
* @date 2018
* Tests for the assembler.
*/
#include <test/Common.h>
#include <libevmasm/Assembly.h>
#include <libsolutil/JSON.h>
#include <libevmasm/Disassemble.h>
#include <libyul/Exceptions.h>
#include <test/Common.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <memory>
#include <string>
#include <tuple>
using namespace solidity::langutil;
using namespace solidity::evmasm;
using namespace std::string_literals;
namespace solidity::frontend::test
{
namespace
{
void checkCompilation(evmasm::Assembly const& _assembly)
{
LinkerObject output = _assembly.assemble();
BOOST_CHECK(output.bytecode.size() > 0);
BOOST_CHECK(output.toHex().length() > 0);
}
}
BOOST_AUTO_TEST_SUITE(Assembler)
BOOST_AUTO_TEST_CASE(all_assembly_items)
{
std::map<std::string, unsigned> indices = {
{ "root.asm", 0 },
{ "sub.asm", 1 },
{ "verbatim.asm", 2 }
};
EVMVersion evmVersion = solidity::test::CommonOptions::get().evmVersion();
Assembly _assembly{evmVersion, false, solidity::test::CommonOptions::get().eofVersion(), {}};
auto root_asm = std::make_shared<std::string>("root.asm");
_assembly.setSourceLocation({1, 3, root_asm});
Assembly _subAsm{evmVersion, false, solidity::test::CommonOptions::get().eofVersion(), {}};
auto sub_asm = std::make_shared<std::string>("sub.asm");
_subAsm.setSourceLocation({6, 8, sub_asm});
Assembly _verbatimAsm(evmVersion, true, solidity::test::CommonOptions::get().eofVersion(), "");
auto verbatim_asm = std::make_shared<std::string>("verbatim.asm");
_verbatimAsm.setSourceLocation({8, 18, verbatim_asm});
// PushImmutable
_subAsm.appendImmutable("someImmutable");
_subAsm.append(AssemblyItem(PushTag, 0));
_subAsm.append(Instruction::INVALID);
std::shared_ptr<Assembly> _subAsmPtr = std::make_shared<Assembly>(_subAsm);
_verbatimAsm.appendVerbatim({0xff,0xff}, 0, 0);
_verbatimAsm.appendVerbatim({0x74, 0x65, 0x73, 0x74}, 0, 1);
_verbatimAsm.append(Instruction::MSTORE);
std::shared_ptr<Assembly> _verbatimAsmPtr = std::make_shared<Assembly>(_verbatimAsm);
// Tag
auto tag = _assembly.newTag();
_assembly.append(tag);
// Operation
_assembly.append(u256(1));
_assembly.append(u256(2));
// Push
auto keccak256 = AssemblyItem(Instruction::KECCAK256);
_assembly.m_currentModifierDepth = 1;
_assembly.append(keccak256);
_assembly.m_currentModifierDepth = 0;
// PushProgramSize
_assembly.appendProgramSize();
// PushLibraryAddress
_assembly.appendLibraryAddress("someLibrary");
// PushTag + Operation
_assembly.appendJump(tag);
// PushData
_assembly.append(bytes{0x1, 0x2, 0x3, 0x4});
// PushSubSize
auto sub = _assembly.appendSubroutine(_subAsmPtr);
// PushSub
_assembly.pushSubroutineOffset(static_cast<size_t>(sub.data()));
// PushSubSize
auto verbatim_sub = _assembly.appendSubroutine(_verbatimAsmPtr);
// PushSub
_assembly.pushSubroutineOffset(static_cast<size_t>(verbatim_sub.data()));
// PushDeployTimeAddress
_assembly.append(PushDeployTimeAddress);
// AssignImmutable.
// Note that since there is no reference to "someOtherImmutable", this will just compile to two POPs in the hex output.
_assembly.appendImmutableAssignment("someOtherImmutable");
_assembly.append(u256(2));
_assembly.appendImmutableAssignment("someImmutable");
// Operation
_assembly.append(Instruction::STOP);
_assembly.appendToAuxiliaryData(bytes{0x42, 0x66});
_assembly.appendToAuxiliaryData(bytes{0xee, 0xaa});
_assembly.m_currentModifierDepth = 2;
_assembly.appendJump(tag);
_assembly.m_currentModifierDepth = 0;
checkCompilation(_assembly);
BOOST_CHECK_EQUAL(
_assembly.assemble().toHex(),
"5b6001600220607f73__$bf005014d9d0f534b8fcb268bd84c491a2$__"
"60005660776024604c600760707300000000000000000000000000000000000000005050"
"600260010152"
"006000"
"56fe"
"7f0000000000000000000000000000000000000000000000000000000000000000"
"6000feffff7465737452010203044266eeaa"
);
BOOST_CHECK_EQUAL(
_assembly.assemblyString(),
" /* \"root.asm\":1:3 */\n"
"tag_1:\n"
" keccak256(0x02, 0x01)\n"
" bytecodeSize\n"
" linkerSymbol(\"bf005014d9d0f534b8fcb268bd84c491a2380f4acd260d1ccfe9cd8201f7e994\")\n"
" jump(tag_1)\n"
" data_a6885b3731702da62e8e4a8f584ac46a7f6822f4e2ba50fba902f67b1588d23b\n"
" dataSize(sub_0)\n"
" dataOffset(sub_0)\n"
" dataSize(sub_1)\n"
" dataOffset(sub_1)\n"
" deployTimeAddress()\n"
" assignImmutable(\"0xc3978657661c4d8e32e3d5f42597c009f0d3859e9f9d0d94325268f9799e2bfb\")\n"
" 0x02\n"
" assignImmutable(\"0x26f2c0195e9d408feff3abd77d83f2971f3c9a18d1e8a9437c7835ae4211fc9f\")\n"
" stop\n"
" jump(tag_1)\n"
"stop\n"
"data_a6885b3731702da62e8e4a8f584ac46a7f6822f4e2ba50fba902f67b1588d23b 01020304\n"
"\n"
"sub_0: assembly {\n"
" /* \"sub.asm\":6:8 */\n"
" immutable(\"0x26f2c0195e9d408feff3abd77d83f2971f3c9a18d1e8a9437c7835ae4211fc9f\")\n"
" tag_0\n"
" invalid\n"
"}\n"
"\n"
"sub_1: assembly {\n"
" /* \"verbatim.asm\":8:18 */\n"
" verbatimbytecode_ffff\n"
" verbatimbytecode_74657374\n"
" mstore\n"
"}\n"
"\n"
"auxdata: 0x4266eeaa\n"
);
std::string json{
"{\".auxdata\":\"4266eeaa\",\".code\":["
"{\"begin\":1,\"end\":3,\"name\":\"tag\",\"source\":0,\"value\":\"1\"},"
"{\"begin\":1,\"end\":3,\"name\":\"JUMPDEST\",\"source\":0},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"1\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"2\"},"
"{\"begin\":1,\"end\":3,\"modifierDepth\":1,\"name\":\"KECCAK256\",\"source\":0},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSHSIZE\",\"source\":0},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSHLIB\",\"source\":0,\"value\":\"someLibrary\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH [tag]\",\"source\":0,\"value\":\"1\"},"
"{\"begin\":1,\"end\":3,\"name\":\"JUMP\",\"source\":0},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH data\",\"source\":0,\"value\":\"A6885B3731702DA62E8E4A8F584AC46A7F6822F4E2BA50FBA902F67B1588D23B\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH #[$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH [$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH #[$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000001\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH [$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000001\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSHDEPLOYADDRESS\",\"source\":0},"
"{\"begin\":1,\"end\":3,\"name\":\"ASSIGNIMMUTABLE\",\"source\":0,\"value\":\"someOtherImmutable\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"2\"},"
"{\"begin\":1,\"end\":3,\"name\":\"ASSIGNIMMUTABLE\",\"source\":0,\"value\":\"someImmutable\"},"
"{\"begin\":1,\"end\":3,\"name\":\"STOP\",\"source\":0},"
"{\"begin\":1,\"end\":3,\"modifierDepth\":2,\"name\":\"PUSH [tag]\",\"source\":0,\"value\":\"1\"},{\"begin\":1,\"end\":3,\"modifierDepth\":2,\"name\":\"JUMP\",\"source\":0}"
"],\".data\":{\"0\":{\".code\":["
"{\"begin\":6,\"end\":8,\"name\":\"PUSHIMMUTABLE\",\"source\":1,\"value\":\"someImmutable\"},"
"{\"begin\":6,\"end\":8,\"name\":\"PUSH [ErrorTag]\",\"source\":1},"
"{\"begin\":6,\"end\":8,\"name\":\"INVALID\",\"source\":1}"
"]},"
"\"1\":{\".code\":["
"{\"begin\":8,\"end\":18,\"name\":\"VERBATIM\",\"source\":2,\"value\":\"ffff\"},"
"{\"begin\":8,\"end\":18,\"name\":\"VERBATIM\",\"source\":2,\"value\":\"74657374\"},"
"{\"begin\":8,\"end\":18,\"name\":\"MSTORE\",\"source\":2}"
"]},\"A6885B3731702DA62E8E4A8F584AC46A7F6822F4E2BA50FBA902F67B1588D23B\":\"01020304\"},\"sourceList\":[\"root.asm\",\"sub.asm\",\"verbatim.asm\"]}"
};
Json jsonValue;
BOOST_CHECK(util::jsonParseStrict(json, jsonValue));
BOOST_CHECK_EQUAL(util::jsonCompactPrint(_assembly.assemblyJSON(indices)), util::jsonCompactPrint(jsonValue));
}
BOOST_AUTO_TEST_CASE(immutables_and_its_source_maps)
{
EVMVersion evmVersion = solidity::test::CommonOptions::get().evmVersion();
// Tests for 1, 2, 3 number of immutables.
for (int numImmutables = 1; numImmutables <= 3; ++numImmutables)
{
BOOST_TEST_MESSAGE("NumImmutables: "s + std::to_string(numImmutables));
// Tests for the cases 1, 2, 3 occurrences of an immutable reference.
for (int numActualRefs = 1; numActualRefs <= 3; ++numActualRefs)
{
BOOST_TEST_MESSAGE("NumActualRefs: "s + std::to_string(numActualRefs));
auto const NumExpectedMappings =
(
2 + // PUSH <a> PUSH <b>
(numActualRefs - 1) * 5 + // DUP DUP PUSH <n> ADD MSTORE
3 // PUSH <n> ADD MSTORE
) * numImmutables;
auto constexpr NumSubs = 1;
auto constexpr NumOpcodesWithoutMappings =
NumSubs + // PUSH <addr> for every sub assembly
1; // INVALID
auto assemblyName = std::make_shared<std::string>("root.asm");
auto subName = std::make_shared<std::string>("sub.asm");
std::map<std::string, unsigned> indices = {
{ *assemblyName, 0 },
{ *subName, 1 }
};
auto subAsm = std::make_shared<Assembly>(evmVersion, false, solidity::test::CommonOptions::get().eofVersion(), std::string{});
for (char i = 0; i < numImmutables; ++i)
{
for (int r = 0; r < numActualRefs; ++r)
{
subAsm->setSourceLocation(SourceLocation{10*i, 10*i + 6 + r, subName});
subAsm->appendImmutable(std::string(1, char('a' + i))); // "a", "b", ...
}
}
Assembly assembly{evmVersion, true, solidity::test::CommonOptions::get().eofVersion(), {}};
for (char i = 1; i <= numImmutables; ++i)
{
assembly.setSourceLocation({10*i, 10*i + 3+i, assemblyName});
assembly.append(u256(0x71)); // immutble value
assembly.append(u256(0)); // target... modules?
assembly.appendImmutableAssignment(std::string(1, char('a' + i - 1)));
}
assembly.appendSubroutine(subAsm);
checkCompilation(assembly);
BOOST_REQUIRE(assembly.codeSections().size() == 1);
std::string const sourceMappings = AssemblyItem::computeSourceMapping(assembly.codeSections().at(0).items, indices);
auto const numberOfMappings = std::count(sourceMappings.begin(), sourceMappings.end(), ';');
LinkerObject const& obj = assembly.assemble();
std::string const disassembly = disassemble(obj.bytecode, evmVersion, "\n");
auto const numberOfOpcodes = std::count(disassembly.begin(), disassembly.end(), '\n');
#if 0 // {{{ debug prints
{
LinkerObject const& subObj = assembly.sub(0).assemble();
std::string const subDisassembly = disassemble(subObj.bytecode, "\n");
std::cout << '\n';
std::cout << "### immutables: " << numImmutables << ", refs: " << numActualRefs << '\n';
std::cout << " - srcmap: \"" << sourceMappings << "\"\n";
std::cout << " - src mappings: " << numberOfMappings << '\n';
std::cout << " - opcodes: " << numberOfOpcodes << '\n';
std::cout << " - subs: " << assembly.numSubs() << '\n';
std::cout << " - sub opcodes " << std::count(subDisassembly.begin(), subDisassembly.end(), '\n') << '\n';
std::cout << " - sub srcmaps " << AssemblyItem::computeSourceMapping(subAsm->items(), indices) << '\n';
std::cout << " - main bytecode:\n\t" << disassemble(obj.bytecode, "\n\t");
std::cout << "\r - sub bytecode:\n\t" << disassemble(subObj.bytecode, "\n\t");
}
#endif // }}}
BOOST_REQUIRE_EQUAL(NumExpectedMappings, numberOfMappings);
BOOST_REQUIRE_EQUAL(NumExpectedMappings, numberOfOpcodes - NumOpcodesWithoutMappings);
}
}
}
BOOST_AUTO_TEST_CASE(immutable)
{
std::map<std::string, unsigned> indices = {
{ "root.asm", 0 },
{ "sub.asm", 1 }
};
EVMVersion evmVersion = solidity::test::CommonOptions::get().evmVersion();
Assembly _assembly{evmVersion, true, solidity::test::CommonOptions::get().eofVersion(), {}};
auto root_asm = std::make_shared<std::string>("root.asm");
_assembly.setSourceLocation({1, 3, root_asm});
Assembly _subAsm{evmVersion, false, solidity::test::CommonOptions::get().eofVersion(), {}};
auto sub_asm = std::make_shared<std::string>("sub.asm");
_subAsm.setSourceLocation({6, 8, sub_asm});
_subAsm.appendImmutable("someImmutable");
_subAsm.appendImmutable("someOtherImmutable");
_subAsm.appendImmutable("someImmutable");
std::shared_ptr<Assembly> _subAsmPtr = std::make_shared<Assembly>(_subAsm);
_assembly.append(u256(42));
_assembly.append(u256(0));
_assembly.appendImmutableAssignment("someImmutable");
_assembly.append(u256(23));
_assembly.append(u256(0));
_assembly.appendImmutableAssignment("someOtherImmutable");
auto sub = _assembly.appendSubroutine(_subAsmPtr);
_assembly.pushSubroutineOffset(static_cast<size_t>(sub.data()));
checkCompilation(_assembly);
std::string genericPush0 = evmVersion.hasPush0() ? "5f" : "6000";
// PUSH1 0x1b v/s PUSH1 0x19
std::string dataOffset = evmVersion.hasPush0() ? "6019" : "601b" ;
BOOST_CHECK_EQUAL(
_assembly.assemble().toHex(),
// root.asm
// assign "someImmutable"
"602a" + // PUSH1 42 - value for someImmutable
genericPush0 + // PUSH1 0 - offset of code into which to insert the immutable
"8181" // DUP2 DUP2
"6001" // PUSH1 1 - offset of first someImmutable in sub_0
"01" // ADD - add offset of immutable to offset of code
"52" // MSTORE
"6043" // PUSH1 67 - offset of second someImmutable in sub_0
"01" // ADD - add offset of immutable to offset of code
"52" // MSTORE
// assign "someOtherImmutable"
"6017" + // PUSH1 23 - value for someOtherImmutable
genericPush0 + // PUSH1 0 - offset of code into which to insert the immutable
"6022" // PUSH1 34 - offset of someOtherImmutable in sub_0
"01" // ADD - add offset of immutable to offset of code
"52" // MSTORE
"6063" + // PUSH1 0x63 - dataSize(sub_0)
dataOffset + // PUSH1 0x23 - dataOffset(sub_0)
"fe" // INVALID
// end of root.asm
// sub.asm
"7f0000000000000000000000000000000000000000000000000000000000000000" // PUSHIMMUTABLE someImmutable - data at offset 1
"7f0000000000000000000000000000000000000000000000000000000000000000" // PUSHIMMUTABLE someOtherImmutable - data at offset 34
"7f0000000000000000000000000000000000000000000000000000000000000000" // PUSHIMMUTABLE someImmutable - data at offset 67
);
BOOST_CHECK_EQUAL(
_assembly.assemblyString(),
" /* \"root.asm\":1:3 */\n"
" 0x2a\n"
" 0x00\n"
" assignImmutable(\"0x26f2c0195e9d408feff3abd77d83f2971f3c9a18d1e8a9437c7835ae4211fc9f\")\n"
" 0x17\n"
" 0x00\n"
" assignImmutable(\"0xc3978657661c4d8e32e3d5f42597c009f0d3859e9f9d0d94325268f9799e2bfb\")\n"
" dataSize(sub_0)\n"
" dataOffset(sub_0)\n"
"stop\n"
"\n"
"sub_0: assembly {\n"
" /* \"sub.asm\":6:8 */\n"
" immutable(\"0x26f2c0195e9d408feff3abd77d83f2971f3c9a18d1e8a9437c7835ae4211fc9f\")\n"
" immutable(\"0xc3978657661c4d8e32e3d5f42597c009f0d3859e9f9d0d94325268f9799e2bfb\")\n"
" immutable(\"0x26f2c0195e9d408feff3abd77d83f2971f3c9a18d1e8a9437c7835ae4211fc9f\")\n"
"}\n"
);
BOOST_CHECK_EQUAL(
util::jsonCompactPrint(_assembly.assemblyJSON(indices)),
"{\".code\":["
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"2A\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"0\"},"
"{\"begin\":1,\"end\":3,\"name\":\"ASSIGNIMMUTABLE\",\"source\":0,\"value\":\"someImmutable\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"17\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH\",\"source\":0,\"value\":\"0\"},"
"{\"begin\":1,\"end\":3,\"name\":\"ASSIGNIMMUTABLE\",\"source\":0,\"value\":\"someOtherImmutable\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH #[$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"
"{\"begin\":1,\"end\":3,\"name\":\"PUSH [$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"}"
"],\".data\":{\"0\":{\".code\":["
"{\"begin\":6,\"end\":8,\"name\":\"PUSHIMMUTABLE\",\"source\":1,\"value\":\"someImmutable\"},"
"{\"begin\":6,\"end\":8,\"name\":\"PUSHIMMUTABLE\",\"source\":1,\"value\":\"someOtherImmutable\"},"
"{\"begin\":6,\"end\":8,\"name\":\"PUSHIMMUTABLE\",\"source\":1,\"value\":\"someImmutable\"}"
"]}},\"sourceList\":[\"root.asm\",\"sub.asm\"]}"
);
}
BOOST_AUTO_TEST_CASE(subobject_encode_decode)
{
EVMVersion evmVersion = solidity::test::CommonOptions::get().evmVersion();
Assembly assembly{evmVersion, true, solidity::test::CommonOptions::get().eofVersion(), {}};
std::shared_ptr<Assembly> subAsmPtr = std::make_shared<Assembly>(evmVersion, false, solidity::test::CommonOptions::get().eofVersion(), std::string{});
std::shared_ptr<Assembly> subSubAsmPtr = std::make_shared<Assembly>(evmVersion, false, solidity::test::CommonOptions::get().eofVersion(), std::string{});
assembly.appendSubroutine(subAsmPtr);
subAsmPtr->appendSubroutine(subSubAsmPtr);
BOOST_CHECK(assembly.encodeSubPath({0}) == 0);
BOOST_REQUIRE_THROW(assembly.encodeSubPath({1}), solidity::evmasm::AssemblyException);
BOOST_REQUIRE_THROW(assembly.decodeSubPath(1), solidity::evmasm::AssemblyException);
std::vector<size_t> subPath{0, 0};
BOOST_CHECK(assembly.decodeSubPath(assembly.encodeSubPath(subPath)) == subPath);
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 18,153
|
C++
|
.cpp
| 382
| 44.712042
| 175
| 0.67511
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,039
|
Mutations.cpp
|
ethereum_solidity/tools/yulPhaser/Mutations.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <tools/yulPhaser/Mutations.h>
#include <tools/yulPhaser/SimulationRNG.h>
#include <libsolutil/CommonData.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <vector>
using namespace solidity;
using namespace solidity::phaser;
std::function<Mutation> phaser::geneRandomisation(double _chance)
{
return [=](Chromosome const& _chromosome)
{
std::string genes;
for (char gene: _chromosome.genes())
genes.push_back(
SimulationRNG::bernoulliTrial(_chance) ?
Chromosome::randomGene() :
gene
);
return Chromosome(std::move(genes));
};
}
std::function<Mutation> phaser::geneDeletion(double _chance)
{
return [=](Chromosome const& _chromosome)
{
std::string genes;
for (char gene: _chromosome.genes())
if (!SimulationRNG::bernoulliTrial(_chance))
genes.push_back(gene);
return Chromosome(std::move(genes));
};
}
std::function<Mutation> phaser::geneAddition(double _chance)
{
return [=](Chromosome const& _chromosome)
{
std::string genes;
if (SimulationRNG::bernoulliTrial(_chance))
genes.push_back(Chromosome::randomGene());
for (char gene: _chromosome.genes())
{
genes.push_back(gene);
if (SimulationRNG::bernoulliTrial(_chance))
genes.push_back(Chromosome::randomGene());
}
return Chromosome(std::move(genes));
};
}
std::function<Mutation> phaser::alternativeMutations(
double _firstMutationChance,
std::function<Mutation> _mutation1,
std::function<Mutation> _mutation2
)
{
return [=](Chromosome const& _chromosome)
{
if (SimulationRNG::bernoulliTrial(_firstMutationChance))
return _mutation1(_chromosome);
else
return _mutation2(_chromosome);
};
}
std::function<Mutation> phaser::mutationSequence(std::vector<std::function<Mutation>> _mutations)
{
return [=](Chromosome const& _chromosome)
{
Chromosome mutatedChromosome = _chromosome;
for (size_t i = 0; i < _mutations.size(); ++i)
mutatedChromosome = _mutations[i](std::move(mutatedChromosome));
return mutatedChromosome;
};
}
namespace
{
ChromosomePair fixedPointSwap(
Chromosome const& _chromosome1,
Chromosome const& _chromosome2,
size_t _crossoverPoint
)
{
assert(_crossoverPoint <= _chromosome1.length());
assert(_crossoverPoint <= _chromosome2.length());
return {
Chromosome(
_chromosome1.genes().substr(0, _crossoverPoint) +
_chromosome2.genes().substr(_crossoverPoint, _chromosome2.length() - _crossoverPoint)
),
Chromosome(
_chromosome2.genes().substr(0, _crossoverPoint) +
_chromosome1.genes().substr(_crossoverPoint, _chromosome1.length() - _crossoverPoint)
),
};
}
}
std::function<Crossover> phaser::randomPointCrossover()
{
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t minLength = std::min(_chromosome1.length(), _chromosome2.length());
// Don't use position 0 (because this just swaps the values) unless it's the only choice.
size_t minPoint = (minLength > 0 ? 1 : 0);
assert(minPoint <= minLength);
size_t randomPoint = SimulationRNG::uniformInt(minPoint, minLength);
return std::get<0>(fixedPointSwap(_chromosome1, _chromosome2, randomPoint));
};
}
std::function<SymmetricCrossover> phaser::symmetricRandomPointCrossover()
{
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t minLength = std::min(_chromosome1.length(), _chromosome2.length());
// Don't use position 0 (because this just swaps the values) unless it's the only choice.
size_t minPoint = (minLength > 0 ? 1 : 0);
assert(minPoint <= minLength);
size_t randomPoint = SimulationRNG::uniformInt(minPoint, minLength);
return fixedPointSwap(_chromosome1, _chromosome2, randomPoint);
};
}
std::function<Crossover> phaser::fixedPointCrossover(double _crossoverPoint)
{
assert(0.0 <= _crossoverPoint && _crossoverPoint <= 1.0);
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t minLength = std::min(_chromosome1.length(), _chromosome2.length());
size_t concretePoint = static_cast<size_t>(std::round(double(minLength) * _crossoverPoint));
return std::get<0>(fixedPointSwap(_chromosome1, _chromosome2, concretePoint));
};
}
namespace
{
ChromosomePair fixedTwoPointSwap(
Chromosome const& _chromosome1,
Chromosome const& _chromosome2,
size_t _crossoverPoint1,
size_t _crossoverPoint2
)
{
assert(_crossoverPoint1 <= _chromosome1.length());
assert(_crossoverPoint1 <= _chromosome2.length());
assert(_crossoverPoint2 <= _chromosome1.length());
assert(_crossoverPoint2 <= _chromosome2.length());
size_t lowPoint = std::min(_crossoverPoint1, _crossoverPoint2);
size_t highPoint = std::max(_crossoverPoint1, _crossoverPoint2);
return {
Chromosome(
_chromosome1.genes().substr(0, lowPoint) +
_chromosome2.genes().substr(lowPoint, highPoint - lowPoint) +
_chromosome1.genes().substr(highPoint, _chromosome1.length() - highPoint)
),
Chromosome(
_chromosome2.genes().substr(0, lowPoint) +
_chromosome1.genes().substr(lowPoint, highPoint - lowPoint) +
_chromosome2.genes().substr(highPoint, _chromosome2.length() - highPoint)
),
};
}
}
std::function<Crossover> phaser::randomTwoPointCrossover()
{
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t minLength = std::min(_chromosome1.length(), _chromosome2.length());
// Don't use position 0 (because this just swaps the values) unless it's the only choice.
size_t minPoint = (minLength > 0 ? 1 : 0);
assert(minPoint <= minLength);
size_t randomPoint1 = SimulationRNG::uniformInt(minPoint, minLength);
size_t randomPoint2 = SimulationRNG::uniformInt(randomPoint1, minLength);
return std::get<0>(fixedTwoPointSwap(_chromosome1, _chromosome2, randomPoint1, randomPoint2));
};
}
std::function<SymmetricCrossover> phaser::symmetricRandomTwoPointCrossover()
{
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t minLength = std::min(_chromosome1.length(), _chromosome2.length());
// Don't use position 0 (because this just swaps the values) unless it's the only choice.
size_t minPoint = (minLength > 0 ? 1 : 0);
assert(minPoint <= minLength);
size_t randomPoint1 = SimulationRNG::uniformInt(minPoint, minLength);
size_t randomPoint2 = SimulationRNG::uniformInt(randomPoint1, minLength);
return fixedTwoPointSwap(_chromosome1, _chromosome2, randomPoint1, randomPoint2);
};
}
namespace
{
ChromosomePair uniformSwap(Chromosome const& _chromosome1, Chromosome const& _chromosome2, double _swapChance)
{
std::string steps1;
std::string steps2;
size_t minLength = std::min(_chromosome1.length(), _chromosome2.length());
for (size_t i = 0; i < minLength; ++i)
if (SimulationRNG::bernoulliTrial(_swapChance))
{
steps1.push_back(_chromosome2.genes()[i]);
steps2.push_back(_chromosome1.genes()[i]);
}
else
{
steps1.push_back(_chromosome1.genes()[i]);
steps2.push_back(_chromosome2.genes()[i]);
}
bool swapTail = SimulationRNG::bernoulliTrial(_swapChance);
if (_chromosome1.length() > minLength)
{
if (swapTail)
steps2 += _chromosome1.genes().substr(minLength, _chromosome1.length() - minLength);
else
steps1 += _chromosome1.genes().substr(minLength, _chromosome1.length() - minLength);
}
if (_chromosome2.length() > minLength)
{
if (swapTail)
steps1 += _chromosome2.genes().substr(minLength, _chromosome2.length() - minLength);
else
steps2 += _chromosome2.genes().substr(minLength, _chromosome2.length() - minLength);
}
return {Chromosome(steps1), Chromosome(steps2)};
}
}
std::function<Crossover> phaser::uniformCrossover(double _swapChance)
{
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
return std::get<0>(uniformSwap(_chromosome1, _chromosome2, _swapChance));
};
}
std::function<SymmetricCrossover> phaser::symmetricUniformCrossover(double _swapChance)
{
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
return uniformSwap(_chromosome1, _chromosome2, _swapChance);
};
}
| 8,724
|
C++
|
.cpp
| 250
| 32.428
| 110
| 0.74816
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,040
|
main.cpp
|
ethereum_solidity/tools/yulPhaser/main.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <tools/yulPhaser/Exceptions.h>
#include <tools/yulPhaser/Phaser.h>
#include <libsolutil/Exceptions.h>
#include <iostream>
int main(int argc, char** argv)
{
try
{
solidity::phaser::Phaser::main(argc, argv);
return 0;
}
catch (boost::program_options::error const& exception)
{
// Bad input data. Invalid command-line parameters.
std::cerr << std::endl;
std::cerr << "ERROR: " << exception.what() << std::endl;
return 2;
}
catch (solidity::phaser::BadInput const& exception)
{
// Bad input data. Syntax errors in the input program, semantic errors in command-line
// parameters, etc.
std::cerr << std::endl;
std::cerr << "ERROR: " << exception.what() << std::endl;
return 2;
}
catch (...)
{
std::cerr << "Uncaught exception:" << std::endl;
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
return 2;
}
}
| 1,568
|
C++
|
.cpp
| 47
| 31.085106
| 88
| 0.730159
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,042
|
Program.cpp
|
ethereum_solidity/tools/yulPhaser/Program.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <tools/yulPhaser/Program.h>
#include <liblangutil/CharStream.h>
#include <liblangutil/ErrorReporter.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/AsmJsonConverter.h>
#include <libyul/AsmParser.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <libyul/ObjectParser.h>
#include <libyul/YulName.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/optimiser/Disambiguator.h>
#include <libyul/optimiser/ForLoopInitRewriter.h>
#include <libyul/optimiser/FunctionGrouper.h>
#include <libyul/optimiser/FunctionHoister.h>
#include <libyul/optimiser/Metrics.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/Suite.h>
#include <libsolutil/JSON.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <cassert>
#include <memory>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::util;
using namespace solidity::phaser;
namespace solidity::phaser
{
std::ostream& operator<<(std::ostream& _stream, Program const& _program);
}
Program::Program(Program const& program):
m_ast(std::make_unique<AST>(std::get<Block>(ASTCopier{}(program.m_ast->root())))),
m_dialect{program.m_dialect},
m_nameDispenser(program.m_nameDispenser)
{
}
std::variant<Program, ErrorList> Program::load(CharStream& _sourceCode)
{
// ASSUMPTION: parseSource() rewinds the stream on its own
// TODO: Add support for EOF
Dialect const& dialect = EVMDialect::strictAssemblyForEVMObjects(EVMVersion{}, std::nullopt);
std::variant<std::unique_ptr<AST>, ErrorList> astOrErrors = parseObject(dialect, _sourceCode);
if (std::holds_alternative<ErrorList>(astOrErrors))
return std::get<ErrorList>(astOrErrors);
std::variant<std::unique_ptr<AsmAnalysisInfo>, ErrorList> analysisInfoOrErrors = analyzeAST(
dialect,
*std::get<std::unique_ptr<AST>>(astOrErrors)
);
if (std::holds_alternative<ErrorList>(analysisInfoOrErrors))
return std::get<ErrorList>(analysisInfoOrErrors);
Program program(
dialect,
disambiguateAST(
dialect,
*std::get<std::unique_ptr<AST>>(astOrErrors),
*std::get<std::unique_ptr<AsmAnalysisInfo>>(analysisInfoOrErrors)
)
);
program.optimise({
FunctionHoister::name,
FunctionGrouper::name,
ForLoopInitRewriter::name,
});
return program;
}
void Program::optimise(std::vector<std::string> const& _optimisationSteps)
{
m_ast = applyOptimisationSteps(m_dialect, m_nameDispenser, std::move(m_ast), _optimisationSteps);
}
std::ostream& phaser::operator<<(std::ostream& _stream, Program const& _program)
{
return _stream << AsmPrinter(_program.m_dialect)(_program.m_ast->root());
}
std::string Program::toJson() const
{
Json serializedAst = AsmJsonConverter(m_dialect, 0)(m_ast->root());
return jsonPrettyPrint(removeNullMembers(std::move(serializedAst)));
}
std::variant<std::unique_ptr<AST>, ErrorList> Program::parseObject(Dialect const& _dialect, CharStream _source)
{
ErrorList errors;
ErrorReporter errorReporter(errors);
auto scanner = std::make_shared<Scanner>(_source);
ObjectParser parser(errorReporter, _dialect);
std::shared_ptr<Object> object = parser.parse(scanner, false);
if (object == nullptr || errorReporter.hasErrors())
// NOTE: It's possible to get errors even if the returned object is non-null.
// For example when there are errors in a nested object.
return errors;
Object* deployedObject = nullptr;
if (object->subObjects.size() > 0)
for (auto& subObject: object->subObjects)
// solc --ir produces an object with a subobject of the same name as the outer object
// but suffixed with "_deployed".
// The other object references the nested one which makes analysis fail. Below we try to
// extract just the nested one for that reason. This is just a heuristic. If there's no
// subobject with such a suffix we fall back to accepting the whole object as is.
if (subObject != nullptr && subObject->name == object->name + "_deployed")
{
deployedObject = dynamic_cast<Object*>(subObject.get());
if (deployedObject != nullptr)
break;
}
Object* selectedObject = (deployedObject != nullptr ? deployedObject : object.get());
// NOTE: I'm making a copy of the whole AST to get unique_ptr rather than shared_ptr.
// This is a slight performance hit but it's much less than the parsing itself.
// unique_ptr lets me be sure that two Program instances can never share the AST by mistake.
// The public API of the class does not provide access to the smart pointer so it won't be hard
// to switch to shared_ptr if the copying turns out to be an issue (though it would be better
// to refactor ObjectParser and Object to use unique_ptr instead).
auto astCopy = std::make_unique<AST>(std::get<Block>(ASTCopier{}(selectedObject->code()->root())));
return std::variant<std::unique_ptr<AST>, ErrorList>(std::move(astCopy));
}
std::variant<std::unique_ptr<AsmAnalysisInfo>, ErrorList> Program::analyzeAST(Dialect const& _dialect, AST const& _ast)
{
ErrorList errors;
ErrorReporter errorReporter(errors);
auto analysisInfo = std::make_unique<AsmAnalysisInfo>();
AsmAnalyzer analyzer(*analysisInfo, errorReporter, _dialect);
bool analysisSuccessful = analyzer.analyze(_ast.root());
if (!analysisSuccessful)
return errors;
assert(!errorReporter.hasErrors());
return std::variant<std::unique_ptr<AsmAnalysisInfo>, ErrorList>(std::move(analysisInfo));
}
std::unique_ptr<AST> Program::disambiguateAST(
Dialect const& _dialect,
AST const& _ast,
AsmAnalysisInfo const& _analysisInfo
)
{
std::set<YulName> const externallyUsedIdentifiers = {};
Disambiguator disambiguator(_dialect, _analysisInfo, externallyUsedIdentifiers);
return std::make_unique<AST>(std::get<Block>(disambiguator(_ast.root())));
}
std::unique_ptr<AST> Program::applyOptimisationSteps(
Dialect const& _dialect,
NameDispenser& _nameDispenser,
std::unique_ptr<AST> _ast,
std::vector<std::string> const& _optimisationSteps
)
{
// An empty set of reserved identifiers. It could be a constructor parameter but I don't
// think it would be useful in this tool. Other tools (like yulopti) have it empty too.
std::set<YulName> const externallyUsedIdentifiers = {};
OptimiserStepContext context{
_dialect,
_nameDispenser,
externallyUsedIdentifiers,
frontend::OptimiserSettings::standard().expectedExecutionsPerDeployment
};
auto astRoot = std::get<Block>(ASTCopier{}(_ast->root()));
for (std::string const& step: _optimisationSteps)
OptimiserSuite::allSteps().at(step)->run(context, astRoot);
return std::make_unique<AST>(std::move(astRoot));
}
size_t Program::computeCodeSize(Block const& _ast, CodeWeights const& _weights)
{
return CodeSize::codeSizeIncludingFunctions(_ast, _weights);
}
| 7,452
|
C++
|
.cpp
| 176
| 40.221591
| 119
| 0.769199
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,047
|
Chromosome.cpp
|
ethereum_solidity/tools/yulPhaser/Chromosome.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <tools/yulPhaser/Chromosome.h>
#include <tools/yulPhaser/SimulationRNG.h>
#include <libyul/optimiser/Suite.h>
#include <libsolutil/CommonData.h>
#include <sstream>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::phaser;
namespace solidity::phaser
{
std::ostream& operator<<(std::ostream& _stream, Chromosome const& _chromosome);
}
Chromosome Chromosome::makeRandom(size_t _length)
{
std::vector<std::string> steps;
for (size_t i = 0; i < _length; ++i)
steps.push_back(randomOptimisationStep());
return Chromosome(std::move(steps));
}
std::ostream& phaser::operator<<(std::ostream& _stream, Chromosome const& _chromosome)
{
return _stream << _chromosome.m_genes;
}
std::vector<std::string> Chromosome::allStepNames()
{
std::vector<std::string> stepNames;
for (auto const& step: OptimiserSuite::allSteps())
stepNames.push_back(step.first);
return stepNames;
}
std::string const& Chromosome::randomOptimisationStep()
{
static std::vector<std::string> stepNames = allStepNames();
return stepNames[SimulationRNG::uniformInt(0, stepNames.size() - 1)];
}
char Chromosome::randomGene()
{
return OptimiserSuite::stepNameToAbbreviationMap().at(randomOptimisationStep());
}
std::string Chromosome::stepsToGenes(std::vector<std::string> const& _optimisationSteps)
{
std::string genes;
for (std::string const& stepName: _optimisationSteps)
genes.push_back(OptimiserSuite::stepNameToAbbreviationMap().at(stepName));
return genes;
}
std::vector<std::string> Chromosome::genesToSteps(std::string const& _genes)
{
std::vector<std::string> steps;
for (char abbreviation: _genes)
steps.push_back(OptimiserSuite::stepAbbreviationToNameMap().at(abbreviation));
return steps;
}
| 2,429
|
C++
|
.cpp
| 67
| 34.38806
| 88
| 0.780248
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,052
|
FunctionReferenceResolver.cpp
|
ethereum_solidity/libyul/FunctionReferenceResolver.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/FunctionReferenceResolver.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
#include <range/v3/view/reverse.hpp>
using namespace solidity::yul;
using namespace solidity::util;
FunctionReferenceResolver::FunctionReferenceResolver(Block const& _ast)
{
(*this)(_ast);
yulAssert(m_scopes.empty());
}
void FunctionReferenceResolver::operator()(FunctionCall const& _functionCall)
{
for (auto&& scope: m_scopes | ranges::views::reverse)
if (FunctionDefinition const** function = util::valueOrNullptr(scope, _functionCall.functionName.name))
{
m_functionReferences[&_functionCall] = *function;
break;
}
// If we did not find anything, it was a builtin call.
ASTWalker::operator()(_functionCall);
}
void FunctionReferenceResolver::operator()(Block const& _block)
{
m_scopes.emplace_back();
for (auto const& statement: _block.statements)
if (auto const* function = std::get_if<FunctionDefinition>(&statement))
m_scopes.back()[function->name] = function;
ASTWalker::operator()(_block);
m_scopes.pop_back();
}
| 1,749
|
C++
|
.cpp
| 45
| 36.733333
| 105
| 0.773373
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,053
|
YulStack.cpp
|
ethereum_solidity/libyul/YulStack.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/YulStack.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/backends/evm/SSAControlFlowGraphBuilder.h>
#include <libyul/backends/evm/EthAssemblyAdapter.h>
#include <libyul/backends/evm/EVMCodeTransform.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/EVMObjectCompiler.h>
#include <libyul/ObjectParser.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/Suite.h>
#include <libyul/YulControlFlowGraphExporter.h>
#include <libevmasm/Assembly.h>
#include <liblangutil/Scanner.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <boost/algorithm/string.hpp>
#include <optional>
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::yul;
using namespace solidity::langutil;
using namespace solidity::util;
CharStream const& YulStack::charStream(std::string const& _sourceName) const
{
yulAssert(m_charStream, "");
yulAssert(m_charStream->name() == _sourceName, "");
return *m_charStream;
}
bool YulStack::parse(std::string const& _sourceName, std::string const& _source)
{
yulAssert(m_stackState == Empty);
try
{
m_charStream = std::make_unique<CharStream>(_source, _sourceName);
std::shared_ptr<Scanner> scanner = std::make_shared<Scanner>(*m_charStream);
m_parserResult = ObjectParser(m_errorReporter, languageToDialect(m_language, m_evmVersion, m_eofVersion)).parse(scanner, false);
}
catch (UnimplementedFeatureError const& _error)
{
reportUnimplementedFeatureError(_error);
}
if (!m_errorReporter.hasErrors())
m_stackState = Parsed;
return m_stackState == Parsed;
}
bool YulStack::parseAndAnalyze(std::string const& _sourceName, std::string const& _source)
{
m_errors.clear();
yulAssert(m_stackState == Empty);
if (!parse(_sourceName, _source))
return false;
yulAssert(m_stackState == Parsed);
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode());
return analyzeParsed();
}
void YulStack::optimize()
{
yulAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful.");
yulAssert(m_parserResult);
try
{
if (
!m_optimiserSettings.runYulOptimiser &&
yul::MSizeFinder::containsMSize(languageToDialect(m_language, m_evmVersion, m_eofVersion), *m_parserResult)
)
return;
auto [optimizeStackAllocation, yulOptimiserSteps, yulOptimiserCleanupSteps] = [&]() -> std::tuple<bool, std::string, std::string>
{
if (!m_optimiserSettings.runYulOptimiser)
{
// Yul optimizer disabled, but empty sequence (:) explicitly provided
if (OptimiserSuite::isEmptyOptimizerSequence(m_optimiserSettings.yulOptimiserSteps + ":" + m_optimiserSettings.yulOptimiserCleanupSteps))
return std::make_tuple(true, "", "");
// Yul optimizer disabled, and no sequence explicitly provided (assumes default sequence)
else
{
yulAssert(
m_optimiserSettings.yulOptimiserSteps == OptimiserSettings::DefaultYulOptimiserSteps &&
m_optimiserSettings.yulOptimiserCleanupSteps == OptimiserSettings::DefaultYulOptimiserCleanupSteps
);
// Defaults are the minimum necessary to avoid running into "Stack too deep" constantly.
return std::make_tuple(true, "u", "");
}
}
return std::make_tuple(
m_optimiserSettings.optimizeStackAllocation,
m_optimiserSettings.yulOptimiserSteps,
m_optimiserSettings.yulOptimiserCleanupSteps
);
}();
m_stackState = Parsed;
solAssert(m_objectOptimizer);
m_objectOptimizer->optimize(
*m_parserResult,
ObjectOptimizer::Settings{
m_language,
m_evmVersion,
m_eofVersion,
optimizeStackAllocation,
yulOptimiserSteps,
yulOptimiserCleanupSteps,
m_optimiserSettings.expectedExecutionsPerDeployment
}
);
// Optimizer does not maintain correct native source locations in the AST.
// We can work around it by regenerating the AST from scratch from optimized IR.
reparse();
}
catch (UnimplementedFeatureError const& _error)
{
reportUnimplementedFeatureError(_error);
}
}
bool YulStack::analyzeParsed()
{
yulAssert(m_stackState >= Parsed);
yulAssert(m_parserResult, "");
return analyzeParsed(*m_parserResult);
}
bool YulStack::analyzeParsed(Object& _object)
{
yulAssert(m_stackState >= Parsed);
yulAssert(_object.hasCode());
_object.analysisInfo = std::make_shared<AsmAnalysisInfo>();
AsmAnalyzer analyzer(
*_object.analysisInfo,
m_errorReporter,
languageToDialect(m_language, m_evmVersion, m_eofVersion),
{},
_object.summarizeStructure()
);
bool success = false;
try
{
success = analyzer.analyze(_object.code()->root());
for (auto& subNode: _object.subObjects)
if (auto subObject = dynamic_cast<Object*>(subNode.get()))
if (!analyzeParsed(*subObject))
success = false;
}
catch (UnimplementedFeatureError const& _error)
{
reportUnimplementedFeatureError(_error);
success = false;
}
if (success)
m_stackState = AnalysisSuccessful;
return success;
}
void YulStack::compileEVM(AbstractAssembly& _assembly, bool _optimize) const
{
EVMDialect const* dialect = nullptr;
switch (m_language)
{
case Language::Assembly:
case Language::StrictAssembly:
dialect = &EVMDialect::strictAssemblyForEVMObjects(m_evmVersion, m_eofVersion);
break;
default:
yulAssert(false, "Invalid language.");
break;
}
EVMObjectCompiler::compile(*m_parserResult, _assembly, *dialect, _optimize, m_eofVersion);
}
void YulStack::reparse()
{
yulAssert(m_parserResult);
yulAssert(m_charStream);
// NOTE: it is important for the source printed here to exactly match what the compiler will
// eventually output to the user. In particular, debug info must be exactly the same.
// Otherwise source locations will be off.
std::string source = print();
YulStack cleanStack(
m_evmVersion,
m_eofVersion,
m_language,
m_optimiserSettings,
m_debugInfoSelection,
m_soliditySourceProvider,
m_objectOptimizer
);
bool reanalysisSuccessful = cleanStack.parseAndAnalyze(m_charStream->name(), source);
yulAssert(
reanalysisSuccessful,
source + "\n\n"
"Invalid IR generated:\n" +
SourceReferenceFormatter::formatErrorInformation(cleanStack.errors(), cleanStack) + "\n"
);
m_stackState = AnalysisSuccessful;
m_parserResult = std::move(cleanStack.m_parserResult);
// NOTE: We keep the char stream, and errors, even though they no longer match the object,
// because it's the original source that matters to the user. Optimized code may have different
// locations and fewer warnings.
}
MachineAssemblyObject YulStack::assemble(Machine _machine)
{
yulAssert(m_stackState >= AnalysisSuccessful);
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode(), "");
yulAssert(m_parserResult->analysisInfo, "");
switch (_machine)
{
case Machine::EVM:
return assembleWithDeployed().first;
}
unreachable();
}
std::pair<MachineAssemblyObject, MachineAssemblyObject>
YulStack::assembleWithDeployed(std::optional<std::string_view> _deployName)
{
auto [creationAssembly, deployedAssembly] = assembleEVMWithDeployed(_deployName);
yulAssert(creationAssembly, "");
yulAssert(m_charStream, "");
MachineAssemblyObject creationObject;
MachineAssemblyObject deployedObject;
try
{
creationObject.bytecode = std::make_shared<evmasm::LinkerObject>(creationAssembly->assemble());
yulAssert(creationObject.bytecode->immutableReferences.empty(), "Leftover immutables.");
creationObject.assembly = creationAssembly;
creationObject.sourceMappings = std::make_unique<std::string>();
for (auto const& codeSection: creationAssembly->codeSections())
{
*creationObject.sourceMappings += evmasm::AssemblyItem::computeSourceMapping(
codeSection.items,
{{m_charStream->name(), 0}}
);
}
if (deployedAssembly)
{
deployedObject.bytecode = std::make_shared<evmasm::LinkerObject>(deployedAssembly->assemble());
deployedObject.assembly = deployedAssembly;
solAssert(deployedAssembly->codeSections().size() == 1);
deployedObject.sourceMappings = std::make_unique<std::string>(
evmasm::AssemblyItem::computeSourceMapping(
deployedAssembly->codeSections().front().items,
{{m_charStream->name(), 0}}
)
);
}
}
catch (UnimplementedFeatureError const& _error)
{
reportUnimplementedFeatureError(_error);
}
return {std::move(creationObject), std::move(deployedObject)};
}
std::pair<std::shared_ptr<evmasm::Assembly>, std::shared_ptr<evmasm::Assembly>>
YulStack::assembleEVMWithDeployed(std::optional<std::string_view> _deployName)
{
yulAssert(m_stackState >= AnalysisSuccessful);
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode(), "");
yulAssert(m_parserResult->analysisInfo, "");
evmasm::Assembly assembly(m_evmVersion, true, m_eofVersion, {});
EthAssemblyAdapter adapter(assembly);
// NOTE: We always need stack optimization when Yul optimizer is disabled (unless code contains
// msize). It being disabled just means that we don't use the full step sequence. We still run
// it with the minimal steps required to avoid "stack too deep".
bool optimize = m_optimiserSettings.optimizeStackAllocation || (
!m_optimiserSettings.runYulOptimiser &&
!yul::MSizeFinder::containsMSize(languageToDialect(m_language, m_evmVersion, m_eofVersion), *m_parserResult)
);
try
{
compileEVM(adapter, optimize);
assembly.optimise(evmasm::Assembly::OptimiserSettings::translateSettings(m_optimiserSettings, m_evmVersion));
std::optional<size_t> subIndex;
// Pick matching assembly if name was given
if (_deployName.has_value())
{
for (size_t i = 0; i < assembly.numSubs(); i++)
if (assembly.sub(i).name() == _deployName)
{
subIndex = i;
break;
}
solAssert(subIndex.has_value(), "Failed to find object to be deployed.");
}
// Otherwise use heuristic: If there is a single sub-assembly, this is likely the object to be deployed.
else if (assembly.numSubs() == 1)
subIndex = 0;
if (subIndex.has_value())
{
evmasm::Assembly& runtimeAssembly = assembly.sub(*subIndex);
return {std::make_shared<evmasm::Assembly>(assembly), std::make_shared<evmasm::Assembly>(runtimeAssembly)};
}
}
catch (UnimplementedFeatureError const& _error)
{
reportUnimplementedFeatureError(_error);
}
return {std::make_shared<evmasm::Assembly>(assembly), {}};
}
std::string YulStack::print() const
{
yulAssert(m_stackState >= Parsed);
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode(), "");
return m_parserResult->toString(
m_debugInfoSelection,
m_soliditySourceProvider
) + "\n";
}
Json YulStack::astJson() const
{
yulAssert(m_stackState >= Parsed);
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode(), "");
return m_parserResult->toJson();
}
Json YulStack::cfgJson() const
{
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode(), "");
yulAssert(m_parserResult->analysisInfo, "");
// FIXME: we should not regenerate the cfg, but for now this is sufficient for testing purposes
auto exportCFGFromObject = [&](Object const& _object) -> Json {
// NOTE: The block Ids are reset for each object
std::unique_ptr<ControlFlow> controlFlow = SSAControlFlowGraphBuilder::build(
*_object.analysisInfo.get(),
languageToDialect(m_language, m_evmVersion, m_eofVersion),
_object.code()->root()
);
YulControlFlowGraphExporter exporter(*controlFlow);
return exporter.run();
};
std::function<Json(std::vector<std::shared_ptr<ObjectNode>>)> exportCFGFromSubObjects;
exportCFGFromSubObjects = [&](std::vector<std::shared_ptr<ObjectNode>> _subObjects) -> Json {
Json subObjectsJson = Json::object();
for (std::shared_ptr<ObjectNode> const& subObjectNode: _subObjects)
if (Object const* subObject = dynamic_cast<Object const*>(subObjectNode.get()))
{
subObjectsJson[subObject->name] = exportCFGFromObject(*subObject);
subObjectsJson["type"] = "subObject";
if (!subObject->subObjects.empty())
subObjectsJson["subObjects"] = exportCFGFromSubObjects(subObject->subObjects);
}
return subObjectsJson;
};
Object const& object = *m_parserResult.get();
Json jsonObject = Json::object();
jsonObject[object.name] = exportCFGFromObject(object);
jsonObject["type"] = "Object";
jsonObject["subObjects"] = exportCFGFromSubObjects(object.subObjects);
return jsonObject;
}
std::shared_ptr<Object> YulStack::parserResult() const
{
yulAssert(m_stackState >= AnalysisSuccessful, "Analysis was not successful.");
yulAssert(m_parserResult, "");
yulAssert(m_parserResult->hasCode(), "");
return m_parserResult;
}
void YulStack::reportUnimplementedFeatureError(UnimplementedFeatureError const& _error)
{
solAssert(_error.comment(), "Unimplemented feature errors must include a message for the user");
m_errorReporter.unimplementedFeatureError(1920_error, _error.sourceLocation(), *_error.comment());
}
| 13,512
|
C++
|
.cpp
| 374
| 33.419786
| 141
| 0.761046
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,054
|
AsmParser.cpp
|
ethereum_solidity/libyul/AsmParser.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Solidity inline assembly parser.
*/
#include <libyul/AST.h>
#include <libyul/AsmParser.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <liblangutil/ErrorReporter.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/Scanner.h>
#include <liblangutil/Common.h>
#include <libsolutil/Common.h>
#include <libsolutil/Visitor.h>
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <regex>
using namespace std::string_literals;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
namespace
{
std::optional<int> toInt(std::string const& _value)
{
try
{
return stoi(_value);
}
catch (std::out_of_range const&)
{
return std::nullopt;
}
}
}
langutil::DebugData::ConstPtr Parser::createDebugData() const
{
switch (m_useSourceLocationFrom)
{
case UseSourceLocationFrom::Scanner:
return DebugData::create(ParserBase::currentLocation(), ParserBase::currentLocation());
case UseSourceLocationFrom::LocationOverride:
return DebugData::create(m_locationOverride, m_locationOverride);
case UseSourceLocationFrom::Comments:
return DebugData::create(ParserBase::currentLocation(), m_locationFromComment, m_astIDFromComment);
}
solAssert(false, "");
}
void Parser::updateLocationEndFrom(
langutil::DebugData::ConstPtr& _debugData,
SourceLocation const& _location
) const
{
solAssert(_debugData, "");
switch (m_useSourceLocationFrom)
{
case UseSourceLocationFrom::Scanner:
{
DebugData updatedDebugData = *_debugData;
updatedDebugData.nativeLocation.end = _location.end;
updatedDebugData.originLocation.end = _location.end;
_debugData = std::make_shared<DebugData const>(std::move(updatedDebugData));
break;
}
case UseSourceLocationFrom::LocationOverride:
// Ignore the update. The location we're overriding with is not supposed to change
break;
case UseSourceLocationFrom::Comments:
{
DebugData updatedDebugData = *_debugData;
updatedDebugData.nativeLocation.end = _location.end;
_debugData = std::make_shared<DebugData const>(std::move(updatedDebugData));
break;
}
}
}
std::unique_ptr<AST> Parser::parse(CharStream& _charStream)
{
m_scanner = std::make_shared<Scanner>(_charStream);
std::unique_ptr<AST> ast = parseInline(m_scanner);
expectToken(Token::EOS);
return ast;
}
std::unique_ptr<AST> Parser::parseInline(std::shared_ptr<Scanner> const& _scanner)
{
m_recursionDepth = 0;
auto previousScannerKind = _scanner->scannerKind();
_scanner->setScannerMode(ScannerKind::Yul);
ScopeGuard resetScanner([&]{ _scanner->setScannerMode(previousScannerKind); });
try
{
m_scanner = _scanner;
if (m_useSourceLocationFrom == UseSourceLocationFrom::Comments)
fetchDebugDataFromComment();
return std::make_unique<AST>(parseBlock());
}
catch (FatalError const& error)
{
yulAssert(m_errorReporter.hasErrors(), "Unreported fatal error: "s + error.what());
}
return nullptr;
}
langutil::Token Parser::advance()
{
auto const token = ParserBase::advance();
if (m_useSourceLocationFrom == UseSourceLocationFrom::Comments)
fetchDebugDataFromComment();
return token;
}
void Parser::fetchDebugDataFromComment()
{
solAssert(m_sourceNames.has_value(), "");
static std::regex const tagRegex = std::regex(
R"~~((?:^|\s+)(@[a-zA-Z0-9\-_]+)(?:\s+|$))~~", // tag, e.g: @src
std::regex_constants::ECMAScript | std::regex_constants::optimize
);
std::string_view commentLiteral = m_scanner->currentCommentLiteral();
std::match_results<std::string_view::const_iterator> match;
langutil::SourceLocation originLocation = m_locationFromComment;
// Empty for each new node.
std::optional<int> astID;
while (regex_search(commentLiteral.cbegin(), commentLiteral.cend(), match, tagRegex))
{
solAssert(match.size() == 2, "");
commentLiteral = commentLiteral.substr(static_cast<size_t>(match.position() + match.length()));
if (match[1] == "@src")
{
if (auto parseResult = parseSrcComment(commentLiteral, m_scanner->currentCommentLocation()))
tie(commentLiteral, originLocation) = *parseResult;
else
break;
}
else if (match[1] == "@ast-id")
{
if (auto parseResult = parseASTIDComment(commentLiteral, m_scanner->currentCommentLocation()))
tie(commentLiteral, astID) = *parseResult;
else
break;
}
else
// Ignore unrecognized tags.
continue;
}
m_locationFromComment = originLocation;
m_astIDFromComment = astID;
}
std::optional<std::pair<std::string_view, SourceLocation>> Parser::parseSrcComment(
std::string_view const _arguments,
langutil::SourceLocation const& _commentLocation
)
{
CharStream argumentStream(std::string(_arguments), "");
Scanner scanner(argumentStream, ScannerKind::SpecialComment);
std::string_view tail{_arguments.substr(_arguments.size())};
auto const parseLocationComponent = [](Scanner& _scanner, bool expectTrailingColon) -> std::optional<std::string>
{
bool negative = false;
if (_scanner.currentToken() == Token::Sub)
{
negative = true;
_scanner.next();
}
if (_scanner.currentToken() != Token::Number)
return std::nullopt;
if (expectTrailingColon && _scanner.peekNextToken() != Token::Colon)
return std::nullopt;
if (!isValidDecimal(_scanner.currentLiteral()))
return std::nullopt;
std::string decimal = (negative ? "-" : "") + _scanner.currentLiteral();
_scanner.next();
if (expectTrailingColon)
_scanner.next();
return decimal;
};
std::optional<std::string> rawSourceIndex = parseLocationComponent(scanner, true);
std::optional<std::string> rawStart = parseLocationComponent(scanner, true);
std::optional<std::string> rawEnd = parseLocationComponent(scanner, false);
size_t const snippetStart = static_cast<size_t>(scanner.currentLocation().start);
bool const locationScannedSuccessfully = rawSourceIndex && rawStart && rawEnd;
bool const locationIsWhitespaceSeparated =
scanner.peekNextToken() == Token::EOS ||
(snippetStart > 0 && langutil::isWhiteSpace(_arguments[snippetStart - 1]));
if (!locationScannedSuccessfully || !locationIsWhitespaceSeparated)
{
m_errorReporter.syntaxError(
8387_error,
_commentLocation,
"Invalid values in source location mapping. Could not parse location specification."
);
return std::nullopt;
}
// captures error cases `"test` (illegal end quote) and `"test\` (illegal escape sequence / dangling backslash)
bool const illegalLiteral = scanner.currentToken() == Token::Illegal && (scanner.currentError() == ScannerError::IllegalStringEndQuote || scanner.currentError() == ScannerError::IllegalEscapeSequence);
if (scanner.currentToken() == Token::StringLiteral || illegalLiteral)
tail = _arguments.substr(static_cast<size_t>(scanner.currentLocation().end));
else
tail = _arguments.substr(static_cast<size_t>(scanner.currentLocation().start));
// Other scanner errors may occur if there is no string literal which follows
// (f.ex. IllegalHexDigit, IllegalCommentTerminator), but these are ignored
if (illegalLiteral)
{
m_errorReporter.syntaxError(
1544_error,
_commentLocation,
"Invalid code snippet in source location mapping. Quote is not terminated."
);
return {{tail, SourceLocation{}}};
}
std::optional<int> const sourceIndex = toInt(*rawSourceIndex);
std::optional<int> const start = toInt(*rawStart);
std::optional<int> const end = toInt(*rawEnd);
if (
!sourceIndex.has_value() || *sourceIndex < -1 ||
!start.has_value() || *start < -1 ||
!end.has_value() || *end < -1
)
m_errorReporter.syntaxError(
6367_error,
_commentLocation,
"Invalid value in source location mapping. "
"Expected non-negative integer values or -1 for source index and location."
);
else if (sourceIndex == -1)
return {{tail, SourceLocation{*start, *end, nullptr}}};
else if (!(sourceIndex >= 0 && m_sourceNames->count(static_cast<unsigned>(*sourceIndex))))
m_errorReporter.syntaxError(
2674_error,
_commentLocation,
"Invalid source mapping. Source index not defined via @use-src."
);
else
{
std::shared_ptr<std::string const> sourceName = m_sourceNames->at(static_cast<unsigned>(*sourceIndex));
solAssert(sourceName, "");
return {{tail, SourceLocation{*start, *end, std::move(sourceName)}}};
}
return {{tail, SourceLocation{}}};
}
std::optional<std::pair<std::string_view, std::optional<int>>> Parser::parseASTIDComment(
std::string_view _arguments,
langutil::SourceLocation const& _commentLocation
)
{
static std::regex const argRegex = std::regex(
R"~~(^(\d+)(?:\s|$))~~",
std::regex_constants::ECMAScript | std::regex_constants::optimize
);
std::match_results<std::string_view::const_iterator> match;
std::optional<int> astID;
bool matched = regex_search(_arguments.cbegin(), _arguments.cend(), match, argRegex);
std::string_view tail = _arguments;
if (matched)
{
solAssert(match.size() == 2, "");
tail = _arguments.substr(static_cast<size_t>(match.position() + match.length()));
astID = toInt(match[1].str());
}
if (!matched || !astID || *astID < 0 || static_cast<int64_t>(*astID) != *astID)
{
m_errorReporter.syntaxError(1749_error, _commentLocation, "Invalid argument for @ast-id.");
astID = std::nullopt;
}
if (matched)
return {{_arguments, astID}};
else
return std::nullopt;
}
Block Parser::parseBlock()
{
RecursionGuard recursionGuard(*this);
Block block = createWithDebugData<Block>();
expectToken(Token::LBrace);
while (currentToken() != Token::RBrace)
block.statements.emplace_back(parseStatement());
updateLocationEndFrom(block.debugData, currentLocation());
advance();
return block;
}
Statement Parser::parseStatement()
{
RecursionGuard recursionGuard(*this);
switch (currentToken())
{
case Token::Let:
return parseVariableDeclaration();
case Token::Function:
return parseFunctionDefinition();
case Token::LBrace:
return parseBlock();
case Token::If:
{
If _if = createWithDebugData<If>();
advance();
_if.condition = std::make_unique<Expression>(parseExpression());
_if.body = parseBlock();
updateLocationEndFrom(_if.debugData, nativeLocationOf(_if.body));
return Statement{std::move(_if)};
}
case Token::Switch:
{
Switch _switch = createWithDebugData<Switch>();
advance();
_switch.expression = std::make_unique<Expression>(parseExpression());
while (currentToken() == Token::Case)
_switch.cases.emplace_back(parseCase());
if (currentToken() == Token::Default)
_switch.cases.emplace_back(parseCase());
if (currentToken() == Token::Default)
fatalParserError(6931_error, "Only one default case allowed.");
else if (currentToken() == Token::Case)
fatalParserError(4904_error, "Case not allowed after default case.");
if (_switch.cases.empty())
fatalParserError(2418_error, "Switch statement without any cases.");
updateLocationEndFrom(_switch.debugData, nativeLocationOf(_switch.cases.back().body));
return Statement{std::move(_switch)};
}
case Token::For:
return parseForLoop();
case Token::Break:
{
Statement stmt{createWithDebugData<Break>()};
checkBreakContinuePosition("break");
advance();
return stmt;
}
case Token::Continue:
{
Statement stmt{createWithDebugData<Continue>()};
checkBreakContinuePosition("continue");
advance();
return stmt;
}
case Token::Leave:
{
Statement stmt{createWithDebugData<Leave>()};
if (!m_insideFunction)
m_errorReporter.syntaxError(8149_error, currentLocation(), "Keyword \"leave\" can only be used inside a function.");
advance();
return stmt;
}
default:
break;
}
// Options left:
// Expression/FunctionCall
// Assignment
std::variant<Literal, Identifier> elementary(parseLiteralOrIdentifier());
switch (currentToken())
{
case Token::LParen:
{
Expression expr = parseCall(std::move(elementary));
return ExpressionStatement{debugDataOf(expr), std::move(expr)};
}
case Token::Comma:
case Token::AssemblyAssign:
{
Assignment assignment;
assignment.debugData = debugDataOf(elementary);
while (true)
{
if (!std::holds_alternative<Identifier>(elementary))
{
auto const token = currentToken() == Token::Comma ? "," : ":=";
fatalParserError(
2856_error,
std::string("Variable name must precede \"") +
token +
"\"" +
(currentToken() == Token::Comma ? " in multiple assignment." : " in assignment.")
);
}
auto const& identifier = std::get<Identifier>(elementary);
if (m_dialect.findBuiltin(identifier.name.str()))
fatalParserError(6272_error, "Cannot assign to builtin function \"" + identifier.name.str() + "\".");
assignment.variableNames.emplace_back(identifier);
if (currentToken() != Token::Comma)
break;
expectToken(Token::Comma);
elementary = parseLiteralOrIdentifier();
}
expectToken(Token::AssemblyAssign);
assignment.value = std::make_unique<Expression>(parseExpression());
updateLocationEndFrom(assignment.debugData, nativeLocationOf(*assignment.value));
return Statement{std::move(assignment)};
}
default:
fatalParserError(6913_error, "Call or assignment expected.");
break;
}
yulAssert(false, "");
return {};
}
Case Parser::parseCase()
{
RecursionGuard recursionGuard(*this);
Case _case = createWithDebugData<Case>();
if (currentToken() == Token::Default)
advance();
else if (currentToken() == Token::Case)
{
advance();
std::variant<Literal, Identifier> literal = parseLiteralOrIdentifier();
if (!std::holds_alternative<Literal>(literal))
fatalParserError(4805_error, "Literal expected.");
_case.value = std::make_unique<Literal>(std::get<Literal>(std::move(literal)));
}
else
yulAssert(false, "Case or default case expected.");
_case.body = parseBlock();
updateLocationEndFrom(_case.debugData, nativeLocationOf(_case.body));
return _case;
}
ForLoop Parser::parseForLoop()
{
RecursionGuard recursionGuard(*this);
ForLoopComponent outerForLoopComponent = m_currentForLoopComponent;
ForLoop forLoop = createWithDebugData<ForLoop>();
expectToken(Token::For);
m_currentForLoopComponent = ForLoopComponent::ForLoopPre;
forLoop.pre = parseBlock();
m_currentForLoopComponent = ForLoopComponent::None;
forLoop.condition = std::make_unique<Expression>(parseExpression());
m_currentForLoopComponent = ForLoopComponent::ForLoopPost;
forLoop.post = parseBlock();
m_currentForLoopComponent = ForLoopComponent::ForLoopBody;
forLoop.body = parseBlock();
updateLocationEndFrom(forLoop.debugData, nativeLocationOf(forLoop.body));
m_currentForLoopComponent = outerForLoopComponent;
return forLoop;
}
Expression Parser::parseExpression(bool _unlimitedLiteralArgument)
{
RecursionGuard recursionGuard(*this);
std::variant<Literal, Identifier> operation = parseLiteralOrIdentifier(_unlimitedLiteralArgument);
return visit(GenericVisitor{
[&](Identifier& _identifier) -> Expression
{
if (currentToken() == Token::LParen)
return parseCall(std::move(operation));
if (m_dialect.findBuiltin(_identifier.name.str()))
fatalParserError(
7104_error,
nativeLocationOf(_identifier),
"Builtin function \"" + _identifier.name.str() + "\" must be called."
);
return std::move(_identifier);
},
[&](Literal& _literal) -> Expression
{
return std::move(_literal);
}
}, operation);
}
std::variant<Literal, Identifier> Parser::parseLiteralOrIdentifier(bool _unlimitedLiteralArgument)
{
RecursionGuard recursionGuard(*this);
switch (currentToken())
{
case Token::Identifier:
{
Identifier identifier{createDebugData(), YulName{currentLiteral()}};
advance();
return identifier;
}
case Token::StringLiteral:
case Token::HexStringLiteral:
case Token::Number:
case Token::TrueLiteral:
case Token::FalseLiteral:
{
LiteralKind kind = LiteralKind::Number;
switch (currentToken())
{
case Token::StringLiteral:
case Token::HexStringLiteral:
kind = LiteralKind::String;
break;
case Token::Number:
if (!isValidNumberLiteral(currentLiteral()))
fatalParserError(4828_error, "Invalid number literal.");
kind = LiteralKind::Number;
break;
case Token::TrueLiteral:
case Token::FalseLiteral:
kind = LiteralKind::Boolean;
break;
default:
break;
}
auto const literalLocation = currentLocation();
Literal literal{
createDebugData(),
kind,
valueOfLiteral(currentLiteral(), kind, _unlimitedLiteralArgument && kind == LiteralKind::String)
};
advance();
if (currentToken() == Token::Colon)
{
expectToken(Token::Colon);
updateLocationEndFrom(literal.debugData, currentLocation());
auto const typedLiteralLocation = SourceLocation::smallestCovering(literalLocation, currentLocation());
std::ignore = expectAsmIdentifier();
raiseUnsupportedTypesError(typedLiteralLocation);
}
return literal;
}
case Token::Illegal:
fatalParserError(1465_error, "Illegal token: " + to_string(m_scanner->currentError()));
break;
default:
fatalParserError(1856_error, "Literal or identifier expected.");
}
return {};
}
VariableDeclaration Parser::parseVariableDeclaration()
{
RecursionGuard recursionGuard(*this);
VariableDeclaration varDecl = createWithDebugData<VariableDeclaration>();
expectToken(Token::Let);
while (true)
{
varDecl.variables.emplace_back(parseNameWithDebugData());
if (currentToken() == Token::Comma)
expectToken(Token::Comma);
else
break;
}
if (currentToken() == Token::AssemblyAssign)
{
expectToken(Token::AssemblyAssign);
varDecl.value = std::make_unique<Expression>(parseExpression());
updateLocationEndFrom(varDecl.debugData, nativeLocationOf(*varDecl.value));
}
else
updateLocationEndFrom(varDecl.debugData, nativeLocationOf(varDecl.variables.back()));
return varDecl;
}
FunctionDefinition Parser::parseFunctionDefinition()
{
RecursionGuard recursionGuard(*this);
if (m_currentForLoopComponent == ForLoopComponent::ForLoopPre)
m_errorReporter.syntaxError(
3441_error,
currentLocation(),
"Functions cannot be defined inside a for-loop init block."
);
ForLoopComponent outerForLoopComponent = m_currentForLoopComponent;
m_currentForLoopComponent = ForLoopComponent::None;
FunctionDefinition funDef = createWithDebugData<FunctionDefinition>();
expectToken(Token::Function);
funDef.name = expectAsmIdentifier();
expectToken(Token::LParen);
while (currentToken() != Token::RParen)
{
funDef.parameters.emplace_back(parseNameWithDebugData());
if (currentToken() == Token::RParen)
break;
expectToken(Token::Comma);
}
expectToken(Token::RParen);
if (currentToken() == Token::RightArrow)
{
expectToken(Token::RightArrow);
while (true)
{
funDef.returnVariables.emplace_back(parseNameWithDebugData());
if (currentToken() == Token::LBrace)
break;
expectToken(Token::Comma);
}
}
bool preInsideFunction = m_insideFunction;
m_insideFunction = true;
funDef.body = parseBlock();
m_insideFunction = preInsideFunction;
updateLocationEndFrom(funDef.debugData, nativeLocationOf(funDef.body));
m_currentForLoopComponent = outerForLoopComponent;
return funDef;
}
FunctionCall Parser::parseCall(std::variant<Literal, Identifier>&& _initialOp)
{
RecursionGuard recursionGuard(*this);
if (!std::holds_alternative<Identifier>(_initialOp))
fatalParserError(9980_error, "Function name expected.");
FunctionCall ret;
ret.functionName = std::move(std::get<Identifier>(_initialOp));
ret.debugData = ret.functionName.debugData;
auto const isUnlimitedLiteralArgument = [handle=m_dialect.findBuiltin(ret.functionName.name.str()), this](size_t const index) {
if (!handle)
return false;
auto const& function = m_dialect.builtin(*handle);
return index < function.literalArguments.size() && function.literalArgument(index).has_value();
};
size_t argumentIndex {0};
expectToken(Token::LParen);
if (currentToken() != Token::RParen)
{
ret.arguments.emplace_back(parseExpression(isUnlimitedLiteralArgument(argumentIndex++)));
while (currentToken() != Token::RParen)
{
expectToken(Token::Comma);
ret.arguments.emplace_back(parseExpression(isUnlimitedLiteralArgument(argumentIndex++)));
}
}
updateLocationEndFrom(ret.debugData, currentLocation());
expectToken(Token::RParen);
return ret;
}
NameWithDebugData Parser::parseNameWithDebugData()
{
RecursionGuard recursionGuard(*this);
NameWithDebugData typedName = createWithDebugData<NameWithDebugData>();
auto const nameLocation = currentLocation();
typedName.name = expectAsmIdentifier();
if (currentToken() == Token::Colon)
{
expectToken(Token::Colon);
updateLocationEndFrom(typedName.debugData, currentLocation());
auto const typedNameLocation = SourceLocation::smallestCovering(nameLocation, currentLocation());
std::ignore = expectAsmIdentifier();
raiseUnsupportedTypesError(typedNameLocation);
}
return typedName;
}
YulName Parser::expectAsmIdentifier()
{
YulName name{currentLiteral()};
if (currentToken() == Token::Identifier && m_dialect.findBuiltin(name.str()))
fatalParserError(5568_error, "Cannot use builtin function name \"" + name.str() + "\" as identifier name.");
// NOTE: We keep the expectation here to ensure the correct source location for the error above.
expectToken(Token::Identifier);
return name;
}
void Parser::checkBreakContinuePosition(std::string const& _which)
{
switch (m_currentForLoopComponent)
{
case ForLoopComponent::None:
m_errorReporter.syntaxError(2592_error, currentLocation(), "Keyword \"" + _which + "\" needs to be inside a for-loop body.");
break;
case ForLoopComponent::ForLoopPre:
m_errorReporter.syntaxError(9615_error, currentLocation(), "Keyword \"" + _which + "\" in for-loop init block is not allowed.");
break;
case ForLoopComponent::ForLoopPost:
m_errorReporter.syntaxError(2461_error, currentLocation(), "Keyword \"" + _which + "\" in for-loop post block is not allowed.");
break;
case ForLoopComponent::ForLoopBody:
break;
}
}
bool Parser::isValidNumberLiteral(std::string const& _literal)
{
try
{
// Try to convert _literal to u256.
[[maybe_unused]] auto tmp = u256(_literal);
}
catch (...)
{
return false;
}
if (boost::starts_with(_literal, "0x"))
return true;
else
return _literal.find_first_not_of("0123456789") == std::string::npos;
}
void Parser::raiseUnsupportedTypesError(SourceLocation const& _location) const
{
m_errorReporter.parserError(5473_error, _location, "Types are not supported in untyped Yul.");
}
| 23,095
|
C++
|
.cpp
| 687
| 30.995633
| 202
| 0.750627
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,056
|
CompilabilityChecker.cpp
|
ethereum_solidity/libyul/CompilabilityChecker.cpp
|
/*(
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Component that checks whether all variables are reachable on the stack.
*/
#include <libyul/CompilabilityChecker.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/backends/evm/EVMCodeTransform.h>
#include <libyul/backends/evm/NoOutputAssembly.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
CompilabilityChecker::CompilabilityChecker(
Dialect const& _dialect,
Object const& _object,
bool _optimizeStackAllocation
)
{
yulAssert(_object.hasCode());
if (auto const* evmDialect = dynamic_cast<EVMDialect const*>(&_dialect))
{
NoOutputEVMDialect noOutputDialect(*evmDialect);
yul::AsmAnalysisInfo analysisInfo = yul::AsmAnalyzer::analyzeStrictAssertCorrect(
noOutputDialect,
_object.code()->root(),
_object.summarizeStructure()
);
BuiltinContext builtinContext;
builtinContext.currentObject = &_object;
if (!_object.name.empty())
builtinContext.subIDs[_object.name] = 1;
for (auto const& subNode: _object.subObjects)
builtinContext.subIDs[subNode->name] = 1;
NoOutputAssembly assembly{evmDialect->evmVersion()};
CodeTransform transform(
assembly,
analysisInfo,
_object.code()->root(),
noOutputDialect,
builtinContext,
_optimizeStackAllocation
);
transform(_object.code()->root());
for (StackTooDeepError const& error: transform.stackErrors())
{
auto& unreachables = unreachableVariables[error.functionName];
if (!util::contains(unreachables, error.variable))
unreachables.emplace_back(error.variable);
int& deficit = stackDeficit[error.functionName];
deficit = std::max(error.depth, deficit);
}
}
}
| 2,326
|
C++
|
.cpp
| 65
| 33.123077
| 83
| 0.776444
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,057
|
AsmAnalysis.cpp
|
ethereum_solidity/libyul/AsmAnalysis.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Analyzer part of inline assembly.
*/
#include <libyul/AsmAnalysis.h>
#include <libyul/AST.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/Utilities.h>
#include <libyul/Exceptions.h>
#include <libyul/Object.h>
#include <libyul/Scope.h>
#include <libyul/ScopeFiller.h>
#include <liblangutil/ErrorReporter.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/StringUtils.h>
#include <libsolutil/Visitor.h>
#include <libevmasm/Instruction.h>
#include <boost/algorithm/string.hpp>
#include <fmt/format.h>
#include <functional>
using namespace std::string_literals;
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
using namespace solidity::langutil;
namespace
{
inline std::string to_string(LiteralKind _kind)
{
switch (_kind)
{
case LiteralKind::Number: return "number";
case LiteralKind::Boolean: return "boolean";
case LiteralKind::String: return "string";
default: yulAssert(false, "");
}
}
}
bool AsmAnalyzer::analyze(Block const& _block)
{
auto watcher = m_errorReporter.errorWatcher();
try
{
// FIXME: Pass location of the object name. Now it's a location of first code section in yul
validateObjectStructure(nativeLocationOf(_block));
if (!(ScopeFiller(m_info, m_errorReporter))(_block))
return false;
(*this)(_block);
}
catch (FatalError const& error)
{
// NOTE: There's a cap on the number of reported errors, but watcher.ok() will work fine even if
// we exceed it because the reporter keeps counting (it just stops adding errors to the list).
// Note also that fact of exceeding the cap triggers a FatalError so one can get thrown even
// if we don't make any of our errors fatal.
yulAssert(!watcher.ok(), "Unreported fatal error: "s + error.what());
}
return watcher.ok();
}
AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object)
{
return analyzeStrictAssertCorrect(_dialect, _object.code()->root(), _object.summarizeStructure());
}
AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(
Dialect const& _dialect,
Block const& _astRoot,
Object::Structure const _objectStructure
)
{
ErrorList errorList;
langutil::ErrorReporter errors(errorList);
AsmAnalysisInfo analysisInfo;
bool success = yul::AsmAnalyzer(
analysisInfo,
errors,
_dialect,
{},
std::move(_objectStructure)
).analyze(_astRoot);
yulAssert(success && !errors.hasErrors(), "Invalid assembly/yul code.");
return analysisInfo;
}
size_t AsmAnalyzer::operator()(Literal const& _literal)
{
bool erroneousLiteralValue = false;
if (_literal.kind == LiteralKind::String && !_literal.value.unlimited() && _literal.value.hint() && _literal.value.hint()->size() > 32)
{
erroneousLiteralValue = true;
m_errorReporter.typeError(
3069_error,
nativeLocationOf(_literal),
"String literal too long (" + std::to_string(formatLiteral(_literal, false /* _validated */ ).size()) + " > 32)"
);
}
else if (_literal.kind == LiteralKind::Number && _literal.value.hint() && bigint(*_literal.value.hint()) > u256(-1))
{
erroneousLiteralValue = true;
m_errorReporter.typeError(6708_error, nativeLocationOf(_literal), "Number literal too large (> 256 bits)");
}
yulAssert(erroneousLiteralValue ^ validLiteral(_literal), "Invalid literal after validating it through AsmAnalyzer.");
return 1;
}
size_t AsmAnalyzer::operator()(Identifier const& _identifier)
{
yulAssert(!_identifier.name.empty(), "");
auto watcher = m_errorReporter.errorWatcher();
if (m_currentScope->lookup(_identifier.name, GenericVisitor{
[&](Scope::Variable const& _var)
{
if (!m_activeVariables.count(&_var))
m_errorReporter.declarationError(
4990_error,
nativeLocationOf(_identifier),
"Variable " + _identifier.name.str() + " used before it was declared."
);
},
[&](Scope::Function const&)
{
m_errorReporter.typeError(
6041_error,
nativeLocationOf(_identifier),
"Function " + _identifier.name.str() + " used without being called."
);
}
}))
{
if (m_resolver)
// We found a local reference, make sure there is no external reference.
m_resolver(
_identifier,
yul::IdentifierContext::NonExternal,
m_currentScope->insideFunction()
);
}
else
{
bool found = m_resolver && m_resolver(
_identifier,
yul::IdentifierContext::RValue,
m_currentScope->insideFunction()
);
if (!found && watcher.ok())
// Only add an error message if the callback did not do it.
m_errorReporter.declarationError(
8198_error,
nativeLocationOf(_identifier),
"Identifier \"" + _identifier.name.str() + "\" not found."
);
}
return 1;
}
void AsmAnalyzer::operator()(ExpressionStatement const& _statement)
{
auto watcher = m_errorReporter.errorWatcher();
size_t numReturns = std::visit(*this, _statement.expression);
if (watcher.ok() && numReturns > 0)
m_errorReporter.typeError(
3083_error,
nativeLocationOf(_statement),
"Top-level expressions are not supposed to return values (this expression returns " +
std::to_string(numReturns) +
" value" +
(numReturns == 1 ? "" : "s") +
"). Use ``pop()`` or assign them."
);
}
void AsmAnalyzer::operator()(Assignment const& _assignment)
{
yulAssert(_assignment.value, "");
size_t const numVariables = _assignment.variableNames.size();
yulAssert(numVariables >= 1, "");
std::set<YulName> variables;
for (auto const& _variableName: _assignment.variableNames)
if (!variables.insert(_variableName.name).second)
m_errorReporter.declarationError(
9005_error,
nativeLocationOf(_assignment),
"Variable " +
_variableName.name.str() +
" occurs multiple times on the left-hand side of the assignment."
);
size_t numRhsValues = std::visit(*this, *_assignment.value);
if (numRhsValues != numVariables)
m_errorReporter.declarationError(
8678_error,
nativeLocationOf(_assignment),
"Variable count for assignment to \"" +
joinHumanReadable(applyMap(_assignment.variableNames, [](auto const& _identifier){ return _identifier.name.str(); })) +
"\" does not match number of values (" +
std::to_string(numVariables) +
" vs. " +
std::to_string(numRhsValues) +
")"
);
for (size_t i = 0; i < numVariables; ++i)
checkAssignment(_assignment.variableNames[i]);
}
void AsmAnalyzer::operator()(VariableDeclaration const& _varDecl)
{
size_t const numVariables = _varDecl.variables.size();
if (m_resolver)
for (auto const& variable: _varDecl.variables)
// Call the resolver for variable declarations to allow it to raise errors on shadowing.
m_resolver(
yul::Identifier{variable.debugData, variable.name},
yul::IdentifierContext::VariableDeclaration,
m_currentScope->insideFunction()
);
for (auto const& variable: _varDecl.variables)
{
expectValidIdentifier(variable.name, nativeLocationOf(variable));
}
if (_varDecl.value)
{
size_t numValues = std::visit(*this, *_varDecl.value);
if (numValues != numVariables)
m_errorReporter.declarationError(
3812_error,
nativeLocationOf(_varDecl),
"Variable count mismatch for declaration of \"" +
joinHumanReadable(applyMap(_varDecl.variables, [](auto const& _identifier){ return _identifier.name.str(); })) +
+ "\": " +
std::to_string(numVariables) +
" variables and " +
std::to_string(numValues) +
" values."
);
}
for (NameWithDebugData const& variable: _varDecl.variables)
m_activeVariables.insert(&std::get<Scope::Variable>(
m_currentScope->identifiers.at(variable.name))
);
}
void AsmAnalyzer::operator()(FunctionDefinition const& _funDef)
{
yulAssert(!_funDef.name.empty(), "");
expectValidIdentifier(_funDef.name, nativeLocationOf(_funDef));
Block const* virtualBlock = m_info.virtualBlocks.at(&_funDef).get();
yulAssert(virtualBlock, "");
Scope& varScope = scope(virtualBlock);
for (auto const& var: _funDef.parameters + _funDef.returnVariables)
{
expectValidIdentifier(var.name, nativeLocationOf(var));
m_activeVariables.insert(&std::get<Scope::Variable>(varScope.identifiers.at(var.name)));
}
(*this)(_funDef.body);
}
size_t AsmAnalyzer::operator()(FunctionCall const& _funCall)
{
yulAssert(!_funCall.functionName.name.empty(), "");
auto watcher = m_errorReporter.errorWatcher();
std::optional<size_t> numParameters;
std::optional<size_t> numReturns;
std::vector<std::optional<LiteralKind>> const* literalArguments = nullptr;
if (std::optional<BuiltinHandle> handle = m_dialect.findBuiltin(_funCall.functionName.name.str()))
{
if (_funCall.functionName.name == "selfdestruct"_yulname)
m_errorReporter.warning(
1699_error,
nativeLocationOf(_funCall.functionName),
"\"selfdestruct\" has been deprecated. "
"Note that, starting from the Cancun hard fork, the underlying opcode no longer deletes the code and "
"data associated with an account and only transfers its Ether to the beneficiary, "
"unless executed in the same transaction in which the contract was created (see EIP-6780). "
"Any use in newly deployed contracts is strongly discouraged even if the new behavior is taken into account. "
"Future changes to the EVM might further reduce the functionality of the opcode."
);
else if (
m_evmVersion.supportsTransientStorage() &&
_funCall.functionName.name == "tstore"_yulname &&
!m_errorReporter.hasError({2394})
)
m_errorReporter.warning(
2394_error,
nativeLocationOf(_funCall.functionName),
"Transient storage as defined by EIP-1153 can break the composability of smart contracts: "
"Since transient storage is cleared only at the end of the transaction and not at the end of the outermost call frame to the contract within a transaction, "
"your contract may unintentionally misbehave when invoked multiple times in a complex transaction. "
"To avoid this, be sure to clear all transient storage at the end of any call to your contract. "
"The use of transient storage for reentrancy guards that are cleared at the end of the call is safe."
);
BuiltinFunction const& f = m_dialect.builtin(*handle);
numParameters = f.numParameters;
numReturns = f.numReturns;
if (!f.literalArguments.empty())
literalArguments = &f.literalArguments;
validateInstructions(_funCall);
m_sideEffects += f.sideEffects;
}
else if (m_currentScope->lookup(_funCall.functionName.name, GenericVisitor{
[&](Scope::Variable const&)
{
m_errorReporter.typeError(
4202_error,
nativeLocationOf(_funCall.functionName),
"Attempt to call variable instead of function."
);
},
[&](Scope::Function const& _fun)
{
numParameters = _fun.numArguments;
numReturns = _fun.numReturns;
}
}))
{
if (m_resolver)
// We found a local reference, make sure there is no external reference.
m_resolver(
_funCall.functionName,
yul::IdentifierContext::NonExternal,
m_currentScope->insideFunction()
);
}
else
{
if (!validateInstructions(_funCall))
m_errorReporter.declarationError(
4619_error,
nativeLocationOf(_funCall.functionName),
"Function \"" + _funCall.functionName.name.str() + "\" not found."
);
yulAssert(!watcher.ok(), "Expected a reported error.");
}
if (numParameters && _funCall.arguments.size() != *numParameters)
m_errorReporter.typeError(
7000_error,
nativeLocationOf(_funCall.functionName),
"Function \"" + _funCall.functionName.name.str() + "\" expects " +
std::to_string(*numParameters) +
" arguments but got " +
std::to_string(_funCall.arguments.size()) + "."
);
for (size_t i = _funCall.arguments.size(); i > 0; i--)
{
Expression const& arg = _funCall.arguments[i - 1];
if (
auto literalArgumentKind = (literalArguments && i <= literalArguments->size()) ?
literalArguments->at(i - 1) :
std::nullopt
)
{
if (!std::holds_alternative<Literal>(arg))
m_errorReporter.typeError(
9114_error,
nativeLocationOf(_funCall.functionName),
"Function expects direct literals as arguments."
);
else if (*literalArgumentKind != std::get<Literal>(arg).kind)
m_errorReporter.typeError(
5859_error,
nativeLocationOf(arg),
"Function expects " + to_string(*literalArgumentKind) + " literal."
);
else if (*literalArgumentKind == LiteralKind::String)
{
std::string functionName = _funCall.functionName.name.str();
if (functionName == "datasize" || functionName == "dataoffset")
{
auto const& argumentAsLiteral = std::get<Literal>(arg);
if (!m_objectStructure.contains(formatLiteral(argumentAsLiteral)))
m_errorReporter.typeError(
3517_error,
nativeLocationOf(arg),
"Unknown data object \"" + formatLiteral(argumentAsLiteral) + "\"."
);
}
else if (functionName.substr(0, "verbatim_"s.size()) == "verbatim_")
{
auto const& literalValue = std::get<Literal>(arg).value;
yulAssert(literalValue.unlimited()); // verbatim literals are always unlimited
if (literalValue.builtinStringLiteralValue().empty())
m_errorReporter.typeError(
1844_error,
nativeLocationOf(arg),
"The \"verbatim_*\" builtins cannot be used with empty bytecode."
);
}
else if (functionName == "eofcreate" || functionName == "returncontract")
{
auto const& argumentAsLiteral = std::get<Literal>(arg);
auto const formattedLiteral = formatLiteral(argumentAsLiteral);
if (util::contains(formattedLiteral, '.'))
m_errorReporter.typeError(
2186_error,
nativeLocationOf(arg),
"Name required but path given as \"" + functionName + "\" argument."
);
if (!m_objectStructure.topLevelSubObjectNames().count(formattedLiteral))
{
if (m_objectStructure.containsData(formattedLiteral))
m_errorReporter.typeError(
7575_error,
nativeLocationOf(arg),
"Data name \"" + formattedLiteral + "\" cannot be used as an argument of eofcreate/returncontract. " +
"An object name is only acceptable."
);
else
m_errorReporter.typeError(
8970_error,
nativeLocationOf(arg),
"Unknown object \"" + formattedLiteral + "\"."
);
}
}
expectUnlimitedStringLiteral(std::get<Literal>(arg));
continue;
}
else if (*literalArgumentKind == LiteralKind::Number)
{
std::string functionName = _funCall.functionName.name.str();
if (functionName == "auxdataloadn")
{
auto const& argumentAsLiteral = std::get<Literal>(arg);
if (argumentAsLiteral.value.value() > std::numeric_limits<uint16_t>::max())
m_errorReporter.typeError(
5202_error,
nativeLocationOf(arg),
"Invalid auxdataloadn argument value. Offset must be in range 0...0xFFFF"
);
}
}
}
expectExpression(arg);
}
if (watcher.ok())
{
yulAssert(numParameters && numParameters == _funCall.arguments.size());
yulAssert(numReturns);
return *numReturns;
}
else if (numReturns)
return *numReturns;
else
return {};
}
void AsmAnalyzer::operator()(If const& _if)
{
expectExpression(*_if.condition);
(*this)(_if.body);
}
void AsmAnalyzer::operator()(Switch const& _switch)
{
yulAssert(_switch.expression, "");
if (_switch.cases.size() == 1 && !_switch.cases[0].value)
m_errorReporter.warning(
9592_error,
nativeLocationOf(_switch),
"\"switch\" statement with only a default case."
);
expectExpression(*_switch.expression);
std::set<u256> cases;
for (auto const& _case: _switch.cases)
{
if (_case.value)
{
auto watcher = m_errorReporter.errorWatcher();
// We cannot use "expectExpression" here because *_case.value is not an
// Expression and would be converted to an Expression otherwise.
(*this)(*_case.value);
/// Note: the parser ensures there is only one default case
if (watcher.ok() && !cases.insert(_case.value->value.value()).second)
m_errorReporter.declarationError(
6792_error,
nativeLocationOf(_case),
"Duplicate case \"" +
formatLiteral(*_case.value) +
"\" defined."
);
}
(*this)(_case.body);
}
}
void AsmAnalyzer::operator()(ForLoop const& _for)
{
yulAssert(_for.condition, "");
Scope* outerScope = m_currentScope;
(*this)(_for.pre);
// The block was closed already, but we re-open it again and stuff the
// condition, the body and the post part inside.
m_currentScope = &scope(&_for.pre);
expectExpression(*_for.condition);
// backup outer for-loop & create new state
auto outerForLoop = m_currentForLoop;
m_currentForLoop = &_for;
(*this)(_for.body);
(*this)(_for.post);
m_currentScope = outerScope;
m_currentForLoop = outerForLoop;
}
void AsmAnalyzer::operator()(Block const& _block)
{
auto previousScope = m_currentScope;
m_currentScope = &scope(&_block);
for (auto const& s: _block.statements)
std::visit(*this, s);
m_currentScope = previousScope;
}
void AsmAnalyzer::expectExpression(Expression const& _expr)
{
size_t numValues = std::visit(*this, _expr);
if (numValues != 1)
m_errorReporter.typeError(
3950_error,
nativeLocationOf(_expr),
"Expected expression to evaluate to one value, but got " +
std::to_string(numValues) +
" values instead."
);
}
void AsmAnalyzer::expectUnlimitedStringLiteral(Literal const& _literal)
{
yulAssert(_literal.kind == LiteralKind::String);
yulAssert(_literal.value.unlimited());
}
void AsmAnalyzer::checkAssignment(Identifier const& _variable)
{
yulAssert(!_variable.name.empty(), "");
auto watcher = m_errorReporter.errorWatcher();
bool hasVariable = false;
bool found = false;
if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name))
{
if (m_resolver)
// We found a local reference, make sure there is no external reference.
m_resolver(
_variable,
yul::IdentifierContext::NonExternal,
m_currentScope->insideFunction()
);
if (!std::holds_alternative<Scope::Variable>(*var))
m_errorReporter.typeError(2657_error, nativeLocationOf(_variable), "Assignment requires variable.");
else if (!m_activeVariables.count(&std::get<Scope::Variable>(*var)))
m_errorReporter.declarationError(
1133_error,
nativeLocationOf(_variable),
"Variable " + _variable.name.str() + " used before it was declared."
);
else
hasVariable = true;
found = true;
}
else if (m_resolver)
{
bool insideFunction = m_currentScope->insideFunction();
if (m_resolver(_variable, yul::IdentifierContext::LValue, insideFunction))
{
found = true;
hasVariable = true;
}
}
if (!found && watcher.ok())
// Only add message if the callback did not.
m_errorReporter.declarationError(4634_error, nativeLocationOf(_variable), "Variable not found or variable not lvalue.");
yulAssert(!watcher.ok() || hasVariable, "");
}
Scope& AsmAnalyzer::scope(Block const* _block)
{
yulAssert(m_info.scopes.count(_block) == 1, "Scope requested but not present.");
auto scopePtr = m_info.scopes.at(_block);
yulAssert(scopePtr, "Scope requested but not present.");
return *scopePtr;
}
void AsmAnalyzer::expectValidIdentifier(YulName _identifier, SourceLocation const& _location)
{
// NOTE: the leading dot case is handled by the parser not allowing it.
if (boost::ends_with(_identifier.str(), "."))
m_errorReporter.syntaxError(
3384_error,
_location,
"\"" + _identifier.str() + "\" is not a valid identifier (ends with a dot)."
);
if (_identifier.str().find("..") != std::string::npos)
m_errorReporter.syntaxError(
7771_error,
_location,
"\"" + _identifier.str() + "\" is not a valid identifier (contains consecutive dots)."
);
if (m_dialect.reservedIdentifier(_identifier.str()))
m_errorReporter.declarationError(
5017_error,
_location,
"The identifier \"" + _identifier.str() + "\" is reserved and can not be used."
);
}
bool AsmAnalyzer::validateInstructions(std::string const& _instructionIdentifier, langutil::SourceLocation const& _location)
{
// NOTE: This function uses the default EVM version instead of the currently selected one.
auto const& defaultEVMDialect = EVMDialect::strictAssemblyForEVM(EVMVersion{}, std::nullopt);
auto const builtinHandle = defaultEVMDialect.findBuiltin(_instructionIdentifier);
if (builtinHandle && defaultEVMDialect.builtin(*builtinHandle).instruction.has_value())
return validateInstructions(*defaultEVMDialect.builtin(*builtinHandle).instruction, _location);
// TODO: Change `prague()` to `EVMVersion{}` once EOF gets deployed
auto const& eofDialect = EVMDialect::strictAssemblyForEVM(EVMVersion::prague(), 1);
auto const eofBuiltinHandle = eofDialect.findBuiltin(_instructionIdentifier);
if (eofBuiltinHandle && eofDialect.builtin(*eofBuiltinHandle).instruction.has_value())
return validateInstructions(*eofDialect.builtin(*eofBuiltinHandle).instruction, _location);
return false;
}
bool AsmAnalyzer::validateInstructions(evmasm::Instruction _instr, SourceLocation const& _location)
{
// We assume that returndatacopy, returndatasize and staticcall are either all available
// or all not available.
yulAssert(m_evmVersion.supportsReturndata() == m_evmVersion.hasStaticCall(), "");
// Similarly we assume bitwise shifting and create2 go together.
yulAssert(m_evmVersion.hasBitwiseShifting() == m_evmVersion.hasCreate2(), "");
// These instructions are disabled in the dialect.
yulAssert(
_instr != evmasm::Instruction::JUMP &&
_instr != evmasm::Instruction::JUMPI &&
_instr != evmasm::Instruction::JUMPDEST,
"");
auto errorForVM = [&](ErrorId _errorId, std::string const& vmKindMessage) {
m_errorReporter.typeError(
_errorId,
_location,
fmt::format(
"The \"{instruction}\" instruction is {kind} VMs (you are currently compiling for \"{version}\").",
fmt::arg("instruction", boost::to_lower_copy(instructionInfo(_instr, m_evmVersion).name)),
fmt::arg("kind", vmKindMessage),
fmt::arg("version", m_evmVersion.name())
)
);
};
// The errors below are meant to be issued when processing an undeclared identifier matching a builtin name
// present on the default EVM version but not on the currently selected one,
// since the other `validateInstructions()` overload uses the default EVM version.
if (_instr == evmasm::Instruction::RETURNDATACOPY && !m_evmVersion.supportsReturndata())
errorForVM(7756_error, "only available for Byzantium-compatible");
else if (_instr == evmasm::Instruction::RETURNDATASIZE && !m_evmVersion.supportsReturndata())
errorForVM(4778_error, "only available for Byzantium-compatible");
else if (_instr == evmasm::Instruction::STATICCALL && !m_evmVersion.hasStaticCall())
errorForVM(1503_error, "only available for Byzantium-compatible");
else if (_instr == evmasm::Instruction::SHL && !m_evmVersion.hasBitwiseShifting())
errorForVM(6612_error, "only available for Constantinople-compatible");
else if (_instr == evmasm::Instruction::SHR && !m_evmVersion.hasBitwiseShifting())
errorForVM(7458_error, "only available for Constantinople-compatible");
else if (_instr == evmasm::Instruction::SAR && !m_evmVersion.hasBitwiseShifting())
errorForVM(2054_error, "only available for Constantinople-compatible");
else if (_instr == evmasm::Instruction::CREATE2 && !m_evmVersion.hasCreate2())
errorForVM(6166_error, "only available for Constantinople-compatible");
else if (_instr == evmasm::Instruction::EXTCODEHASH && !m_evmVersion.hasExtCodeHash())
errorForVM(7110_error, "only available for Constantinople-compatible");
else if (_instr == evmasm::Instruction::CHAINID && !m_evmVersion.hasChainID())
errorForVM(1561_error, "only available for Istanbul-compatible");
else if (_instr == evmasm::Instruction::SELFBALANCE && !m_evmVersion.hasSelfBalance())
errorForVM(7721_error, "only available for Istanbul-compatible");
else if (_instr == evmasm::Instruction::BASEFEE && !m_evmVersion.hasBaseFee())
errorForVM(5430_error, "only available for London-compatible");
else if (_instr == evmasm::Instruction::BLOBBASEFEE && !m_evmVersion.hasBlobBaseFee())
errorForVM(6679_error, "only available for Cancun-compatible");
else if (_instr == evmasm::Instruction::BLOBHASH && !m_evmVersion.hasBlobHash())
errorForVM(8314_error, "only available for Cancun-compatible");
else if (_instr == evmasm::Instruction::MCOPY && !m_evmVersion.hasMcopy())
errorForVM(7755_error, "only available for Cancun-compatible");
else if ((_instr == evmasm::Instruction::TSTORE || _instr == evmasm::Instruction::TLOAD) && !m_evmVersion.supportsTransientStorage())
errorForVM(6243_error, "only available for Cancun-compatible");
else if (_instr == evmasm::Instruction::PC)
m_errorReporter.error(
2450_error,
Error::Type::SyntaxError,
_location,
"PC instruction is a low-level EVM feature. "
"Because of that PC is disallowed in strict assembly."
);
else if (m_eofVersion.has_value() && (
_instr == evmasm::Instruction::CALL ||
_instr == evmasm::Instruction::CALLCODE ||
_instr == evmasm::Instruction::DELEGATECALL ||
_instr == evmasm::Instruction::SELFDESTRUCT ||
_instr == evmasm::Instruction::JUMP ||
_instr == evmasm::Instruction::JUMPI ||
_instr == evmasm::Instruction::PC ||
_instr == evmasm::Instruction::CREATE ||
_instr == evmasm::Instruction::CODESIZE ||
_instr == evmasm::Instruction::CODECOPY ||
_instr == evmasm::Instruction::EXTCODESIZE ||
_instr == evmasm::Instruction::EXTCODECOPY ||
_instr == evmasm::Instruction::GAS
))
{
m_errorReporter.typeError(
9132_error,
_location,
fmt::format(
"The \"{instruction}\" instruction is {kind} VMs (you are currently compiling to EOF).",
fmt::arg("instruction", boost::to_lower_copy(instructionInfo(_instr, m_evmVersion).name)),
fmt::arg("kind", "only available in legacy bytecode")
)
);
}
else
{
// Sanity check
solAssert(m_evmVersion.hasOpcode(_instr, m_eofVersion));
return false;
}
// Sanity check
// PC is not available in strict assembly but it is always valid opcode in legacy evm.
solAssert(_instr == evmasm::Instruction::PC || !m_evmVersion.hasOpcode(_instr, m_eofVersion));
return true;
}
bool AsmAnalyzer::validateInstructions(FunctionCall const& _functionCall)
{
return validateInstructions(_functionCall.functionName.name.str(), nativeLocationOf(_functionCall.functionName));
}
void AsmAnalyzer::validateObjectStructure(langutil::SourceLocation _astRootLocation)
{
if (m_eofVersion.has_value() && util::contains(m_objectStructure.objectName, '.')) // No dots in object name for EOF
m_errorReporter.syntaxError(
9822_error,
_astRootLocation,
fmt::format(
"The object name \"{objectName}\" is invalid in EOF context. Object names must not contain 'dot' character.",
fmt::arg("objectName", m_objectStructure.objectName)
)
);
}
| 27,410
|
C++
|
.cpp
| 730
| 34.256164
| 161
| 0.724039
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,058
|
YulControlFlowGraphExporter.cpp
|
ethereum_solidity/libyul/YulControlFlowGraphExporter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/Utilities.h>
#include <libyul/YulControlFlowGraphExporter.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/Numeric.h>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/transform.hpp>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::yul;
YulControlFlowGraphExporter::YulControlFlowGraphExporter(ControlFlow const& _controlFlow): m_controlFlow(_controlFlow)
{
}
std::string YulControlFlowGraphExporter::varToString(SSACFG const& _cfg, SSACFG::ValueId _var)
{
if (_var.value == std::numeric_limits<size_t>::max())
return std::string("INVALID");
auto const& info = _cfg.valueInfo(_var);
return std::visit(
util::GenericVisitor{
[&](SSACFG::UnreachableValue const&) -> std::string {
return "[unreachable]";
},
[&](SSACFG::LiteralValue const& _literal) {
return toCompactHexWithPrefix(_literal.value);
},
[&](auto const&) {
return "v" + std::to_string(_var.value);
}
},
info
);
}
Json YulControlFlowGraphExporter::run()
{
Json yulObjectJson = Json::object();
yulObjectJson["blocks"] = exportBlock(*m_controlFlow.mainGraph, SSACFG::BlockId{0});
Json functionsJson = Json::object();
for (auto const& [function, functionGraph]: m_controlFlow.functionGraphMapping)
functionsJson[function->name.str()] = exportFunction(*functionGraph);
yulObjectJson["functions"] = functionsJson;
return yulObjectJson;
}
Json YulControlFlowGraphExporter::exportFunction(SSACFG const& _cfg)
{
Json functionJson = Json::object();
functionJson["type"] = "Function";
functionJson["entry"] = "Block" + std::to_string(_cfg.entry.value);
static auto constexpr argsTransform = [](auto const& _arg) { return fmt::format("v{}", std::get<1>(_arg).value); };
functionJson["arguments"] = _cfg.arguments | ranges::views::transform(argsTransform) | ranges::to<std::vector>;
functionJson["numReturns"] = _cfg.returns.size();
functionJson["blocks"] = exportBlock(_cfg, _cfg.entry);
return functionJson;
}
Json YulControlFlowGraphExporter::exportBlock(SSACFG const& _cfg, SSACFG::BlockId _entryId)
{
Json blocksJson = Json::array();
util::BreadthFirstSearch<SSACFG::BlockId> bfs{{{_entryId}}};
bfs.run([&](SSACFG::BlockId _blockId, auto _addChild) {
auto const& block = _cfg.block(_blockId);
// Convert current block to JSON
Json blockJson = toJson(_cfg, _blockId);
Json exitBlockJson = Json::object();
std::visit(util::GenericVisitor{
[&](SSACFG::BasicBlock::MainExit const&) {
exitBlockJson["type"] = "MainExit";
},
[&](SSACFG::BasicBlock::Jump const& _jump)
{
exitBlockJson["targets"] = { "Block" + std::to_string(_jump.target.value) };
exitBlockJson["type"] = "Jump";
_addChild(_jump.target);
},
[&](SSACFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
exitBlockJson["targets"] = { "Block" + std::to_string(_conditionalJump.zero.value), "Block" + std::to_string(_conditionalJump.nonZero.value) };
exitBlockJson["cond"] = varToString(_cfg, _conditionalJump.condition);
exitBlockJson["type"] = "ConditionalJump";
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](SSACFG::BasicBlock::FunctionReturn const& _return) {
exitBlockJson["returnValues"] = toJson(_cfg, _return.returnValues);
exitBlockJson["type"] = "FunctionReturn";
},
[&](SSACFG::BasicBlock::Terminated const&) {
exitBlockJson["type"] = "Terminated";
},
[&](SSACFG::BasicBlock::JumpTable const&) {
yulAssert(false);
}
}, block.exit);
blockJson["exit"] = exitBlockJson;
blocksJson.emplace_back(blockJson);
});
return blocksJson;
}
Json YulControlFlowGraphExporter::toJson(SSACFG const& _cfg, SSACFG::BlockId _blockId)
{
Json blockJson = Json::object();
auto const& block = _cfg.block(_blockId);
blockJson["id"] = "Block" + std::to_string(_blockId.value);
blockJson["instructions"] = Json::array();
if (!block.phis.empty())
{
blockJson["entries"] = block.entries
| ranges::views::transform([](auto const& entry) { return "Block" + std::to_string(entry.value); })
| ranges::to<Json::array_t>();
for (auto const& phi: block.phis)
{
auto* phiInfo = std::get_if<SSACFG::PhiValue>(&_cfg.valueInfo(phi));
yulAssert(phiInfo);
Json phiJson = Json::object();
phiJson["op"] = "PhiFunction";
phiJson["in"] = toJson(_cfg, phiInfo->arguments);
phiJson["out"] = toJson(_cfg, std::vector<SSACFG::ValueId>{phi});
blockJson["instructions"].push_back(phiJson);
}
}
for (auto const& operation: block.operations)
blockJson["instructions"].push_back(toJson(blockJson, _cfg, operation));
return blockJson;
}
Json YulControlFlowGraphExporter::toJson(Json& _ret, SSACFG const& _cfg, SSACFG::Operation const& _operation)
{
Json opJson = Json::object();
std::visit(util::GenericVisitor{
[&](SSACFG::Call const& _call) {
_ret["type"] = "FunctionCall";
opJson["op"] = _call.function.get().name.str();
},
[&](SSACFG::BuiltinCall const& _call) {
_ret["type"] = "BuiltinCall";
Json builtinArgsJson = Json::array();
auto const& builtin = _call.builtin.get();
if (!builtin.literalArguments.empty())
{
auto const& functionCallArgs = _call.call.get().arguments;
for (size_t i = 0; i < builtin.literalArguments.size(); ++i)
{
std::optional<LiteralKind> const& argument = builtin.literalArguments[i];
if (argument.has_value() && i < functionCallArgs.size())
{
// The function call argument at index i must be a literal if builtin.literalArguments[i] is not nullopt
yulAssert(std::holds_alternative<Literal>(functionCallArgs[i]));
builtinArgsJson.push_back(formatLiteral(std::get<Literal>(functionCallArgs[i])));
}
}
}
if (!builtinArgsJson.empty())
opJson["builtinArgs"] = builtinArgsJson;
opJson["op"] = _call.builtin.get().name;
},
}, _operation.kind);
opJson["in"] = toJson(_cfg, _operation.inputs);
opJson["out"] = toJson(_cfg, _operation.outputs);
return opJson;
}
Json YulControlFlowGraphExporter::toJson(SSACFG const& _cfg, std::vector<SSACFG::ValueId> const& _values)
{
Json ret = Json::array();
for (auto const& value: _values)
ret.push_back(varToString(_cfg, value));
return ret;
}
| 6,985
|
C++
|
.cpp
| 180
| 35.788889
| 147
| 0.713822
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,059
|
AsmJsonConverter.cpp
|
ethereum_solidity/libyul/AsmJsonConverter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @date 2019
* Converts inline assembly AST to JSON format
*/
#include <libyul/AST.h>
#include <libyul/AsmJsonConverter.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/UTF8.h>
namespace solidity::yul
{
Json AsmJsonConverter::operator()(Block const& _node) const
{
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulBlock");
ret["statements"] = vectorOfVariantsToJson(_node.statements);
return ret;
}
Json AsmJsonConverter::operator()(NameWithDebugData const& _node) const
{
yulAssert(!_node.name.empty(), "Invalid variable name.");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulTypedName");
ret["name"] = _node.name.str();
// even though types are removed from Yul, we keep this field in the Json interface to not introduce
// a breaking change
// can be removed with the next breaking version
ret["type"] = "";
return ret;
}
Json AsmJsonConverter::operator()(Literal const& _node) const
{
yulAssert(validLiteral(_node));
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulLiteral");
switch (_node.kind)
{
case LiteralKind::Number:
ret["kind"] = "number";
break;
case LiteralKind::Boolean:
ret["kind"] = "bool";
break;
case LiteralKind::String:
ret["kind"] = "string";
ret["hexValue"] = util::toHex(util::asBytes(formatLiteral(_node)));
break;
}
ret["type"] = "";
{
auto const formattedLiteral = formatLiteral(_node);
if (util::validateUTF8(formattedLiteral))
ret["value"] = formattedLiteral;
}
return ret;
}
Json AsmJsonConverter::operator()(Identifier const& _node) const
{
yulAssert(!_node.name.empty(), "Invalid identifier");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulIdentifier");
ret["name"] = _node.name.str();
return ret;
}
Json AsmJsonConverter::operator()(Assignment const& _node) const
{
yulAssert(_node.variableNames.size() >= 1, "Invalid assignment syntax");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulAssignment");
for (auto const& var: _node.variableNames)
ret["variableNames"].emplace_back((*this)(var));
ret["value"] = _node.value ? std::visit(*this, *_node.value) : Json();
return ret;
}
Json AsmJsonConverter::operator()(FunctionCall const& _node) const
{
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulFunctionCall");
ret["functionName"] = (*this)(_node.functionName);
ret["arguments"] = vectorOfVariantsToJson(_node.arguments);
return ret;
}
Json AsmJsonConverter::operator()(ExpressionStatement const& _node) const
{
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulExpressionStatement");
ret["expression"] = std::visit(*this, _node.expression);
return ret;
}
Json AsmJsonConverter::operator()(VariableDeclaration const& _node) const
{
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulVariableDeclaration");
for (auto const& var: _node.variables)
ret["variables"].emplace_back((*this)(var));
ret["value"] = _node.value ? std::visit(*this, *_node.value) : Json();
return ret;
}
Json AsmJsonConverter::operator()(FunctionDefinition const& _node) const
{
yulAssert(!_node.name.empty(), "Invalid function name.");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulFunctionDefinition");
ret["name"] = _node.name.str();
for (auto const& var: _node.parameters)
ret["parameters"].emplace_back((*this)(var));
for (auto const& var: _node.returnVariables)
ret["returnVariables"].emplace_back((*this)(var));
ret["body"] = (*this)(_node.body);
return ret;
}
Json AsmJsonConverter::operator()(If const& _node) const
{
yulAssert(_node.condition, "Invalid if condition.");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulIf");
ret["condition"] = std::visit(*this, *_node.condition);
ret["body"] = (*this)(_node.body);
return ret;
}
Json AsmJsonConverter::operator()(Switch const& _node) const
{
yulAssert(_node.expression, "Invalid expression pointer.");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulSwitch");
ret["expression"] = std::visit(*this, *_node.expression);
for (auto const& var: _node.cases)
ret["cases"].emplace_back((*this)(var));
return ret;
}
Json AsmJsonConverter::operator()(Case const& _node) const
{
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulCase");
ret["value"] = _node.value ? (*this)(*_node.value) : "default";
ret["body"] = (*this)(_node.body);
return ret;
}
Json AsmJsonConverter::operator()(ForLoop const& _node) const
{
yulAssert(_node.condition, "Invalid for loop condition.");
Json ret = createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulForLoop");
ret["pre"] = (*this)(_node.pre);
ret["condition"] = std::visit(*this, *_node.condition);
ret["post"] = (*this)(_node.post);
ret["body"] = (*this)(_node.body);
return ret;
}
Json AsmJsonConverter::operator()(Break const& _node) const
{
return createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulBreak");
}
Json AsmJsonConverter::operator()(Continue const& _node) const
{
return createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulContinue");
}
Json AsmJsonConverter::operator()(Leave const& _node) const
{
return createAstNode(originLocationOf(_node), nativeLocationOf(_node), "YulLeave");
}
Json AsmJsonConverter::createAstNode(langutil::SourceLocation const& _originLocation, langutil::SourceLocation const& _nativeLocation, std::string _nodeType) const
{
Json ret;
ret["nodeType"] = std::move(_nodeType);
auto srcLocation = [&](int start, int end) -> std::string
{
int length = (start >= 0 && end >= 0 && end >= start) ? end - start : -1;
return std::to_string(start) + ":" + std::to_string(length) + ":" + (m_sourceIndex.has_value() ? std::to_string(m_sourceIndex.value()) : "-1");
};
ret["src"] = srcLocation(_originLocation.start, _originLocation.end);
ret["nativeSrc"] = srcLocation(_nativeLocation.start, _nativeLocation.end);
return ret;
}
template <class T>
Json AsmJsonConverter::vectorOfVariantsToJson(std::vector<T> const& _vec) const
{
Json ret = Json::array();
for (auto const& var: _vec)
ret.emplace_back(std::visit(*this, var));
return ret;
}
}
| 7,086
|
C++
|
.cpp
| 185
| 36.437838
| 163
| 0.736368
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,060
|
AsmPrinter.cpp
|
ethereum_solidity/libyul/AsmPrinter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <c@ethdev.com>
* @date 2017
* Converts a parsed assembly into its textual form.
*/
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <range/v3/view/transform.hpp>
#include <functional>
#include <memory>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::yul;
std::string AsmPrinter::operator()(Literal const& _literal)
{
yulAssert(validLiteral(_literal));
std::string const locationComment = formatDebugData(_literal);
std::string const formattedValue = formatLiteral(_literal);
switch (_literal.kind)
{
case LiteralKind::Number:
case LiteralKind::Boolean:
return locationComment + formattedValue;
case LiteralKind::String:
break;
}
return locationComment + escapeAndQuoteString(formattedValue);
}
std::string AsmPrinter::operator()(Identifier const& _identifier)
{
yulAssert(!_identifier.name.empty(), "Invalid identifier.");
return formatDebugData(_identifier) + _identifier.name.str();
}
std::string AsmPrinter::operator()(ExpressionStatement const& _statement)
{
std::string const locationComment = formatDebugData(_statement);
return locationComment + std::visit(*this, _statement.expression);
}
std::string AsmPrinter::operator()(Assignment const& _assignment)
{
std::string const locationComment = formatDebugData(_assignment);
yulAssert(_assignment.variableNames.size() >= 1, "");
std::string variables = (*this)(_assignment.variableNames.front());
for (size_t i = 1; i < _assignment.variableNames.size(); ++i)
variables += ", " + (*this)(_assignment.variableNames[i]);
return locationComment + variables + " := " + std::visit(*this, *_assignment.value);
}
std::string AsmPrinter::operator()(VariableDeclaration const& _variableDeclaration)
{
std::string out = formatDebugData(_variableDeclaration);
out += "let ";
out += boost::algorithm::join(
_variableDeclaration.variables | ranges::views::transform(
[this](NameWithDebugData argument) { return formatNameWithDebugData(argument); }
),
", "
);
if (_variableDeclaration.value)
{
out += " := ";
out += std::visit(*this, *_variableDeclaration.value);
}
return out;
}
std::string AsmPrinter::operator()(FunctionDefinition const& _functionDefinition)
{
yulAssert(!_functionDefinition.name.empty(), "Invalid function name.");
std::string out = formatDebugData(_functionDefinition);
out += "function " + _functionDefinition.name.str() + "(";
out += boost::algorithm::join(
_functionDefinition.parameters | ranges::views::transform(
[this](NameWithDebugData argument) { return formatNameWithDebugData(argument); }
),
", "
);
out += ")";
if (!_functionDefinition.returnVariables.empty())
{
out += " -> ";
out += boost::algorithm::join(
_functionDefinition.returnVariables | ranges::views::transform(
[this](NameWithDebugData argument) { return formatNameWithDebugData(argument); }
),
", "
);
}
return out + "\n" + (*this)(_functionDefinition.body);
}
std::string AsmPrinter::operator()(FunctionCall const& _functionCall)
{
std::string const locationComment = formatDebugData(_functionCall);
std::string const functionName = (*this)(_functionCall.functionName);
return
locationComment +
functionName + "(" +
boost::algorithm::join(
_functionCall.arguments | ranges::views::transform([&](auto&& _node) { return std::visit(*this, _node); }),
", " ) +
")";
}
std::string AsmPrinter::operator()(If const& _if)
{
yulAssert(_if.condition, "Invalid if condition.");
std::string out = formatDebugData(_if);
out += "if " + std::visit(*this, *_if.condition);
std::string body = (*this)(_if.body);
char delim = '\n';
if (body.find('\n') == std::string::npos)
delim = ' ';
return out + delim + body;
}
std::string AsmPrinter::operator()(Switch const& _switch)
{
yulAssert(_switch.expression, "Invalid expression pointer.");
std::string out = formatDebugData(_switch);
out += "switch " + std::visit(*this, *_switch.expression);
for (auto const& _case: _switch.cases)
{
if (!_case.value)
out += "\ndefault ";
else
out += "\ncase " + (*this)(*_case.value) + " ";
out += (*this)(_case.body);
}
return out;
}
std::string AsmPrinter::operator()(ForLoop const& _forLoop)
{
yulAssert(_forLoop.condition, "Invalid for loop condition.");
std::string const locationComment = formatDebugData(_forLoop);
std::string pre = (*this)(_forLoop.pre);
std::string condition = std::visit(*this, *_forLoop.condition);
std::string post = (*this)(_forLoop.post);
char delim = '\n';
if (
pre.size() + condition.size() + post.size() < 60 &&
pre.find('\n') == std::string::npos &&
post.find('\n') == std::string::npos
)
delim = ' ';
return
locationComment +
("for " + std::move(pre) + delim + std::move(condition) + delim + std::move(post) + "\n") +
(*this)(_forLoop.body);
}
std::string AsmPrinter::operator()(Break const& _break)
{
return formatDebugData(_break) + "break";
}
std::string AsmPrinter::operator()(Continue const& _continue)
{
return formatDebugData(_continue) + "continue";
}
// '_leave' and '__leave' is reserved in VisualStudio
std::string AsmPrinter::operator()(Leave const& leave_)
{
return formatDebugData(leave_) + "leave";
}
std::string AsmPrinter::operator()(Block const& _block)
{
std::string const locationComment = formatDebugData(_block);
if (_block.statements.empty())
return locationComment + "{ }";
std::string body = boost::algorithm::join(
_block.statements | ranges::views::transform([&](auto&& _node) { return std::visit(*this, _node); }),
"\n"
);
if (body.size() < 30 && body.find('\n') == std::string::npos)
return locationComment + "{ " + body + " }";
else
{
boost::replace_all(body, "\n", "\n ");
return locationComment + "{\n " + body + "\n}";
}
}
std::string AsmPrinter::formatNameWithDebugData(NameWithDebugData _variable)
{
yulAssert(!_variable.name.empty(), "Invalid variable name.");
return formatDebugData(_variable) + _variable.name.str();
}
std::string AsmPrinter::formatSourceLocation(
SourceLocation const& _location,
std::map<std::string, unsigned> const& _nameToSourceIndex,
DebugInfoSelection const& _debugInfoSelection,
CharStreamProvider const* _soliditySourceProvider
)
{
yulAssert(!_nameToSourceIndex.empty(), "");
if (_debugInfoSelection.snippet)
yulAssert(_debugInfoSelection.location, "@src tag must always contain the source location");
if (_debugInfoSelection.none())
return "";
std::string sourceIndex = "-1";
std::string solidityCodeSnippet = "";
if (_location.sourceName)
{
sourceIndex = std::to_string(_nameToSourceIndex.at(*_location.sourceName));
if (
_debugInfoSelection.snippet &&
_soliditySourceProvider &&
!_soliditySourceProvider->charStream(*_location.sourceName).isImportedFromAST()
)
{
solidityCodeSnippet = escapeAndQuoteString(
_soliditySourceProvider->charStream(*_location.sourceName).singleLineSnippet(_location)
);
// On top of escaping quotes we also escape the slash inside any `*/` to guard against
// it prematurely terminating multi-line comment blocks. We do not escape all slashes
// because the ones without `*` are not dangerous and ignoring them reduces visual noise.
boost::replace_all(solidityCodeSnippet, "*/", "*\\/");
}
}
std::string sourceLocation =
"@src " +
sourceIndex +
":" +
std::to_string(_location.start) +
":" +
std::to_string(_location.end);
return sourceLocation + (solidityCodeSnippet.empty() ? "" : " ") + solidityCodeSnippet;
}
std::string AsmPrinter::formatDebugData(langutil::DebugData::ConstPtr const& _debugData, bool _statement)
{
if (!_debugData || m_debugInfoSelection.none())
return "";
std::vector<std::string> items;
if (auto id = _debugData->astID)
if (m_debugInfoSelection.astID)
items.emplace_back("@ast-id " + std::to_string(*id));
if (
m_lastLocation != _debugData->originLocation &&
!m_nameToSourceIndex.empty()
)
{
m_lastLocation = _debugData->originLocation;
items.emplace_back(formatSourceLocation(
_debugData->originLocation,
m_nameToSourceIndex,
m_debugInfoSelection,
m_soliditySourceProvider
));
}
std::string commentBody = joinHumanReadable(items, " ");
if (commentBody.empty())
return "";
else
return
_statement ?
"/// " + commentBody + "\n" :
"/** " + commentBody + " */ ";
}
| 9,293
|
C++
|
.cpp
| 272
| 31.8125
| 110
| 0.720227
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,061
|
Dialect.cpp
|
ethereum_solidity/libyul/Dialect.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul dialect.
*/
#include <libyul/Dialect.h>
#include <libyul/AST.h>
using namespace solidity::yul;
using namespace solidity::langutil;
Literal Dialect::zeroLiteral() const
{
return {DebugData::create(), LiteralKind::Number, LiteralValue(0, std::nullopt)};
}
| 955
|
C++
|
.cpp
| 25
| 36.4
| 82
| 0.780303
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,062
|
ControlFlowSideEffectsCollector.cpp
|
ethereum_solidity/libyul/ControlFlowSideEffectsCollector.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libyul/FunctionReferenceResolver.h>
#include <libsolutil/Common.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Algorithms.h>
#include <range/v3/view/map.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/algorithm/find_if.hpp>
using namespace solidity::yul;
ControlFlowBuilder::ControlFlowBuilder(Block const& _ast)
{
m_currentNode = newNode();
(*this)(_ast);
}
void ControlFlowBuilder::operator()(FunctionCall const& _functionCall)
{
walkVector(_functionCall.arguments | ranges::views::reverse);
newConnectedNode();
m_currentNode->functionCall = &_functionCall;
}
void ControlFlowBuilder::operator()(If const& _if)
{
visit(*_if.condition);
ControlFlowNode* node = m_currentNode;
ControlFlowNode* ifEnd = newNode();
node->successors.emplace_back(ifEnd);
newConnectedNode();
(*this)(_if.body);
m_currentNode->successors.emplace_back(ifEnd);
m_currentNode = ifEnd;
}
void ControlFlowBuilder::operator()(Switch const& _switch)
{
visit(*_switch.expression);
ControlFlowNode* initialNode = m_currentNode;
ControlFlowNode* finalNode = newNode();
if (_switch.cases.back().value)
initialNode->successors.emplace_back(finalNode);
for (Case const& case_: _switch.cases)
{
m_currentNode = initialNode;
newConnectedNode();
(*this)(case_.body);
m_currentNode->successors.emplace_back(finalNode);
}
m_currentNode = finalNode;
}
void ControlFlowBuilder::operator()(FunctionDefinition const& _function)
{
ScopedSaveAndRestore currentNode(m_currentNode, nullptr);
ScopedSaveAndRestore leave(m_leave, nullptr);
ScopedSaveAndRestore _break(m_break, nullptr);
ScopedSaveAndRestore _continue(m_continue, nullptr);
FunctionFlow flow;
flow.exit = newNode();
m_currentNode = newNode();
flow.entry = m_currentNode;
m_leave = flow.exit;
(*this)(_function.body);
m_currentNode->successors.emplace_back(flow.exit);
m_functionFlows[&_function] = std::move(flow);
m_leave = nullptr;
}
void ControlFlowBuilder::operator()(ForLoop const& _for)
{
ScopedSaveAndRestore scopedBreakNode(m_break, nullptr);
ScopedSaveAndRestore scopedContinueNode(m_continue, nullptr);
(*this)(_for.pre);
ControlFlowNode* breakNode = newNode();
m_break = breakNode;
ControlFlowNode* continueNode = newNode();
m_continue = continueNode;
newConnectedNode();
ControlFlowNode* loopNode = m_currentNode;
visit(*_for.condition);
m_currentNode->successors.emplace_back(m_break);
newConnectedNode();
(*this)(_for.body);
m_currentNode->successors.emplace_back(m_continue);
m_currentNode = continueNode;
(*this)(_for.post);
m_currentNode->successors.emplace_back(loopNode);
m_currentNode = breakNode;
}
void ControlFlowBuilder::operator()(Break const&)
{
yulAssert(m_break);
m_currentNode->successors.emplace_back(m_break);
m_currentNode = newNode();
}
void ControlFlowBuilder::operator()(Continue const&)
{
yulAssert(m_continue);
m_currentNode->successors.emplace_back(m_continue);
m_currentNode = newNode();
}
void ControlFlowBuilder::operator()(Leave const&)
{
yulAssert(m_leave);
m_currentNode->successors.emplace_back(m_leave);
m_currentNode = newNode();
}
void ControlFlowBuilder::newConnectedNode()
{
ControlFlowNode* node = newNode();
m_currentNode->successors.emplace_back(node);
m_currentNode = node;
}
ControlFlowNode* ControlFlowBuilder::newNode()
{
m_nodes.emplace_back(std::make_shared<ControlFlowNode>());
return m_nodes.back().get();
}
ControlFlowSideEffectsCollector::ControlFlowSideEffectsCollector(
Dialect const& _dialect,
Block const& _ast
):
m_dialect(_dialect),
m_cfgBuilder(_ast),
m_functionReferences(FunctionReferenceResolver{_ast}.references())
{
for (auto&& [function, flow]: m_cfgBuilder.functionFlows())
{
yulAssert(!flow.entry->functionCall);
yulAssert(function);
m_processedNodes[function] = {};
m_pendingNodes[function].push_front(flow.entry);
m_functionSideEffects[function] = {false, false, false};
m_functionCalls[function] = {};
}
// Process functions while we have progress. For now, we are only interested
// in `canContinue`.
bool progress = true;
while (progress)
{
progress = false;
for (FunctionDefinition const* function: m_pendingNodes | ranges::views::keys)
if (processFunction(*function))
progress = true;
}
// No progress anymore: All remaining nodes are calls
// to functions that always recurse.
// If we have not set `canContinue` by now, the function's exit
// is not reachable.
// Now it is sufficient to handle the reachable function calls (`m_functionCalls`),
// we do not have to consider the control-flow graph anymore.
for (auto&& [function, calls]: m_functionCalls)
{
yulAssert(function);
ControlFlowSideEffects& functionSideEffects = m_functionSideEffects[function];
auto _visit = [&, visited = std::set<FunctionDefinition const*>{}](FunctionDefinition const& _function, auto&& _recurse) mutable {
// Worst side-effects already, stop searching.
if (functionSideEffects.canTerminate && functionSideEffects.canRevert)
return;
if (!visited.insert(&_function).second)
return;
for (FunctionCall const* call: m_functionCalls.at(&_function))
{
ControlFlowSideEffects const& calledSideEffects = sideEffects(*call);
if (calledSideEffects.canTerminate)
functionSideEffects.canTerminate = true;
if (calledSideEffects.canRevert)
functionSideEffects.canRevert = true;
if (m_functionReferences.count(call))
_recurse(*m_functionReferences.at(call), _recurse);
}
};
_visit(*function, _visit);
}
}
std::map<YulName, ControlFlowSideEffects> ControlFlowSideEffectsCollector::functionSideEffectsNamed() const
{
std::map<YulName, ControlFlowSideEffects> result;
for (auto&& [function, sideEffects]: m_functionSideEffects)
yulAssert(result.insert({function->name, sideEffects}).second);
return result;
}
bool ControlFlowSideEffectsCollector::processFunction(FunctionDefinition const& _function)
{
bool progress = false;
while (ControlFlowNode const* node = nextProcessableNode(_function))
{
if (node == m_cfgBuilder.functionFlows().at(&_function).exit)
{
m_functionSideEffects[&_function].canContinue = true;
return true;
}
for (ControlFlowNode const* s: node->successors)
recordReachabilityAndQueue(_function, s);
progress = true;
}
return progress;
}
ControlFlowNode const* ControlFlowSideEffectsCollector::nextProcessableNode(FunctionDefinition const& _function)
{
std::list<ControlFlowNode const*>& nodes = m_pendingNodes[&_function];
auto it = ranges::find_if(nodes, [this](ControlFlowNode const* _node) {
return !_node->functionCall || sideEffects(*_node->functionCall).canContinue;
});
if (it == nodes.end())
return nullptr;
ControlFlowNode const* node = *it;
nodes.erase(it);
return node;
}
ControlFlowSideEffects const& ControlFlowSideEffectsCollector::sideEffects(FunctionCall const& _call) const
{
if (std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(_call.functionName.name.str()))
return m_dialect.builtin(*builtinHandle).controlFlowSideEffects;
else
return m_functionSideEffects.at(m_functionReferences.at(&_call));
}
void ControlFlowSideEffectsCollector::recordReachabilityAndQueue(
FunctionDefinition const& _function,
ControlFlowNode const* _node
)
{
if (_node->functionCall)
m_functionCalls[&_function].insert(_node->functionCall);
if (m_processedNodes[&_function].insert(_node).second)
m_pendingNodes.at(&_function).push_front(_node);
}
| 8,260
|
C++
|
.cpp
| 238
| 32.42437
| 132
| 0.772425
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,063
|
ObjectOptimizer.cpp
|
ethereum_solidity/libyul/ObjectOptimizer.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/ObjectOptimizer.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/EVMMetrics.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/Suite.h>
#include <liblangutil/DebugInfoSelection.h>
#include <libsolutil/Keccak256.h>
#include <boost/algorithm/string.hpp>
#include <limits>
#include <numeric>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::yul;
Dialect const& yul::languageToDialect(Language _language, EVMVersion _version, std::optional<uint8_t> _eofVersion)
{
switch (_language)
{
case Language::Assembly:
case Language::StrictAssembly:
return EVMDialect::strictAssemblyForEVMObjects(_version, _eofVersion);
}
util::unreachable();
}
void ObjectOptimizer::optimize(Object& _object, Settings const& _settings)
{
yulAssert(_object.subId == std::numeric_limits<size_t>::max(), "Not a top-level object.");
optimize(_object, _settings, true /* _isCreation */);
}
void ObjectOptimizer::optimize(Object& _object, Settings const& _settings, bool _isCreation)
{
yulAssert(_object.code());
yulAssert(_object.debugData);
for (auto& subNode: _object.subObjects)
if (auto subObject = dynamic_cast<Object*>(subNode.get()))
{
bool isCreation = !boost::ends_with(subObject->name, "_deployed");
optimize(
*subObject,
_settings,
isCreation
);
}
Dialect const& dialect = languageToDialect(_settings.language, _settings.evmVersion, _settings.eofVersion);
std::unique_ptr<GasMeter> meter;
if (EVMDialect const* evmDialect = dynamic_cast<EVMDialect const*>(&dialect))
meter = std::make_unique<GasMeter>(*evmDialect, _isCreation, _settings.expectedExecutionsPerDeployment);
std::optional<h256> cacheKey = calculateCacheKey(_object.code()->root(), *_object.debugData, _settings, _isCreation);
if (cacheKey.has_value() && m_cachedObjects.count(*cacheKey) != 0)
{
overwriteWithOptimizedObject(*cacheKey, _object);
return;
}
OptimiserSuite::run(
dialect,
meter.get(),
_object,
_settings.optimizeStackAllocation,
_settings.yulOptimiserSteps,
_settings.yulOptimiserCleanupSteps,
_isCreation ? std::nullopt : std::make_optional(_settings.expectedExecutionsPerDeployment),
{}
);
if (cacheKey.has_value())
storeOptimizedObject(*cacheKey, _object, dialect);
}
void ObjectOptimizer::storeOptimizedObject(util::h256 _cacheKey, Object const& _optimizedObject, Dialect const& _dialect)
{
m_cachedObjects[_cacheKey] = CachedObject{
std::make_shared<Block>(ASTCopier{}.translate(_optimizedObject.code()->root())),
&_dialect,
};
}
void ObjectOptimizer::overwriteWithOptimizedObject(util::h256 _cacheKey, Object& _object) const
{
yulAssert(m_cachedObjects.count(_cacheKey) != 0);
CachedObject const& cachedObject = m_cachedObjects.at(_cacheKey);
yulAssert(cachedObject.optimizedAST);
_object.setCode(std::make_shared<AST>(ASTCopier{}.translate(*cachedObject.optimizedAST)));
yulAssert(_object.code());
// There's no point in caching AnalysisInfo because it references AST nodes. It can't be shared
// by multiple ASTs and it's easier to recalculate it than properly clone it.
yulAssert(cachedObject.dialect);
_object.analysisInfo = std::make_shared<AsmAnalysisInfo>(
AsmAnalyzer::analyzeStrictAssertCorrect(
*cachedObject.dialect,
_object
)
);
// NOTE: Source name index is included in the key so it must be identical. No need to store and restore it.
}
std::optional<h256> ObjectOptimizer::calculateCacheKey(
Block const& _ast,
ObjectDebugData const& _debugData,
Settings const& _settings,
bool _isCreation
)
{
AsmPrinter asmPrinter(
languageToDialect(_settings.language, _settings.evmVersion, _settings.eofVersion),
_debugData.sourceNames,
DebugInfoSelection::All()
);
bytes rawKey;
// NOTE: AsmPrinter never prints nativeLocations included in debug data, so ASTs differing only
// in that regard are considered equal here. This is fine because the optimizer does not keep
// them up to date across AST transformations anyway so in any use where they need to be reliable,
// we just regenerate them by reparsing the object.
rawKey += keccak256(asmPrinter(_ast)).asBytes();
rawKey += keccak256(_debugData.formatUseSrcComment()).asBytes();
rawKey += h256(u256(_settings.language)).asBytes();
rawKey += FixedHash<1>(uint8_t(_settings.optimizeStackAllocation ? 0 : 1)).asBytes();
rawKey += h256(u256(_settings.expectedExecutionsPerDeployment)).asBytes();
rawKey += FixedHash<1>(uint8_t(_isCreation ? 0 : 1)).asBytes();
rawKey += keccak256(_settings.evmVersion.name()).asBytes();
yulAssert(!_settings.eofVersion.has_value() || *_settings.eofVersion > 0);
rawKey += FixedHash<1>(uint8_t(_settings.eofVersion ? 0 : *_settings.eofVersion)).asBytes();
rawKey += keccak256(_settings.yulOptimiserSteps).asBytes();
rawKey += keccak256(_settings.yulOptimiserCleanupSteps).asBytes();
return h256(keccak256(rawKey));
}
| 5,794
|
C++
|
.cpp
| 140
| 39.178571
| 121
| 0.771063
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,064
|
AST.cpp
|
ethereum_solidity/libyul/AST.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
namespace solidity::yul
{
LiteralValue::LiteralValue(std::string _builtinStringLiteralValue):
m_numericValue(std::nullopt),
m_stringValue(std::make_shared<std::string>(std::move(_builtinStringLiteralValue)))
{ }
LiteralValue::LiteralValue(solidity::yul::LiteralValue::Data const& _data, std::optional<std::string> const& _hint):
m_numericValue(_data),
m_stringValue(_hint ? std::make_shared<std::string>(*_hint) : nullptr)
{ }
LiteralValue::Data const& LiteralValue::value() const
{
yulAssert(!unlimited());
return *m_numericValue;
}
LiteralValue::BuiltinStringLiteralData const& LiteralValue::builtinStringLiteralValue() const
{
yulAssert(unlimited());
return *m_stringValue;
}
bool LiteralValue::unlimited() const
{
return !m_numericValue.has_value();
}
LiteralValue::RepresentationHint const& LiteralValue::hint() const
{
yulAssert(!unlimited());
return m_stringValue;
}
bool LiteralValue::operator==(LiteralValue const& _rhs) const
{
if (unlimited() != _rhs.unlimited())
return false;
if (unlimited())
return builtinStringLiteralValue() == _rhs.builtinStringLiteralValue();
return value() == _rhs.value();
}
bool LiteralValue::operator<(solidity::yul::LiteralValue const& _rhs) const
{
if (unlimited() != _rhs.unlimited())
return unlimited() < _rhs.unlimited();
if (unlimited())
return builtinStringLiteralValue() < _rhs.builtinStringLiteralValue();
return value() < _rhs.value();
}
}
| 2,158
|
C++
|
.cpp
| 62
| 33.112903
| 116
| 0.774302
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,066
|
Utilities.cpp
|
ethereum_solidity/libyul/Utilities.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Some useful snippets for the optimiser.
*/
#include <libyul/Utilities.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/FixedHash.h>
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
std::string solidity::yul::reindent(std::string const& _code)
{
int constexpr indentationWidth = 4;
auto constexpr static countBraces = [](std::string const& _s) noexcept -> int
{
auto const i = _s.find("//");
auto const e = i == _s.npos ? end(_s) : next(begin(_s), static_cast<ptrdiff_t>(i));
auto const opening = count_if(begin(_s), e, [](auto ch) { return ch == '{' || ch == '('; });
auto const closing = count_if(begin(_s), e, [](auto ch) { return ch == '}' || ch == ')'; });
return int(opening - closing);
};
std::vector<std::string> lines;
boost::split(lines, _code, boost::is_any_of("\n"));
for (std::string& line: lines)
boost::trim(line);
// Reduce multiple consecutive empty lines.
lines = fold(lines, std::vector<std::string>{}, [](auto&& _lines, auto&& _line) {
if (!(_line.empty() && !_lines.empty() && _lines.back().empty()))
_lines.emplace_back(std::move(_line));
return std::move(_lines);
});
std::stringstream out;
int depth = 0;
for (std::string const& line: lines)
{
int const diff = countBraces(line);
if (diff < 0)
depth += diff;
if (!line.empty())
{
for (int i = 0; i < depth * indentationWidth; ++i)
out << ' ';
out << line;
}
out << '\n';
if (diff > 0)
depth += diff;
}
return out.str();
}
LiteralValue solidity::yul::valueOfNumberLiteral(std::string_view const _literal)
{
return LiteralValue{LiteralValue::Data(_literal), std::string(_literal)};
}
LiteralValue solidity::yul::valueOfStringLiteral(std::string_view const _literal)
{
std::string const s(_literal);
return LiteralValue{u256(h256(s, h256::FromBinary, h256::AlignLeft)), s};
}
LiteralValue solidity::yul::valueOfBuiltinStringLiteralArgument(std::string_view _literal)
{
return LiteralValue{std::string(_literal)};
}
LiteralValue solidity::yul::valueOfBoolLiteral(std::string_view const _literal)
{
if (_literal == "true")
return LiteralValue{true};
else if (_literal == "false")
return LiteralValue{false};
yulAssert(false, "Unexpected bool literal value!");
}
LiteralValue solidity::yul::valueOfLiteral(std::string_view const _literal, LiteralKind const& _kind, bool const _unlimitedLiteralArgument)
{
switch (_kind)
{
case LiteralKind::Number:
return valueOfNumberLiteral(_literal);
case LiteralKind::Boolean:
return valueOfBoolLiteral(_literal);
case LiteralKind::String:
return _unlimitedLiteralArgument ? valueOfBuiltinStringLiteralArgument(_literal) : valueOfStringLiteral(_literal);
}
util::unreachable();
}
std::string solidity::yul::formatLiteral(solidity::yul::Literal const& _literal, bool const _validated)
{
if (_validated)
yulAssert(validLiteral(_literal), "Encountered invalid literal in formatLiteral.");
if (_literal.value.unlimited())
return _literal.value.builtinStringLiteralValue();
if (_literal.value.hint())
return *_literal.value.hint();
if (_literal.kind == LiteralKind::Boolean)
return _literal.value.value() == false ? "false" : "true";
// if there is no hint and it is not a boolean, just stringify the u256 word
return _literal.value.value().str();
}
bool solidity::yul::validLiteral(solidity::yul::Literal const& _literal)
{
switch (_literal.kind)
{
case LiteralKind::Number:
return validNumberLiteral(_literal);
case LiteralKind::Boolean:
return validBoolLiteral(_literal);
case LiteralKind::String:
return validStringLiteral(_literal);
}
util::unreachable();
}
bool solidity::yul::validStringLiteral(solidity::yul::Literal const& _literal)
{
if (_literal.kind != LiteralKind::String)
return false;
if (_literal.value.unlimited())
return true;
if (_literal.value.hint())
return _literal.value.hint()->size() <= 32 && _literal.value.value() == valueOfLiteral(*_literal.value.hint(), _literal.kind).value();
return true;
}
bool solidity::yul::validNumberLiteral(solidity::yul::Literal const& _literal)
{
if (_literal.kind != LiteralKind::Number || _literal.value.unlimited())
return false;
if (!_literal.value.hint())
return true;
auto const& repr = *_literal.value.hint();
if (!isValidDecimal(repr) && !isValidHex(repr))
return false;
if (bigint(repr) > u256(-1))
return false;
if (_literal.value.value() != valueOfLiteral(repr, _literal.kind).value())
return false;
return true;
}
bool solidity::yul::validBoolLiteral(solidity::yul::Literal const& _literal)
{
if (_literal.kind != LiteralKind::Boolean || _literal.value.unlimited())
return false;
if (_literal.value.hint() && !(*_literal.value.hint() == "true" || *_literal.value.hint() == "false"))
return false;
yulAssert(u256(0) == u256(false));
yulAssert(u256(1) == u256(true));
if (_literal.value.hint())
{
if (*_literal.value.hint() == "false")
return _literal.value.value() == false;
else
return _literal.value.value() == true;
}
return _literal.value.value() == true || _literal.value.value() == false;
}
template<>
bool Less<Literal>::operator()(Literal const& _lhs, Literal const& _rhs) const
{
if (_lhs.kind != _rhs.kind)
return _lhs.kind < _rhs.kind;
if (_lhs.value.unlimited() && _rhs.value.unlimited())
yulAssert(
_lhs.kind == LiteralKind::String && _rhs.kind == LiteralKind::String,
"Cannot have unlimited value that is not of String kind."
);
return _lhs.value < _rhs.value;
}
bool SwitchCaseCompareByLiteralValue::operator()(Case const* _lhs, Case const* _rhs) const
{
yulAssert(_lhs && _rhs, "");
return Less<Literal*>{}(_lhs->value.get(), _rhs->value.get());
}
| 6,554
|
C++
|
.cpp
| 188
| 32.553191
| 139
| 0.715914
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,067
|
Object.cpp
|
ethereum_solidity/libyul/Object.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul code and data object container.
*/
#include <libyul/Object.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AsmJsonConverter.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string.hpp>
#include <range/v3/view/transform.hpp>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::yul;
std::string Data::toString(DebugInfoSelection const&, CharStreamProvider const*) const
{
return "data \"" + name + "\" hex\"" + util::toHex(data) + "\"";
}
std::string Object::toString(
DebugInfoSelection const& _debugInfoSelection,
CharStreamProvider const* _soliditySourceProvider
) const
{
yulAssert(hasCode(), "No code");
yulAssert(debugData, "No debug data");
std::string inner = "code " + AsmPrinter(
m_dialect,
debugData->sourceNames,
_debugInfoSelection,
_soliditySourceProvider
)(code()->root());
for (auto const& obj: subObjects)
inner += "\n" + obj->toString(_debugInfoSelection, _soliditySourceProvider);
return
debugData->formatUseSrcComment() +
"object \"" + name + "\" {\n" +
indent(inner) + "\n" +
"}";
}
Json Data::toJson() const
{
Json ret;
ret["nodeType"] = "YulData";
ret["value"] = util::toHex(data);
return ret;
}
std::string ObjectDebugData::formatUseSrcComment() const
{
if (!sourceNames)
return "";
auto formatIdNamePair = [](auto&& _pair) {
return std::to_string(_pair.first) + ":" + util::escapeAndQuoteString(*_pair.second);
};
std::string serializedSourceNames = joinHumanReadable(
ranges::views::transform(*sourceNames, formatIdNamePair)
);
return "/// @use-src " + serializedSourceNames + "\n";
}
Json Object::toJson() const
{
yulAssert(hasCode(), "No code");
Json codeJson;
codeJson["nodeType"] = "YulCode";
codeJson["block"] = AsmJsonConverter(m_dialect, 0 /* sourceIndex */)(code()->root());
Json subObjectsJson = Json::array();
for (std::shared_ptr<ObjectNode> const& subObject: subObjects)
subObjectsJson.emplace_back(subObject->toJson());
Json ret;
ret["nodeType"] = "YulObject";
ret["name"] = name;
ret["code"] = codeJson;
ret["subObjects"] = subObjectsJson;
return ret;
}
std::set<std::string> Object::Structure::topLevelSubObjectNames() const
{
std::set<std::string> topLevelObjectNames;
for (auto const& path: objectPaths)
if (!util::contains(path, '.') && path != objectName)
topLevelObjectNames.insert(path);
return topLevelObjectNames;
}
Object::Structure Object::summarizeStructure() const
{
Structure structure;
structure.objectPaths =
name.empty() || util::contains(name, '.') ?
std::set<std::string>{} :
std::set<std::string>{name};
structure.objectName = name;
for (std::shared_ptr<ObjectNode> const& subObjectNode: subObjects)
{
yulAssert(!structure.contains(subObjectNode->name));
if (util::contains(subObjectNode->name, '.'))
continue;
if (auto const* subObject = dynamic_cast<Object const*>(subObjectNode.get()))
{
structure.objectPaths.insert(subObjectNode->name);
auto const subObjectStructure = subObject->summarizeStructure();
for (auto const& subSubObj: subObjectStructure.objectPaths)
if (subObject->name != subSubObj)
{
yulAssert(!structure.contains(subObject->name + "." + subSubObj));
structure.objectPaths.insert(subObject->name + "." + subSubObj);
}
for (auto const& subSubObjData: subObjectStructure.dataPaths)
if (subObject->name != subSubObjData)
{
yulAssert(!structure.contains(subObject->name + "." + subSubObjData));
structure.dataPaths.insert(subObject->name + "." + subSubObjData);
}
}
else
structure.dataPaths.insert(subObjectNode->name);
}
yulAssert(!structure.contains(""));
return structure;
}
std::vector<size_t> Object::pathToSubObject(std::string_view _qualifiedName) const
{
yulAssert(_qualifiedName != name, "");
yulAssert(subIndexByName.count(name) == 0, "");
if (boost::algorithm::starts_with(_qualifiedName, name + "."))
_qualifiedName = _qualifiedName.substr(name.length() + 1);
yulAssert(!_qualifiedName.empty(), "");
std::vector<std::string> subObjectPathComponents;
boost::algorithm::split(subObjectPathComponents, _qualifiedName, boost::is_any_of("."));
std::vector<size_t> path;
Object const* object = this;
for (std::string const& currentSubObjectName: subObjectPathComponents)
{
yulAssert(!currentSubObjectName.empty(), "");
auto subIndexIt = object->subIndexByName.find(currentSubObjectName);
yulAssert(
subIndexIt != object->subIndexByName.end(),
"Assembly object <" + std::string(_qualifiedName) + "> not found or does not contain code."
);
object = dynamic_cast<Object const*>(object->subObjects[subIndexIt->second].get());
yulAssert(object, "Assembly object <" + std::string(_qualifiedName) + "> not found or does not contain code.");
yulAssert(object->subId != std::numeric_limits<size_t>::max(), "");
path.push_back({object->subId});
}
return path;
}
std::shared_ptr<AST const> Object::code() const
{
return m_code;
}
bool Object::hasCode() const { return code() != nullptr; }
void Object::setCode(std::shared_ptr<AST const> const& _ast, std::shared_ptr<yul::AsmAnalysisInfo> _analysisInfo)
{
m_code = _ast;
analysisInfo = std::move(_analysisInfo);
}
void Object::collectSourceIndices(std::map<std::string, unsigned>& _indices) const
{
if (debugData && debugData->sourceNames.has_value())
for (auto const& [sourceIndex, sourceName]: debugData->sourceNames.value())
{
solAssert(_indices.count(*sourceName) == 0 || _indices[*sourceName] == sourceIndex);
_indices[*sourceName] = sourceIndex;
}
for (std::shared_ptr<ObjectNode> const& subNode: subObjects)
if (auto subObject = dynamic_cast<Object*>(subNode.get()))
subObject->collectSourceIndices(_indices);
}
bool Object::hasContiguousSourceIndices() const
{
std::map<std::string, unsigned> sourceIndices;
collectSourceIndices(sourceIndices);
unsigned maxSourceIndex = 0;
std::set<unsigned> indices;
for (auto const& [sources, sourceIndex]: sourceIndices)
{
maxSourceIndex = std::max(sourceIndex, maxSourceIndex);
indices.insert(sourceIndex);
}
solAssert(maxSourceIndex + 1 >= indices.size());
return indices.size() == 0 || indices.size() == maxSourceIndex + 1;
}
| 7,032
|
C++
|
.cpp
| 196
| 33.433673
| 113
| 0.734462
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,068
|
AsmJsonImporter.cpp
|
ethereum_solidity/libyul/AsmJsonImporter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author julius <djudju@protonmail.com>
* @date 2019
* Converts an inlineAssembly AST from JSON format to AsmData
*/
#include <libyul/AsmJsonImporter.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/Scanner.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <vector>
using namespace solidity::langutil;
namespace solidity::yul
{
using SourceLocation = langutil::SourceLocation;
SourceLocation const AsmJsonImporter::createSourceLocation(Json const& _node)
{
yulAssert(member(_node, "src").is_string(), "'src' must be a string");
return solidity::langutil::parseSourceLocation(_node["src"].get<std::string>(), m_sourceNames);
}
AST AsmJsonImporter::createAST(solidity::Json const& _node)
{
return AST(createBlock(_node));
}
template <class T>
T AsmJsonImporter::createAsmNode(Json const& _node)
{
T r;
SourceLocation nativeLocation = createSourceLocation(_node);
yulAssert(nativeLocation.hasText(), "Invalid source location in Asm AST");
// TODO: We should add originLocation to the AST.
// While it's not included, we'll use nativeLocation for it because we only support importing
// inline assembly as a part of a Solidity AST and there these locations are always the same.
r.debugData = DebugData::create(nativeLocation, nativeLocation);
return r;
}
Json AsmJsonImporter::member(Json const& _node, std::string const& _name)
{
if (!_node.contains(_name))
return Json();
return _node[_name];
}
NameWithDebugData AsmJsonImporter::createNameWithDebugData(Json const& _node)
{
auto nameWithDebugData = createAsmNode<NameWithDebugData>(_node);
nameWithDebugData.name = YulName{member(_node, "name").get<std::string>()};
return nameWithDebugData;
}
Statement AsmJsonImporter::createStatement(Json const& _node)
{
Json jsonNodeType = member(_node, "nodeType");
yulAssert(jsonNodeType.is_string(), "Expected \"nodeType\" to be of type string!");
std::string nodeType = jsonNodeType.get<std::string>();
yulAssert(nodeType.substr(0, 3) == "Yul", "Invalid nodeType prefix");
nodeType = nodeType.substr(3);
if (nodeType == "ExpressionStatement")
return createExpressionStatement(_node);
else if (nodeType == "Assignment")
return createAssignment(_node);
else if (nodeType == "VariableDeclaration")
return createVariableDeclaration(_node);
else if (nodeType == "FunctionDefinition")
return createFunctionDefinition(_node);
else if (nodeType == "If")
return createIf(_node);
else if (nodeType == "Switch")
return createSwitch(_node);
else if (nodeType == "ForLoop")
return createForLoop(_node);
else if (nodeType == "Break")
return createBreak(_node);
else if (nodeType == "Continue")
return createContinue(_node);
else if (nodeType == "Leave")
return createLeave(_node);
else if (nodeType == "Block")
return createBlock(_node);
else
yulAssert(false, "Invalid nodeType as statement");
// FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794)
util::unreachable();
}
Expression AsmJsonImporter::createExpression(Json const& _node)
{
Json jsonNodeType = member(_node, "nodeType");
yulAssert(jsonNodeType.is_string(), "Expected \"nodeType\" to be of type string!");
std::string nodeType = jsonNodeType.get<std::string>();
yulAssert(nodeType.substr(0, 3) == "Yul", "Invalid nodeType prefix");
nodeType = nodeType.substr(3);
if (nodeType == "FunctionCall")
return createFunctionCall(_node);
else if (nodeType == "Identifier")
return createIdentifier(_node);
else if (nodeType == "Literal")
return createLiteral(_node);
else
yulAssert(false, "Invalid nodeType as expression");
// FIXME: Workaround for spurious GCC 12.1 warning (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105794)
util::unreachable();
}
std::vector<Expression> AsmJsonImporter::createExpressionVector(Json const& _array)
{
std::vector<Expression> ret;
for (auto& var: _array)
ret.emplace_back(createExpression(var));
return ret;
}
std::vector<Statement> AsmJsonImporter::createStatementVector(Json const& _array)
{
std::vector<Statement> ret;
for (auto& var: _array)
ret.emplace_back(createStatement(var));
return ret;
}
Block AsmJsonImporter::createBlock(Json const& _node)
{
auto block = createAsmNode<Block>(_node);
block.statements = createStatementVector(_node["statements"]);
return block;
}
Literal AsmJsonImporter::createLiteral(Json const& _node)
{
auto lit = createAsmNode<Literal>(_node);
std::string kind = member(_node, "kind").get<std::string>();
solAssert(member(_node, "hexValue").is_string() || member(_node, "value").is_string(), "");
std::string value;
if (_node.contains("hexValue"))
value = util::asString(util::fromHex(member(_node, "hexValue").get<std::string>()));
else
value = member(_node, "value").get<std::string>();
{
auto const typeNode = member(_node, "type");
yulAssert(
typeNode.empty() || typeNode.get<std::string>().empty(),
fmt::format(
"Expected literal types to be either empty or absent in the JSON. Got \"{}\".",
typeNode.get<std::string>()
)
);
}
if (kind == "number")
{
langutil::CharStream charStream(value, "");
langutil::Scanner scanner{charStream};
lit.kind = LiteralKind::Number;
yulAssert(
scanner.currentToken() == Token::Number,
"Expected number but got " + langutil::TokenTraits::friendlyName(scanner.currentToken()) + std::string(" while scanning ") + value
);
}
else if (kind == "bool")
{
langutil::CharStream charStream(value, "");
langutil::Scanner scanner{charStream};
lit.kind = LiteralKind::Boolean;
yulAssert(
scanner.currentToken() == Token::TrueLiteral ||
scanner.currentToken() == Token::FalseLiteral,
"Expected true/false literal!"
);
}
else if (kind == "string")
{
lit.kind = LiteralKind::String;
yulAssert(
value.size() <= 32,
"String literal too long (" + std::to_string(value.size()) + " > 32)"
);
}
else
yulAssert(false, "unknown type of literal");
// import only for inline assembly, no unlimited string literals there
lit.value = valueOfLiteral(value, lit.kind, false /* _unlimitedLiteralArgument */);
yulAssert(validLiteral(lit));
return lit;
}
Leave AsmJsonImporter::createLeave(Json const& _node)
{
return createAsmNode<Leave>(_node);
}
Identifier AsmJsonImporter::createIdentifier(Json const& _node)
{
auto identifier = createAsmNode<Identifier>(_node);
identifier.name = YulName(member(_node, "name").get<std::string>());
return identifier;
}
Assignment AsmJsonImporter::createAssignment(Json const& _node)
{
auto assignment = createAsmNode<Assignment>(_node);
if (_node.contains("variableNames"))
for (auto const& var: member(_node, "variableNames"))
assignment.variableNames.emplace_back(createIdentifier(var));
assignment.value = std::make_unique<Expression>(createExpression(member(_node, "value")));
return assignment;
}
FunctionCall AsmJsonImporter::createFunctionCall(Json const& _node)
{
auto functionCall = createAsmNode<FunctionCall>(_node);
for (auto const& var: member(_node, "arguments"))
functionCall.arguments.emplace_back(createExpression(var));
functionCall.functionName = createIdentifier(member(_node, "functionName"));
return functionCall;
}
ExpressionStatement AsmJsonImporter::createExpressionStatement(Json const& _node)
{
auto statement = createAsmNode<ExpressionStatement>(_node);
statement.expression = createExpression(member(_node, "expression"));
return statement;
}
VariableDeclaration AsmJsonImporter::createVariableDeclaration(Json const& _node)
{
auto varDec = createAsmNode<VariableDeclaration>(_node);
for (auto const& var: member(_node, "variables"))
varDec.variables.emplace_back(createNameWithDebugData(var));
if (_node.contains("value"))
varDec.value = std::make_unique<Expression>(createExpression(member(_node, "value")));
return varDec;
}
FunctionDefinition AsmJsonImporter::createFunctionDefinition(Json const& _node)
{
auto funcDef = createAsmNode<FunctionDefinition>(_node);
funcDef.name = YulName{member(_node, "name").get<std::string>()};
if (_node.contains("parameters"))
for (auto const& var: member(_node, "parameters"))
funcDef.parameters.emplace_back(createNameWithDebugData(var));
if (_node.contains("returnVariables"))
for (auto const& var: member(_node, "returnVariables"))
funcDef.returnVariables.emplace_back(createNameWithDebugData(var));
funcDef.body = createBlock(member(_node, "body"));
return funcDef;
}
If AsmJsonImporter::createIf(Json const& _node)
{
auto ifStatement = createAsmNode<If>(_node);
ifStatement.condition = std::make_unique<Expression>(createExpression(member(_node, "condition")));
ifStatement.body = createBlock(member(_node, "body"));
return ifStatement;
}
Case AsmJsonImporter::createCase(Json const& _node)
{
auto caseStatement = createAsmNode<Case>(_node);
auto const& value = member(_node, "value");
if (value.is_string())
yulAssert(value.get<std::string>() == "default", "Expected default case");
else
caseStatement.value = std::make_unique<Literal>(createLiteral(value));
caseStatement.body = createBlock(member(_node, "body"));
return caseStatement;
}
Switch AsmJsonImporter::createSwitch(Json const& _node)
{
auto switchStatement = createAsmNode<Switch>(_node);
switchStatement.expression = std::make_unique<Expression>(createExpression(member(_node, "expression")));
for (auto const& var: member(_node, "cases"))
switchStatement.cases.emplace_back(createCase(var));
return switchStatement;
}
ForLoop AsmJsonImporter::createForLoop(Json const& _node)
{
auto forLoop = createAsmNode<ForLoop>(_node);
forLoop.pre = createBlock(member(_node, "pre"));
forLoop.condition = std::make_unique<Expression>(createExpression(member(_node, "condition")));
forLoop.post = createBlock(member(_node, "post"));
forLoop.body = createBlock(member(_node, "body"));
return forLoop;
}
Break AsmJsonImporter::createBreak(Json const& _node)
{
return createAsmNode<Break>(_node);
}
Continue AsmJsonImporter::createContinue(Json const& _node)
{
return createAsmNode<Continue>(_node);
}
}
| 10,875
|
C++
|
.cpp
| 292
| 35.092466
| 133
| 0.755296
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,069
|
EthAssemblyAdapter.cpp
|
ethereum_solidity/libyul/backends/evm/EthAssemblyAdapter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Adaptor between AbstractAssembly and libevmasm.
*/
#include <libyul/backends/evm/EthAssemblyAdapter.h>
#include <libyul/backends/evm/AbstractAssembly.h>
#include <libyul/Exceptions.h>
#include <libevmasm/Assembly.h>
#include <libevmasm/AssemblyItem.h>
#include <libevmasm/Instruction.h>
#include <liblangutil/SourceLocation.h>
#include <memory>
#include <functional>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
using namespace solidity::langutil;
EthAssemblyAdapter::EthAssemblyAdapter(evmasm::Assembly& _assembly):
m_assembly(_assembly)
{
}
void EthAssemblyAdapter::setSourceLocation(SourceLocation const& _location)
{
m_assembly.setSourceLocation(_location);
}
int EthAssemblyAdapter::stackHeight() const
{
return m_assembly.deposit();
}
void EthAssemblyAdapter::setStackHeight(int height)
{
m_assembly.setDeposit(height);
}
void EthAssemblyAdapter::appendInstruction(evmasm::Instruction _instruction)
{
m_assembly.append(_instruction);
}
void EthAssemblyAdapter::appendConstant(u256 const& _constant)
{
m_assembly.append(_constant);
}
void EthAssemblyAdapter::appendLabel(LabelID _labelId)
{
m_assembly.append(evmasm::AssemblyItem(evmasm::Tag, _labelId));
}
void EthAssemblyAdapter::appendLabelReference(LabelID _labelId)
{
m_assembly.append(evmasm::AssemblyItem(evmasm::PushTag, _labelId));
}
size_t EthAssemblyAdapter::newLabelId()
{
return assemblyTagToIdentifier(m_assembly.newTag());
}
size_t EthAssemblyAdapter::namedLabel(std::string const& _name, size_t _params, size_t _returns, std::optional<size_t> _sourceID)
{
return assemblyTagToIdentifier(m_assembly.namedTag(_name, _params, _returns, _sourceID));
}
void EthAssemblyAdapter::appendLinkerSymbol(std::string const& _linkerSymbol)
{
m_assembly.appendLibraryAddress(_linkerSymbol);
}
void EthAssemblyAdapter::appendVerbatim(bytes _data, size_t _arguments, size_t _returnVariables)
{
m_assembly.appendVerbatim(std::move(_data), _arguments, _returnVariables);
}
void EthAssemblyAdapter::appendJump(int _stackDiffAfter, JumpType _jumpType)
{
appendJumpInstruction(evmasm::Instruction::JUMP, _jumpType);
m_assembly.adjustDeposit(_stackDiffAfter);
}
void EthAssemblyAdapter::appendJumpTo(LabelID _labelId, int _stackDiffAfter, JumpType _jumpType)
{
appendLabelReference(_labelId);
appendJump(_stackDiffAfter, _jumpType);
}
void EthAssemblyAdapter::appendJumpToIf(LabelID _labelId, JumpType _jumpType)
{
appendLabelReference(_labelId);
appendJumpInstruction(evmasm::Instruction::JUMPI, _jumpType);
}
void EthAssemblyAdapter::appendAssemblySize()
{
m_assembly.appendProgramSize();
}
std::pair<std::shared_ptr<AbstractAssembly>, AbstractAssembly::SubID> EthAssemblyAdapter::createSubAssembly(bool _creation, std::string _name)
{
std::shared_ptr<evmasm::Assembly> assembly{std::make_shared<evmasm::Assembly>(m_assembly.evmVersion(), _creation, m_assembly.eofVersion(), std::move(_name))};
auto sub = m_assembly.newSub(assembly);
return {std::make_shared<EthAssemblyAdapter>(*assembly), static_cast<size_t>(sub.data())};
}
void EthAssemblyAdapter::appendEOFCreate(ContainerID _containerID)
{
m_assembly.appendEOFCreate(_containerID);
}
void EthAssemblyAdapter::appendReturnContract(ContainerID _containerID)
{
m_assembly.appendReturnContract(_containerID);
}
void EthAssemblyAdapter::appendDataOffset(std::vector<AbstractAssembly::SubID> const& _subPath)
{
if (auto it = m_dataHashBySubId.find(_subPath[0]); it != m_dataHashBySubId.end())
{
yulAssert(_subPath.size() == 1, "");
m_assembly << evmasm::AssemblyItem(evmasm::PushData, it->second);
return;
}
m_assembly.pushSubroutineOffset(m_assembly.encodeSubPath(_subPath));
}
void EthAssemblyAdapter::appendDataSize(std::vector<AbstractAssembly::SubID> const& _subPath)
{
if (auto it = m_dataHashBySubId.find(_subPath[0]); it != m_dataHashBySubId.end())
{
yulAssert(_subPath.size() == 1, "");
m_assembly << u256(m_assembly.data(h256(it->second)).size());
return;
}
m_assembly.pushSubroutineSize(m_assembly.encodeSubPath(_subPath));
}
AbstractAssembly::SubID EthAssemblyAdapter::appendData(bytes const& _data)
{
evmasm::AssemblyItem pushData = m_assembly.newData(_data);
SubID subID = m_nextDataCounter++;
m_dataHashBySubId[subID] = pushData.data();
return subID;
}
void EthAssemblyAdapter::appendToAuxiliaryData(bytes const& _data)
{
m_assembly.appendToAuxiliaryData(_data);
}
void EthAssemblyAdapter::appendImmutable(std::string const& _identifier)
{
m_assembly.appendImmutable(_identifier);
}
void EthAssemblyAdapter::appendImmutableAssignment(std::string const& _identifier)
{
m_assembly.appendImmutableAssignment(_identifier);
}
void EthAssemblyAdapter::appendAuxDataLoadN(uint16_t _offset)
{
m_assembly.appendAuxDataLoadN(_offset);
}
void EthAssemblyAdapter::markAsInvalid()
{
m_assembly.markAsInvalid();
}
langutil::EVMVersion EthAssemblyAdapter::evmVersion() const
{
return m_assembly.evmVersion();
}
EthAssemblyAdapter::LabelID EthAssemblyAdapter::assemblyTagToIdentifier(evmasm::AssemblyItem const& _tag)
{
u256 id = _tag.data();
yulAssert(id <= std::numeric_limits<LabelID>::max(), "Tag id too large.");
return LabelID(id);
}
void EthAssemblyAdapter::appendJumpInstruction(evmasm::Instruction _instruction, JumpType _jumpType)
{
yulAssert(_instruction == evmasm::Instruction::JUMP || _instruction == evmasm::Instruction::JUMPI, "");
evmasm::AssemblyItem jump(_instruction);
switch (_jumpType)
{
case JumpType::Ordinary:
yulAssert(jump.getJumpType() == evmasm::AssemblyItem::JumpType::Ordinary, "");
break;
case JumpType::IntoFunction:
jump.setJumpType(evmasm::AssemblyItem::JumpType::IntoFunction);
break;
case JumpType::OutOfFunction:
jump.setJumpType(evmasm::AssemblyItem::JumpType::OutOfFunction);
break;
}
m_assembly.append(std::move(jump));
}
| 6,515
|
C++
|
.cpp
| 186
| 33.317204
| 159
| 0.79612
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,070
|
SSACFGTopologicalSort.cpp
|
ethereum_solidity/libyul/backends/evm/SSACFGTopologicalSort.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/backends/evm/SSACFGTopologicalSort.h>
using namespace solidity::yul;
ForwardSSACFGTopologicalSort::ForwardSSACFGTopologicalSort(SSACFG const& _cfg):
m_cfg(_cfg),
m_explored(m_cfg.numBlocks(), false), m_blockWisePreOrder(m_cfg.numBlocks(), 0),
m_blockWiseMaxSubtreePreOrder(m_cfg.numBlocks(), 0)
{
yulAssert(m_cfg.entry.value == 0);
m_preOrder.reserve(m_cfg.numBlocks());
m_postOrder.reserve(m_cfg.numBlocks());
for (size_t id = 0; id < m_cfg.numBlocks(); ++id)
{
if (!m_explored[id])
dfs(id);
}
for (auto const& [v1, v2]: m_potentialBackEdges)
if (ancestor(v2, v1))
m_backEdgeTargets.insert(v2);
}
void ForwardSSACFGTopologicalSort::dfs(size_t const _vertex) {
yulAssert(!m_explored[_vertex]);
m_explored[_vertex] = true;
m_blockWisePreOrder[_vertex] = m_preOrder.size();
m_blockWiseMaxSubtreePreOrder[_vertex] = m_blockWisePreOrder[_vertex];
m_preOrder.push_back(_vertex);
m_cfg.block(SSACFG::BlockId{_vertex}).forEachExit([&](SSACFG::BlockId const& _exitBlock){
if (!m_explored[_exitBlock.value])
{
dfs(_exitBlock.value);
m_blockWiseMaxSubtreePreOrder[_vertex] = std::max(m_blockWiseMaxSubtreePreOrder[_vertex], m_blockWiseMaxSubtreePreOrder[_exitBlock.value]);
}
else
m_potentialBackEdges.emplace_back(_vertex, _exitBlock.value);
});
m_postOrder.push_back(_vertex);
}
bool ForwardSSACFGTopologicalSort::ancestor(size_t const _block1, size_t const _block2) const {
yulAssert(_block1 < m_blockWisePreOrder.size());
yulAssert(_block2 < m_blockWisePreOrder.size());
auto const preOrderIndex1 = m_blockWisePreOrder[_block1];
auto const preOrderIndex2 = m_blockWisePreOrder[_block2];
bool const node1VisitedBeforeNode2 = preOrderIndex1 <= preOrderIndex2;
bool const node2InSubtreeOfNode1 = preOrderIndex2 <= m_blockWiseMaxSubtreePreOrder[_block1];
return node1VisitedBeforeNode2 && node2InSubtreeOfNode1;
}
bool ForwardSSACFGTopologicalSort::backEdge(SSACFG::BlockId const& _block1, SSACFG::BlockId const& _block2) const
{
if (ancestor(_block2.value, _block1.value))
{
// check that block1 -> block2 is indeed an edge in the cfg
bool isEdge = false;
m_cfg.block(_block1).forEachExit([&_block2, &isEdge](SSACFG::BlockId const& _exit) { isEdge |= _block2 == _exit; });
return isEdge;
}
return false;
}
| 2,974
|
C++
|
.cpp
| 70
| 40.214286
| 142
| 0.763668
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,071
|
SSACFGLoopNestingForest.cpp
|
ethereum_solidity/libyul/backends/evm/SSACFGLoopNestingForest.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/backends/evm/SSACFGLoopNestingForest.h>
using namespace solidity::yul;
SSACFGLoopNestingForest::SSACFGLoopNestingForest(ForwardSSACFGTopologicalSort const& _sort):
m_sort(_sort),
m_cfg(_sort.cfg()),
m_vertexPartition(m_cfg.numBlocks()),
m_loopParents(m_cfg.numBlocks(), std::numeric_limits<size_t>::max())
{
auto dfsOrder = m_sort.preOrder();
// we go from innermost to outermost
std::reverse(dfsOrder.begin(), dfsOrder.end());
for (auto const& blockId: dfsOrder)
findLoop(blockId);
// get the root nodes
for (auto loopHeader: m_loopNodes)
{
while (m_loopParents[loopHeader] != std::numeric_limits<size_t>::max())
loopHeader = m_loopParents[loopHeader];
m_loopRootNodes.insert(loopHeader);
}
}
void SSACFGLoopNestingForest::findLoop(size_t const _potentialHeader)
{
if (m_sort.backEdgeTargets().count(_potentialHeader) > 0)
{
std::set<size_t> loopBody;
std::set<size_t> workList;
for (auto const pred: m_cfg.block(SSACFG::BlockId{_potentialHeader}).entries)
{
auto const representative = m_vertexPartition.find(pred.value);
if (
representative != _potentialHeader &&
m_sort.backEdge(SSACFG::BlockId{pred}, SSACFG::BlockId{_potentialHeader})
)
workList.insert(representative);
}
while (!workList.empty())
{
auto const y = workList.extract(workList.begin()).value();
loopBody.insert(y);
for (auto const& predecessor: m_cfg.block(SSACFG::BlockId{y}).entries)
{
if (!m_sort.backEdge(SSACFG::BlockId{predecessor}, SSACFG::BlockId{y}))
{
auto const predecessorHeader = m_vertexPartition.find(predecessor.value);
if (predecessorHeader != _potentialHeader && loopBody.count(predecessorHeader) == 0)
workList.insert(predecessorHeader);
}
}
}
if (!loopBody.empty())
collapse(loopBody, _potentialHeader);
}
}
void SSACFGLoopNestingForest::collapse(std::set<size_t> const& _loopBody, size_t _loopHeader)
{
for (auto const z: _loopBody)
{
m_loopParents[z] = _loopHeader;
m_vertexPartition.merge(_loopHeader, z, false); // don't merge by size, loop header should be representative
}
yulAssert(m_vertexPartition.find(_loopHeader) == _loopHeader); // representative was preserved
m_loopNodes.insert(_loopHeader);
}
| 2,930
|
C++
|
.cpp
| 78
| 34.75641
| 111
| 0.747887
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,072
|
VariableReferenceCounter.cpp
|
ethereum_solidity/libyul/backends/evm/VariableReferenceCounter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Counts the number of references to a variable.
*/
#include <libyul/backends/evm/VariableReferenceCounter.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/AST.h>
#include <libsolutil/Visitor.h>
using namespace solidity::yul;
void VariableReferenceCounter::operator()(Identifier const& _identifier)
{
increaseRefIfFound(_identifier.name);
}
void VariableReferenceCounter::operator()(FunctionDefinition const& _function)
{
Scope* originalScope = m_scope;
yulAssert(m_info.virtualBlocks.at(&_function), "");
m_scope = m_info.scopes.at(m_info.virtualBlocks.at(&_function).get()).get();
yulAssert(m_scope, "Variable scope does not exist.");
for (auto const& v: _function.returnVariables)
increaseRefIfFound(v.name);
(*this)(_function.body);
m_scope = originalScope;
}
void VariableReferenceCounter::operator()(ForLoop const& _forLoop)
{
Scope* originalScope = m_scope;
// Special scoping rules.
m_scope = m_info.scopes.at(&_forLoop.pre).get();
walkVector(_forLoop.pre.statements);
visit(*_forLoop.condition);
(*this)(_forLoop.body);
(*this)(_forLoop.post);
m_scope = originalScope;
}
void VariableReferenceCounter::operator()(Block const& _block)
{
Scope* originalScope = m_scope;
m_scope = m_info.scopes.at(&_block).get();
ASTWalker::operator()(_block);
m_scope = originalScope;
}
void VariableReferenceCounter::increaseRefIfFound(YulName _variableName)
{
m_scope->lookup(_variableName, util::GenericVisitor{
[&](Scope::Variable const& _var)
{
++m_variableReferences[&_var];
},
[](Scope::Function const&) { }
});
}
| 2,260
|
C++
|
.cpp
| 65
| 32.753846
| 78
| 0.762058
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,073
|
SSACFGLiveness.cpp
|
ethereum_solidity/libyul/backends/evm/SSACFGLiveness.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/backends/evm/SSACFGLiveness.h>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/reverse.hpp>
using namespace solidity::yul;
namespace
{
constexpr auto literalsFilter(SSACFG const& _cfg)
{
return [&_cfg](SSACFG::ValueId const& _valueId) -> bool
{
return !std::holds_alternative<SSACFG::LiteralValue>(_cfg.valueInfo(_valueId));;
};
}
}
SSACFGLiveness::SSACFGLiveness(SSACFG const& _cfg):
m_cfg(_cfg),
m_topologicalSort(_cfg),
m_loopNestingForest(m_topologicalSort),
m_liveIns(_cfg.numBlocks()),
m_liveOuts(_cfg.numBlocks()),
m_operationLiveOuts(_cfg.numBlocks())
{
runDagDfs();
for (auto const loopRootNode: m_loopNestingForest.loopRootNodes())
runLoopTreeDfs(loopRootNode);
fillOperationsLiveOut();
}
void SSACFGLiveness::runDagDfs()
{
// SSA Book, Algorithm 9.2
for (auto const blockIdValue: m_topologicalSort.postOrder())
{
// post-order traversal
SSACFG::BlockId blockId{blockIdValue};
auto const& block = m_cfg.block(blockId);
// live <- PhiUses(B)
std::set<SSACFG::ValueId> live{};
block.forEachExit(
[&](SSACFG::BlockId const& _successor)
{
for (auto const& phi: m_cfg.block(_successor).phis)
{
auto const& info = m_cfg.valueInfo(phi);
yulAssert(std::holds_alternative<SSACFG::PhiValue>(info), "value info of phi wasn't PhiValue");
auto const& entries = m_cfg.block(std::get<SSACFG::PhiValue>(info).block).entries;
// this is getting the argument index of the phi function corresponding to the path going
// through "blockId", ie, the currently handled block
auto const it = entries.find(blockId);
yulAssert(it != entries.end());
auto const argIndex = static_cast<size_t>(std::distance(entries.begin(), it));
yulAssert(argIndex < std::get<SSACFG::PhiValue>(info).arguments.size());
auto const arg = std::get<SSACFG::PhiValue>(info).arguments.at(argIndex);
if (!std::holds_alternative<SSACFG::LiteralValue>(m_cfg.valueInfo(arg)))
live.insert(arg);
}
});
// for each S \in succs(B) s.t. (B, S) not a back edge: live <- live \cup (LiveIn(S) - PhiDefs(S))
block.forEachExit(
[&](SSACFG::BlockId const& _successor) {
if (!m_topologicalSort.backEdge(blockId, _successor))
live += m_liveIns[_successor.value] - m_cfg.block(_successor).phis;
});
if (std::holds_alternative<SSACFG::BasicBlock::FunctionReturn>(block.exit))
live += std::get<SSACFG::BasicBlock::FunctionReturn>(block.exit).returnValues
| ranges::views::filter(literalsFilter(m_cfg));
// clean out unreachables
live = live | ranges::views::filter([&](auto const& valueId) { return !std::holds_alternative<SSACFG::UnreachableValue>(m_cfg.valueInfo(valueId)); }) | ranges::to<std::set>;
// LiveOut(B) <- live
m_liveOuts[blockId.value] = live;
// for each program point p in B, backwards, do:
for (auto const& op: block.operations | ranges::views::reverse)
{
// remove variables defined at p from live
live -= op.outputs | ranges::views::filter(literalsFilter(m_cfg)) | ranges::to<std::vector>;
// add uses at p to live
live += op.inputs | ranges::views::filter(literalsFilter(m_cfg)) | ranges::to<std::vector>;
}
// livein(b) <- live \cup PhiDefs(B)
m_liveIns[blockId.value] = live + block.phis;
}
}
void SSACFGLiveness::runLoopTreeDfs(size_t const _loopHeader)
{
// SSA Book, Algorithm 9.3
if (m_loopNestingForest.loopNodes().count(_loopHeader) > 0)
{
// the loop header block id
auto const& block = m_cfg.block(SSACFG::BlockId{_loopHeader});
// LiveLoop <- LiveIn(B_N) - PhiDefs(B_N)
auto liveLoop = m_liveIns[_loopHeader] - block.phis;
// must be live out of header if live in of children
m_liveOuts[_loopHeader] += liveLoop;
// for each blockId \in children(loopHeader)
for (size_t blockIdValue = 0; blockIdValue < m_cfg.numBlocks(); ++blockIdValue)
if (m_loopNestingForest.loopParents()[blockIdValue] == _loopHeader)
{
// propagate loop liveness information down to the loop header's children
m_liveIns[blockIdValue] += liveLoop;
m_liveOuts[blockIdValue] += liveLoop;
runLoopTreeDfs(blockIdValue);
}
}
}
void SSACFGLiveness::fillOperationsLiveOut()
{
for (size_t blockIdValue = 0; blockIdValue < m_cfg.numBlocks(); ++blockIdValue)
{
auto const& operations = m_cfg.block(SSACFG::BlockId{blockIdValue}).operations;
auto& liveOuts = m_operationLiveOuts[blockIdValue];
liveOuts.resize(operations.size());
if (!operations.empty())
{
auto live = m_liveOuts[blockIdValue];
auto rit = liveOuts.rbegin();
for (auto const& op: operations | ranges::views::reverse)
{
*rit = live;
live -= op.outputs | ranges::views::filter(literalsFilter(m_cfg)) | ranges::to<std::vector>;
live += op.inputs | ranges::views::filter(literalsFilter(m_cfg)) | ranges::to<std::vector>;
++rit;
}
}
}
}
| 5,568
|
C++
|
.cpp
| 139
| 36.928058
| 175
| 0.716636
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,075
|
NoOutputAssembly.cpp
|
ethereum_solidity/libyul/backends/evm/NoOutputAssembly.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Assembly interface that ignores everything. Can be used as a backend for a compilation dry-run.
*/
#include <libyul/backends/evm/NoOutputAssembly.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libevmasm/Instruction.h>
#include <range/v3/view/iota.hpp>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
using namespace solidity::langutil;
namespace
{
void modifyBuiltinToNoOutput(BuiltinFunctionForEVM& _builtin)
{
_builtin.generateCode = [_builtin](FunctionCall const& _call, AbstractAssembly& _assembly, BuiltinContext&)
{
for (size_t i: ranges::views::iota(0u, _call.arguments.size()))
if (!_builtin.literalArgument(i))
_assembly.appendInstruction(evmasm::Instruction::POP);
for (size_t i = 0; i < _builtin.numReturns; i++)
_assembly.appendConstant(u256(0));
};
}
}
void NoOutputAssembly::appendInstruction(evmasm::Instruction _instr)
{
m_stackHeight += instructionInfo(_instr, m_evmVersion).ret - instructionInfo(_instr, m_evmVersion).args;
}
void NoOutputAssembly::appendConstant(u256 const&)
{
appendInstruction(evmasm::pushInstruction(1));
}
void NoOutputAssembly::appendLabel(LabelID)
{
appendInstruction(evmasm::Instruction::JUMPDEST);
}
void NoOutputAssembly::appendLabelReference(LabelID)
{
appendInstruction(evmasm::pushInstruction(1));
}
NoOutputAssembly::LabelID NoOutputAssembly::newLabelId()
{
return 1;
}
AbstractAssembly::LabelID NoOutputAssembly::namedLabel(std::string const&, size_t, size_t, std::optional<size_t>)
{
return 1;
}
void NoOutputAssembly::appendLinkerSymbol(std::string const&)
{
yulAssert(false, "Linker symbols not yet implemented.");
}
void NoOutputAssembly::appendVerbatim(bytes, size_t _arguments, size_t _returnVariables)
{
m_stackHeight += static_cast<int>(_returnVariables) - static_cast<int>(_arguments);
}
void NoOutputAssembly::appendJump(int _stackDiffAfter, JumpType)
{
appendInstruction(evmasm::Instruction::JUMP);
m_stackHeight += _stackDiffAfter;
}
void NoOutputAssembly::appendJumpTo(LabelID _labelId, int _stackDiffAfter, JumpType _jumpType)
{
appendLabelReference(_labelId);
appendJump(_stackDiffAfter, _jumpType);
}
void NoOutputAssembly::appendJumpToIf(LabelID _labelId, JumpType)
{
appendLabelReference(_labelId);
appendInstruction(evmasm::Instruction::JUMPI);
}
void NoOutputAssembly::appendAssemblySize()
{
appendInstruction(evmasm::Instruction::PUSH1);
}
std::pair<std::shared_ptr<AbstractAssembly>, AbstractAssembly::SubID> NoOutputAssembly::createSubAssembly(bool, std::string)
{
yulAssert(false, "Sub assemblies not implemented.");
return {};
}
void NoOutputAssembly::appendDataOffset(std::vector<AbstractAssembly::SubID> const&)
{
appendInstruction(evmasm::Instruction::PUSH1);
}
void NoOutputAssembly::appendDataSize(std::vector<AbstractAssembly::SubID> const&)
{
appendInstruction(evmasm::Instruction::PUSH1);
}
AbstractAssembly::SubID NoOutputAssembly::appendData(bytes const&)
{
return 1;
}
void NoOutputAssembly::appendImmutable(std::string const&)
{
yulAssert(false, "loadimmutable not implemented.");
}
void NoOutputAssembly::appendImmutableAssignment(std::string const&)
{
yulAssert(false, "setimmutable not implemented.");
}
void NoOutputAssembly::appendAuxDataLoadN(uint16_t)
{
yulAssert(false, "auxdataloadn not implemented.");
}
void NoOutputAssembly::appendEOFCreate(ContainerID)
{
yulAssert(false, "eofcreate not implemented.");
}
void NoOutputAssembly::appendReturnContract(ContainerID)
{
yulAssert(false, "returncontract not implemented.");
}
NoOutputEVMDialect::NoOutputEVMDialect(EVMDialect const& _copyFrom):
EVMDialect(_copyFrom.evmVersion(), _copyFrom.eofVersion(), _copyFrom.providesObjectAccess())
{
for (auto& fun: m_functions)
if (fun)
modifyBuiltinToNoOutput(*fun);
}
BuiltinFunctionForEVM const& NoOutputEVMDialect::builtin(BuiltinHandle const& _handle) const
{
if (isVerbatimHandle(_handle))
// for verbatims the modification is performed lazily as they are stored in a lookup table fashion
if (
auto& builtin = m_verbatimFunctions[_handle.id];
!builtin
)
{
builtin = std::make_unique<BuiltinFunctionForEVM>(createVerbatimFunctionFromHandle(_handle));
modifyBuiltinToNoOutput(*builtin);
}
return EVMDialect::builtin(_handle);
}
| 4,977
|
C++
|
.cpp
| 149
| 31.583893
| 124
| 0.797371
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,076
|
SSAControlFlowGraph.cpp
|
ethereum_solidity/libyul/backends/evm/SSAControlFlowGraph.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/backends/evm/SSAControlFlowGraph.h>
#include <libyul/backends/evm/SSACFGLiveness.h>
#include <libsolutil/StringUtils.h>
#include <libsolutil/Visitor.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtautological-compare"
#include <fmt/ranges.h>
#pragma GCC diagnostic pop
#include <range/v3/view/zip.hpp>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::yul;
namespace
{
class SSACFGPrinter
{
public:
SSACFGPrinter(SSACFG const& _cfg, SSACFG::BlockId _blockId, SSACFGLiveness const* _liveness):
m_cfg(_cfg), m_functionIndex(0), m_liveness(_liveness)
{
printBlock(_blockId);
}
SSACFGPrinter(SSACFG const& _cfg, size_t _functionIndex, Scope::Function const& _function, SSACFGLiveness const* _liveness):
m_cfg(_cfg), m_functionIndex(_functionIndex), m_liveness(_liveness)
{
printFunction(_function);
}
friend std::ostream& operator<<(std::ostream& stream, SSACFGPrinter const& printer) {
stream << printer.m_result.str();
return stream;
}
private:
static std::string varToString(SSACFG const& _cfg, SSACFG::ValueId _var) {
if (_var.value == std::numeric_limits<size_t>::max())
return "INVALID";
auto const& info = _cfg.valueInfo(_var);
return std::visit(
GenericVisitor{
[&](SSACFG::UnreachableValue const&) -> std::string {
return "[unreachable]";
},
[&](SSACFG::PhiValue const&) -> std::string {
return fmt::format("v{}", _var.value);
},
[&](SSACFG::VariableValue const&) -> std::string {
return fmt::format("v{}", _var.value);
},
[&](SSACFG::LiteralValue const& _literal) -> std::string {
return formatNumberReadable(_literal.value);
}
},
info
);
}
std::string formatBlockHandle(SSACFG::BlockId const& _id) const
{
return fmt::format("Block{}_{}", m_functionIndex, _id.value);
}
std::string formatEdge(SSACFG::BlockId const& _v, SSACFG::BlockId const& _w, std::optional<std::string> const& _vPort = std::nullopt)
{
std::string const style = m_liveness && m_liveness->topologicalSort().backEdge(_v, _w) ? "dashed" : "solid";
if (_vPort)
return fmt::format("{}Exit:{} -> {} [style=\"{}\"];\n", formatBlockHandle(_v), *_vPort, formatBlockHandle(_w), style);
else
return fmt::format("{}Exit -> {} [style=\"{}\"];\n", formatBlockHandle(_v), formatBlockHandle(_w), style);
}
static std::string formatPhi(SSACFG const& _cfg, SSACFG::PhiValue const& _phiValue)
{
auto const transform = [&](SSACFG::ValueId const& valueId) { return varToString(_cfg, valueId); };
std::vector<std::string> formattedArgs;
formattedArgs.reserve(_phiValue.arguments.size());
for (auto const& [arg, entry]: ranges::zip_view(_phiValue.arguments | ranges::views::transform(transform), _cfg.block(_phiValue.block).entries))
formattedArgs.push_back(fmt::format("Block {} => {}", entry.value, arg));
if (!formattedArgs.empty())
return fmt::format("φ(\\l\\\n\t{}\\l\\\n)", fmt::join(formattedArgs, ",\\l\\\n\t"));
else
return "φ()";
}
void writeBlock(SSACFG::BlockId const& _id, SSACFG::BasicBlock const& _block)
{
auto const valueToString = [&](SSACFG::ValueId const& valueId) { return varToString(m_cfg, valueId); };
bool entryBlock = _id.value == 0 && m_functionIndex == 0;
if (entryBlock)
{
m_result << fmt::format("Entry{} [label=\"Entry\"];\n", m_functionIndex);
m_result << fmt::format("Entry{} -> {};\n", m_functionIndex, formatBlockHandle(_id));
}
{
if (m_liveness)
{
m_result << fmt::format(
"{} [label=\"\\\nBlock {}; ({}, max {})\\n",
formatBlockHandle(_id),
_id.value,
m_liveness->topologicalSort().preOrderIndexOf(_id.value),
m_liveness->topologicalSort().maxSubtreePreOrderIndexOf(_id.value)
);
m_result << fmt::format(
"LiveIn: {}\\l\\\n",
fmt::join(m_liveness->liveIn(_id) | ranges::views::transform(valueToString), ",")
);
m_result << fmt::format(
"LiveOut: {}\\l\\n",
fmt::join(m_liveness->liveOut(_id) | ranges::views::transform(valueToString), ",")
);
}
else
m_result << fmt::format("{} [label=\"\\\nBlock {}\\n", formatBlockHandle(_id), _id.value);
for (auto const& phi: _block.phis)
{
auto const* phiValue = std::get_if<SSACFG::PhiValue>(&m_cfg.valueInfo(phi));
solAssert(phiValue);
m_result << fmt::format("v{} := {}\\l\\\n", phi.value, formatPhi(m_cfg, *phiValue));
}
for (auto const& operation: _block.operations)
{
std::string const label = std::visit(GenericVisitor{
[&](SSACFG::Call const& _call) {
return _call.function.get().name.str();
},
[&](SSACFG::BuiltinCall const& _call) {
return _call.builtin.get().name;
},
}, operation.kind);
if (!operation.outputs.empty())
m_result << fmt::format(
"{} := ",
fmt::join(operation.outputs | ranges::views::transform(valueToString), ", ")
);
m_result << fmt::format(
"{}({})\\l\\\n",
label,
fmt::join(operation.inputs | ranges::views::transform(valueToString), ", ")
);
}
m_result << "\"];\n";
std::visit(GenericVisitor{
[&](SSACFG::BasicBlock::MainExit const&)
{
m_result << fmt::format("{}Exit [label=\"MainExit\"];\n", formatBlockHandle(_id));
m_result << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id));
},
[&](SSACFG::BasicBlock::Jump const& _jump)
{
m_result << fmt::format("{} -> {}Exit [arrowhead=none];\n", formatBlockHandle(_id), formatBlockHandle(_id));
m_result << fmt::format("{}Exit [label=\"Jump\" shape=oval];\n", formatBlockHandle(_id));
m_result << formatEdge(_id, _jump.target);
},
[&](SSACFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
m_result << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id));
m_result << fmt::format(
"{}Exit [label=\"{{ If {} | {{ <0> Zero | <1> NonZero }}}}\" shape=Mrecord];\n",
formatBlockHandle(_id), varToString(m_cfg, _conditionalJump.condition)
);
m_result << formatEdge(_id, _conditionalJump.zero, "0");
m_result << formatEdge(_id, _conditionalJump.nonZero, "1");
},
[&](SSACFG::BasicBlock::JumpTable const& jt)
{
m_result << fmt::format("{} -> {}Exit;\n", formatBlockHandle(_id), formatBlockHandle(_id));
std::string options;
for (auto const& jumpCase: jt.cases)
{
if (!options.empty())
options += " | ";
options += fmt::format("<{0}> {0}", formatNumber(jumpCase.first));
}
if (!options.empty())
options += " | ";
options += "<default> default";
m_result << fmt::format("{}Exit [label=\"{{ JT | {{ {} }} }}\" shape=Mrecord];\n", formatBlockHandle(_id), options);
for (auto const& jumpCase: jt.cases)
m_result << formatEdge(_id, jumpCase.second, formatNumber(jumpCase.first));
m_result << formatEdge(_id, jt.defaultCase, "default");
},
[&](SSACFG::BasicBlock::FunctionReturn const& fr)
{
m_result << formatBlockHandle(_id) << "Exit [label=\"FunctionReturn["
<< fmt::format("{}", fmt::join(fr.returnValues | ranges::views::transform(valueToString), ", "))
<< "]\"];\n";
m_result << formatBlockHandle(_id) << " -> " << formatBlockHandle(_id) << "Exit;\n";
},
[&](SSACFG::BasicBlock::Terminated const&)
{
m_result << formatBlockHandle(_id) << "Exit [label=\"Terminated\"];\n";
m_result << formatBlockHandle(_id) << " -> " << formatBlockHandle(_id) << "Exit;\n";
}
}, _block.exit);
}
}
void printBlock(SSACFG::BlockId const& _rootId)
{
std::set<SSACFG::BlockId> explored{};
explored.insert(_rootId);
std::deque<SSACFG::BlockId> toVisit{};
toVisit.emplace_back(_rootId);
while (!toVisit.empty())
{
auto const id = toVisit.front();
toVisit.pop_front();
auto const& block = m_cfg.block(id);
writeBlock(id, block);
block.forEachExit(
[&](SSACFG::BlockId const& _exitBlock)
{
if (explored.count(_exitBlock) == 0)
{
explored.insert(_exitBlock);
toVisit.emplace_back(_exitBlock);
}
}
);
}
}
void printFunction(Scope::Function const& _fun)
{
static auto constexpr returnsTransform = [](auto const& functionReturnValue) { return functionReturnValue.get().name.str(); };
static auto constexpr argsTransform = [](auto const& arg) { return fmt::format("v{}", std::get<1>(arg).value); };
m_result << "FunctionEntry_" << _fun.name.str() << "_" << m_cfg.entry.value << " [label=\"";
if (!m_cfg.returns.empty())
m_result << fmt::format("function {0}:\n {1} := {0}({2})", _fun.name.str(), fmt::join(m_cfg.returns | ranges::views::transform(returnsTransform), ", "), fmt::join(m_cfg.arguments | ranges::views::transform(argsTransform), ", "));
else
m_result << fmt::format("function {0}:\n {0}({1})", _fun.name.str(), fmt::join(m_cfg.arguments | ranges::views::transform(argsTransform), ", "));
m_result << "\"];\n";
m_result << "FunctionEntry_" << _fun.name.str() << "_" << m_cfg.entry.value << " -> Block" << m_functionIndex << "_" << m_cfg.entry.value << ";\n";
printBlock(m_cfg.entry);
}
SSACFG const& m_cfg;
size_t m_functionIndex;
SSACFGLiveness const* m_liveness;
std::stringstream m_result{};
};
}
std::string SSACFG::toDot(
bool _includeDiGraphDefinition,
std::optional<size_t> _functionIndex,
SSACFGLiveness const* _liveness
) const
{
std::ostringstream output;
if (_includeDiGraphDefinition)
output << "digraph SSACFG {\nnodesep=0.7;\ngraph[fontname=\"DejaVu Sans\"]\nnode[shape=box,fontname=\"DejaVu Sans\"];\n\n";
if (function)
output << SSACFGPrinter(*this, _functionIndex ? *_functionIndex : static_cast<size_t>(1), *function, _liveness);
else
output << SSACFGPrinter(*this, entry, _liveness);
if (_includeDiGraphDefinition)
output << "}\n";
return output.str();
}
| 10,531
|
C++
|
.cpp
| 265
| 35.811321
| 232
| 0.648965
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,077
|
AsmCodeGen.cpp
|
ethereum_solidity/libyul/backends/evm/AsmCodeGen.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Helper to compile Yul code using libevmasm.
*/
#include <libyul/backends/evm/AsmCodeGen.h>
#include <libyul/backends/evm/EthAssemblyAdapter.h>
#include <libyul/backends/evm/EVMCodeTransform.h>
#include <libyul/AST.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libsolutil/StackTooDeepString.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
using namespace solidity::langutil;
void CodeGenerator::assemble(
Block const& _parsedData,
AsmAnalysisInfo& _analysisInfo,
evmasm::Assembly& _assembly,
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
ExternalIdentifierAccess::CodeGenerator _identifierAccessCodeGen,
bool _useNamedLabelsForFunctions,
bool _optimizeStackAllocation
)
{
EthAssemblyAdapter assemblyAdapter(_assembly);
BuiltinContext builtinContext;
CodeTransform transform(
assemblyAdapter,
_analysisInfo,
_parsedData,
EVMDialect::strictAssemblyForEVM(_evmVersion, _eofVersion),
builtinContext,
_optimizeStackAllocation,
_identifierAccessCodeGen,
_useNamedLabelsForFunctions ?
CodeTransform::UseNamedLabels::YesAndForceUnique :
CodeTransform::UseNamedLabels::Never
);
transform(_parsedData);
if (!transform.stackErrors().empty())
assertThrow(
false,
langutil::StackTooDeepError,
util::stackTooDeepString + " When compiling inline assembly" +
(transform.stackErrors().front().comment() ? ": " + *transform.stackErrors().front().comment() : ".")
);
}
| 2,171
|
C++
|
.cpp
| 61
| 33.377049
| 104
| 0.795909
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,078
|
SSAControlFlowGraphBuilder.cpp
|
ethereum_solidity/libyul/backends/evm/SSAControlFlowGraphBuilder.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Transformation of a Yul AST into a control flow graph.
*/
#include <libyul/backends/evm/SSAControlFlowGraphBuilder.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/backends/evm/ControlFlow.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/StringUtils.h>
#include <libsolutil/Visitor.h>
#include <libsolutil/cxx20.h>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/drop_last.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/zip.hpp>
using namespace solidity;
using namespace solidity::yul;
namespace solidity::yul
{
SSAControlFlowGraphBuilder::SSAControlFlowGraphBuilder(
ControlFlow& _controlFlow,
SSACFG& _graph,
AsmAnalysisInfo const& _analysisInfo,
ControlFlowSideEffectsCollector const& _sideEffects,
Dialect const& _dialect
):
m_controlFlow(_controlFlow),
m_graph(_graph),
m_info(_analysisInfo),
m_sideEffects(_sideEffects),
m_dialect(_dialect)
{
}
std::unique_ptr<ControlFlow> SSAControlFlowGraphBuilder::build(
AsmAnalysisInfo const& _analysisInfo,
Dialect const& _dialect,
Block const& _block
)
{
ControlFlowSideEffectsCollector sideEffects(_dialect, _block);
auto controlFlow = std::make_unique<ControlFlow>();
SSAControlFlowGraphBuilder builder(*controlFlow, *controlFlow->mainGraph, _analysisInfo, sideEffects, _dialect);
builder.m_currentBlock = controlFlow->mainGraph->makeBlock(debugDataOf(_block));
builder.sealBlock(builder.m_currentBlock);
builder(_block);
if (!builder.blockInfo(builder.m_currentBlock).sealed)
builder.sealBlock(builder.m_currentBlock);
controlFlow->mainGraph->block(builder.m_currentBlock).exit = SSACFG::BasicBlock::MainExit{};
builder.cleanUnreachable();
return controlFlow;
}
SSACFG::ValueId SSAControlFlowGraphBuilder::tryRemoveTrivialPhi(SSACFG::ValueId _phi)
{
// TODO: double-check if this is sane
auto const* phiInfo = std::get_if<SSACFG::PhiValue>(&m_graph.valueInfo(_phi));
yulAssert(phiInfo);
yulAssert(blockInfo(phiInfo->block).sealed);
SSACFG::ValueId same;
for (SSACFG::ValueId arg: phiInfo->arguments)
{
if (arg == same || arg == _phi)
continue; // unique value or self-reference
if (same.hasValue())
return _phi; // phi merges at least two distinct values -> not trivial
same = arg;
}
if (!same.hasValue())
{
// This will happen for unreachable paths.
// TODO: check how best to deal with this
same = m_graph.unreachableValue();
}
m_graph.block(phiInfo->block).phis.erase(_phi);
std::set<SSACFG::ValueId> phiUses;
for (size_t blockIdValue = 0; blockIdValue < m_graph.numBlocks(); ++blockIdValue)
{
auto& block = m_graph.block(SSACFG::BlockId{blockIdValue});
for (auto blockPhi: block.phis)
{
yulAssert(blockPhi != _phi, "Phis should be defined in exactly one block, _phi was erased.");
auto* blockPhiInfo = std::get_if<SSACFG::PhiValue>(&m_graph.valueInfo(blockPhi));
yulAssert(blockPhiInfo);
bool usedInPhi = false;
for (auto& arg: blockPhiInfo->arguments)
if (arg == _phi)
{
arg = same;
usedInPhi = true;
}
if (usedInPhi)
phiUses.emplace(blockPhi);
}
for (auto& op: block.operations)
std::replace(op.inputs.begin(), op.inputs.end(), _phi, same);
std::visit(util::GenericVisitor{
[_phi, same](SSACFG::BasicBlock::FunctionReturn& _functionReturn) {
std::replace(
_functionReturn.returnValues.begin(),
_functionReturn.returnValues.end(),
_phi,
same
);
},
[_phi, same](SSACFG::BasicBlock::ConditionalJump& _condJump) {
if (_condJump.condition == _phi)
_condJump.condition = same;
},
[_phi, same](SSACFG::BasicBlock::JumpTable& _jumpTable) {
if (_jumpTable.value == _phi)
_jumpTable.value = same;
},
[](SSACFG::BasicBlock::Jump&) {},
[](SSACFG::BasicBlock::MainExit&) {},
[](SSACFG::BasicBlock::Terminated&) {}
}, block.exit);
}
for (auto& [_, currentVariableDefs]: m_currentDef)
std::replace(currentVariableDefs.begin(), currentVariableDefs.end(), _phi, same);
for (auto phiUse: phiUses)
tryRemoveTrivialPhi(phiUse);
return same;
}
/// Removes edges to blocks that are not reachable.
void SSAControlFlowGraphBuilder::cleanUnreachable()
{
// Determine which blocks are reachable from the entry.
util::BreadthFirstSearch<SSACFG::BlockId> reachabilityCheck{{m_graph.entry}};
reachabilityCheck.run([&](SSACFG::BlockId _blockId, auto&& _addChild) {
auto const& block = m_graph.block(_blockId);
visit(util::GenericVisitor{
[&](SSACFG::BasicBlock::Jump const& _jump) {
_addChild(_jump.target);
},
[&](SSACFG::BasicBlock::ConditionalJump const& _jump) {
_addChild(_jump.zero);
_addChild(_jump.nonZero);
},
[](SSACFG::BasicBlock::JumpTable const&) { yulAssert(false); },
[](SSACFG::BasicBlock::FunctionReturn const&) {},
[](SSACFG::BasicBlock::Terminated const&) {},
[](SSACFG::BasicBlock::MainExit const&) {}
}, block.exit);
});
auto isUnreachableValue = [&](SSACFG::ValueId const& _value) -> bool {
auto* valueInfo = std::get_if<SSACFG::UnreachableValue>(&m_graph.valueInfo(_value));
return (valueInfo) ? true : false;
};
// Remove all entries from unreachable nodes from the graph.
for (SSACFG::BlockId blockId: reachabilityCheck.visited)
{
auto& block = m_graph.block(blockId);
std::set<SSACFG::ValueId> maybeTrivialPhi;
for (auto it = block.entries.begin(); it != block.entries.end();)
if (reachabilityCheck.visited.count(*it))
it++;
else
it = block.entries.erase(it);
for (auto phi: block.phis)
if (auto* phiInfo = std::get_if<SSACFG::PhiValue>(&m_graph.valueInfo(phi)))
cxx20::erase_if(phiInfo->arguments, [&](SSACFG::ValueId _arg) {
if (isUnreachableValue(_arg))
{
maybeTrivialPhi.insert(phi);
return true;
}
return false;
});
// After removing a phi argument, we might end up with a trivial phi that can be removed.
for (auto phi: maybeTrivialPhi)
tryRemoveTrivialPhi(phi);
}
}
void SSAControlFlowGraphBuilder::buildFunctionGraph(
Scope::Function const* _function,
FunctionDefinition const* _functionDefinition
)
{
m_controlFlow.functionGraphs.emplace_back(std::make_unique<SSACFG>());
auto& cfg = *m_controlFlow.functionGraphs.back();
m_controlFlow.functionGraphMapping.emplace_back(_function, &cfg);
yulAssert(m_info.scopes.at(&_functionDefinition->body), "");
Scope* virtualFunctionScope = m_info.scopes.at(m_info.virtualBlocks.at(_functionDefinition).get()).get();
yulAssert(virtualFunctionScope, "");
cfg.entry = cfg.makeBlock(debugDataOf(_functionDefinition->body));
auto arguments = _functionDefinition->parameters | ranges::views::transform([&](auto const& _param) {
auto const& var = std::get<Scope::Variable>(virtualFunctionScope->identifiers.at(_param.name));
// Note: cannot use std::make_tuple since it unwraps reference wrappers.
return std::tuple{std::cref(var), cfg.newVariable(cfg.entry)};
}) | ranges::to<std::vector>;
auto returns = _functionDefinition->returnVariables | ranges::views::transform([&](auto const& _param) {
return std::cref(std::get<Scope::Variable>(virtualFunctionScope->identifiers.at(_param.name)));
}) | ranges::to<std::vector>;
cfg.debugData = _functionDefinition->debugData;
cfg.function = _function;
cfg.canContinue = m_sideEffects.functionSideEffects().at(_functionDefinition).canContinue;
cfg.arguments = arguments;
cfg.returns = returns;
SSAControlFlowGraphBuilder builder(m_controlFlow, cfg, m_info, m_sideEffects, m_dialect);
builder.m_currentBlock = cfg.entry;
builder.m_functionDefinitions = m_functionDefinitions;
for (auto&& [var, varId]: cfg.arguments)
builder.currentDef(var, cfg.entry) = varId;
for (auto const& var: cfg.returns)
builder.currentDef(var.get(), cfg.entry) = builder.zero();
builder.sealBlock(cfg.entry);
builder(_functionDefinition->body);
cfg.exits.insert(builder.m_currentBlock);
// Artificial explicit function exit (`leave`) at the end of the body.
builder(Leave{debugDataOf(*_functionDefinition)});
builder.cleanUnreachable();
}
void SSAControlFlowGraphBuilder::operator()(ExpressionStatement const& _expressionStatement)
{
auto const* functionCall = std::get_if<FunctionCall>(&_expressionStatement.expression);
yulAssert(functionCall);
auto results = visitFunctionCall(*functionCall);
yulAssert(results.empty());
}
void SSAControlFlowGraphBuilder::operator()(Assignment const& _assignment)
{
assign(
_assignment.variableNames | ranges::views::transform([&](auto& _var) { return std::ref(lookupVariable(_var.name)); }) | ranges::to<std::vector>,
_assignment.value.get()
);
}
void SSAControlFlowGraphBuilder::operator()(VariableDeclaration const& _variableDeclaration)
{
assign(
_variableDeclaration.variables | ranges::views::transform([&](auto& _var) { return std::ref(lookupVariable(_var.name)); }) | ranges::to<std::vector>,
_variableDeclaration.value.get()
);
}
void SSAControlFlowGraphBuilder::operator()(FunctionDefinition const& _functionDefinition)
{
Scope::Function const& function = lookupFunction(_functionDefinition.name);
buildFunctionGraph(&function, &_functionDefinition);
}
void SSAControlFlowGraphBuilder::operator()(If const& _if)
{
auto condition = std::visit(*this, *_if.condition);
auto ifBranch = m_graph.makeBlock(debugDataOf(_if.body));
auto afterIf = m_graph.makeBlock(debugDataOf(currentBlock()));
conditionalJump(
debugDataOf(_if),
condition,
ifBranch,
afterIf
);
sealBlock(ifBranch);
m_currentBlock = ifBranch;
(*this)(_if.body);
jump(debugDataOf(_if.body), afterIf);
sealBlock(afterIf);
}
void SSAControlFlowGraphBuilder::operator()(Switch const& _switch)
{
auto expression = std::visit(*this, *_switch.expression);
auto useJumpTableForSwitch = [](Switch const&) {
// TODO: check for EOF support & tight switch values.
return false;
};
if (useJumpTableForSwitch(_switch))
{
// TODO: also generate a subtraction to shift tight, but non-zero switch cases - or, alternative,
// transform to zero-based tight switches on Yul if possible.
std::map<u256, SSACFG::BlockId> cases;
std::optional<SSACFG::BlockId> defaultCase;
std::vector<std::tuple<SSACFG::BlockId, std::reference_wrapper<Block const>>> children;
for (auto const& _case: _switch.cases)
{
auto blockId = m_graph.makeBlock(debugDataOf(_case.body));
if (_case.value)
cases[_case.value->value.value()] = blockId;
else
defaultCase = blockId;
children.emplace_back(blockId, std::ref(_case.body));
}
auto afterSwitch = m_graph.makeBlock(debugDataOf(currentBlock()));
tableJump(debugDataOf(_switch), expression, cases, defaultCase ? *defaultCase : afterSwitch);
for (auto [blockId, block]: children)
{
sealBlock(blockId);
m_currentBlock = blockId;
(*this)(block);
jump(debugDataOf(currentBlock()), afterSwitch);
}
sealBlock(afterSwitch);
m_currentBlock = afterSwitch;
}
else
{
auto makeValueCompare = [&](Case const& _case) {
FunctionCall const& ghostCall = m_graph.ghostCalls.emplace_back(FunctionCall{
debugDataOf(_case),
Identifier{{}, "eq"_yulname},
{*_case.value /* skip second argument */ }
});
auto outputValue = m_graph.newVariable(m_currentBlock);
std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(ghostCall.functionName.name.str());
currentBlock().operations.emplace_back(SSACFG::Operation{
{outputValue},
SSACFG::BuiltinCall{
debugDataOf(_case),
m_dialect.builtin(*builtinHandle),
ghostCall
},
{m_graph.newLiteral(debugDataOf(_case), _case.value->value.value()), expression}
});
return outputValue;
};
auto afterSwitch = m_graph.makeBlock(debugDataOf(currentBlock()));
yulAssert(!_switch.cases.empty(), "");
for (auto const& switchCase: _switch.cases | ranges::views::drop_last(1))
{
yulAssert(switchCase.value, "");
auto caseBranch = m_graph.makeBlock(debugDataOf(switchCase.body));
auto elseBranch = m_graph.makeBlock(debugDataOf(_switch));
conditionalJump(debugDataOf(switchCase), makeValueCompare(switchCase), caseBranch, elseBranch);
sealBlock(caseBranch);
sealBlock(elseBranch);
m_currentBlock = caseBranch;
(*this)(switchCase.body);
jump(debugDataOf(switchCase.body), afterSwitch);
m_currentBlock = elseBranch;
}
Case const& switchCase = _switch.cases.back();
if (switchCase.value)
{
auto caseBranch = m_graph.makeBlock(debugDataOf(switchCase.body));
conditionalJump(debugDataOf(switchCase), makeValueCompare(switchCase), caseBranch, afterSwitch);
sealBlock(caseBranch);
m_currentBlock = caseBranch;
}
(*this)(switchCase.body);
jump(debugDataOf(switchCase.body), afterSwitch);
sealBlock(afterSwitch);
}
}
void SSAControlFlowGraphBuilder::operator()(ForLoop const& _loop)
{
ScopedSaveAndRestore scopeRestore(m_scope, m_info.scopes.at(&_loop.pre).get());
(*this)(_loop.pre);
auto preLoopDebugData = debugDataOf(currentBlock());
std::optional<bool> constantCondition;
if (auto const* literalCondition = std::get_if<Literal>(_loop.condition.get()))
constantCondition = literalCondition->value.value() != 0;
SSACFG::BlockId loopCondition = m_graph.makeBlock(debugDataOf(*_loop.condition));
SSACFG::BlockId loopBody = m_graph.makeBlock(debugDataOf(_loop.body));
SSACFG::BlockId post = m_graph.makeBlock(debugDataOf(_loop.post));
SSACFG::BlockId afterLoop = m_graph.makeBlock(preLoopDebugData);
class ForLoopInfoScope {
public:
ForLoopInfoScope(std::stack<ForLoopInfo>& _info, SSACFG::BlockId _breakBlock, SSACFG::BlockId _continueBlock): m_info(_info)
{
m_info.push(ForLoopInfo{_breakBlock, _continueBlock});
}
~ForLoopInfoScope() {
m_info.pop();
}
private:
std::stack<ForLoopInfo>& m_info;
} forLoopInfoScope(m_forLoopInfo, afterLoop, post);
if (constantCondition.has_value())
{
std::visit(*this, *_loop.condition);
if (*constantCondition)
{
jump(debugDataOf(*_loop.condition), loopBody);
(*this)(_loop.body);
jump(debugDataOf(_loop.body), post);
sealBlock(post);
(*this)(_loop.post);
jump(debugDataOf(_loop.post), loopBody);
sealBlock(loopBody);
}
else
jump(debugDataOf(*_loop.condition), afterLoop);
}
else
{
jump(debugDataOf(_loop.pre), loopCondition);
auto condition = std::visit(*this, *_loop.condition);
conditionalJump(debugDataOf(*_loop.condition), condition, loopBody, afterLoop);
sealBlock(loopBody);
m_currentBlock = loopBody;
(*this)(_loop.body);
jump(debugDataOf(_loop.body), post);
sealBlock(post);
(*this)(_loop.post);
jump(debugDataOf(_loop.post), loopCondition);
sealBlock(loopCondition);
}
sealBlock(afterLoop);
m_currentBlock = afterLoop;
}
void SSAControlFlowGraphBuilder::operator()(Break const& _break)
{
yulAssert(!m_forLoopInfo.empty());
auto currentBlockDebugData = debugDataOf(currentBlock());
jump(debugDataOf(_break), m_forLoopInfo.top().breakBlock);
m_currentBlock = m_graph.makeBlock(currentBlockDebugData);
sealBlock(m_currentBlock);
}
void SSAControlFlowGraphBuilder::operator()(Continue const& _continue)
{
yulAssert(!m_forLoopInfo.empty());
auto currentBlockDebugData = debugDataOf(currentBlock());
jump(debugDataOf(_continue), m_forLoopInfo.top().continueBlock);
m_currentBlock = m_graph.makeBlock(currentBlockDebugData);
sealBlock(m_currentBlock);
}
void SSAControlFlowGraphBuilder::operator()(Leave const& _leaveStatement)
{
auto currentBlockDebugData = debugDataOf(currentBlock());
currentBlock().exit = SSACFG::BasicBlock::FunctionReturn{
debugDataOf(_leaveStatement),
m_graph.returns | ranges::views::transform([&](auto _var) {
return readVariable(_var, m_currentBlock);
}) | ranges::to<std::vector>
};
m_currentBlock = m_graph.makeBlock(currentBlockDebugData);
sealBlock(m_currentBlock);
}
void SSAControlFlowGraphBuilder::registerFunctionDefinition(FunctionDefinition const& _functionDefinition)
{
yulAssert(m_scope, "");
yulAssert(m_scope->identifiers.count(_functionDefinition.name), "");
auto& function = std::get<Scope::Function>(m_scope->identifiers.at(_functionDefinition.name));
m_graph.functions.emplace_back(function);
m_functionDefinitions.emplace_back(&function, &_functionDefinition);
}
void SSAControlFlowGraphBuilder::operator()(Block const& _block)
{
ScopedSaveAndRestore saveScope(m_scope, m_info.scopes.at(&_block).get());
// gather all function definitions so that they are visible to each other's subgraphs
static constexpr auto functionDefinitionFilter = ranges::views::filter(
[](auto const& _statement) { return std::holds_alternative<FunctionDefinition>(_statement); }
);
for (auto const& statement: _block.statements | functionDefinitionFilter)
registerFunctionDefinition(std::get<FunctionDefinition>(statement));
// now visit the rest
for (auto const& statement: _block.statements)
std::visit(*this, statement);
}
SSACFG::ValueId SSAControlFlowGraphBuilder::operator()(FunctionCall const& _call)
{
auto results = visitFunctionCall(_call);
yulAssert(results.size() == 1);
return results.front();
}
SSACFG::ValueId SSAControlFlowGraphBuilder::operator()(Identifier const& _identifier)
{
auto const& var = lookupVariable(_identifier.name);
return readVariable(var, m_currentBlock);
}
SSACFG::ValueId SSAControlFlowGraphBuilder::operator()(Literal const& _literal)
{
return m_graph.newLiteral(debugDataOf(currentBlock()), _literal.value.value());
}
void SSAControlFlowGraphBuilder::assign(std::vector<std::reference_wrapper<Scope::Variable const>> _variables, Expression const* _expression)
{
auto rhs = [&]() -> std::vector<SSACFG::ValueId> {
if (auto const* functionCall = std::get_if<FunctionCall>(_expression))
return visitFunctionCall(*functionCall);
else if (_expression)
return {std::visit(*this, *_expression)};
else
return {_variables.size(), zero()};
}();
yulAssert(rhs.size() == _variables.size());
for (auto const& [var, value]: ranges::zip_view(_variables, rhs))
writeVariable(var, m_currentBlock, value);
}
std::vector<SSACFG::ValueId> SSAControlFlowGraphBuilder::visitFunctionCall(FunctionCall const& _call)
{
bool canContinue = true;
SSACFG::Operation operation = [&](){
if (std::optional<BuiltinHandle> const& builtinHandle = m_dialect.findBuiltin(_call.functionName.name.str()))
{
auto const& builtinFunction = m_dialect.builtin(*builtinHandle);
SSACFG::Operation result{{}, SSACFG::BuiltinCall{_call.debugData, builtinFunction, _call}, {}};
for (auto&& [idx, arg]: _call.arguments | ranges::views::enumerate | ranges::views::reverse)
if (!builtinFunction.literalArgument(idx).has_value())
result.inputs.emplace_back(std::visit(*this, arg));
for (size_t i = 0; i < builtinFunction.numReturns; ++i)
result.outputs.emplace_back(m_graph.newVariable(m_currentBlock));
canContinue = builtinFunction.controlFlowSideEffects.canContinue;
return result;
}
else
{
Scope::Function const& function = lookupFunction(_call.functionName.name);
auto const* definition = findFunctionDefinition(&function);
yulAssert(definition);
canContinue = m_sideEffects.functionSideEffects().at(definition).canContinue;
SSACFG::Operation result{{}, SSACFG::Call{debugDataOf(_call), function, _call, canContinue}, {}};
for (auto const& arg: _call.arguments | ranges::views::reverse)
result.inputs.emplace_back(std::visit(*this, arg));
for (size_t i = 0; i < function.numReturns; ++i)
result.outputs.emplace_back(m_graph.newVariable(m_currentBlock));
return result;
}
}();
auto results = operation.outputs;
currentBlock().operations.emplace_back(std::move(operation));
if (!canContinue)
{
currentBlock().exit = SSACFG::BasicBlock::Terminated{};
m_currentBlock = m_graph.makeBlock(debugDataOf(currentBlock()));
sealBlock(m_currentBlock);
}
return results;
}
SSACFG::ValueId SSAControlFlowGraphBuilder::zero()
{
return m_graph.newLiteral(debugDataOf(currentBlock()), 0u);
}
SSACFG::ValueId SSAControlFlowGraphBuilder::readVariable(Scope::Variable const& _variable, SSACFG::BlockId _block)
{
if (auto const& def = currentDef(_variable, _block))
return *def;
return readVariableRecursive(_variable, _block);
}
SSACFG::ValueId SSAControlFlowGraphBuilder::readVariableRecursive(Scope::Variable const& _variable, SSACFG::BlockId _block)
{
auto& block = m_graph.block(_block);
auto& info = blockInfo(_block);
SSACFG::ValueId val;
if (!info.sealed)
{
// incomplete block
val = m_graph.newPhi(_block);
block.phis.insert(val);
info.incompletePhis.emplace_back(val, std::ref(_variable));
}
else if (block.entries.size() == 1)
// one predecessor: no phi needed
val = readVariable(_variable, *block.entries.begin());
else
{
// Break potential cycles with operandless phi
val = m_graph.newPhi(_block);
block.phis.insert(val);
writeVariable(_variable, _block, val);
// we call tryRemoveTrivialPhi explicitly opposed to what is presented in Algorithm 2, as our implementation
// does not call it in addPhiOperands to avoid removing phis in unsealed blocks
val = tryRemoveTrivialPhi(addPhiOperands(_variable, val));
}
writeVariable(_variable, _block, val);
return val;
}
SSACFG::ValueId SSAControlFlowGraphBuilder::addPhiOperands(Scope::Variable const& _variable, SSACFG::ValueId _phi)
{
yulAssert(std::holds_alternative<SSACFG::PhiValue>(m_graph.valueInfo(_phi)));
auto& phi = std::get<SSACFG::PhiValue>(m_graph.valueInfo(_phi));
for (auto pred: m_graph.block(phi.block).entries)
phi.arguments.emplace_back(readVariable(_variable, pred));
// we call tryRemoveTrivialPhi explicitly to avoid removing trivial phis in unsealed blocks
return _phi;
}
void SSAControlFlowGraphBuilder::writeVariable(Scope::Variable const& _variable, SSACFG::BlockId _block, SSACFG::ValueId _value)
{
currentDef(_variable, _block) = _value;
}
Scope::Function const& SSAControlFlowGraphBuilder::lookupFunction(YulName _name) const
{
Scope::Function const* function = nullptr;
yulAssert(m_scope->lookup(_name, util::GenericVisitor{
[](Scope::Variable&) { yulAssert(false, "Expected function name."); },
[&](Scope::Function& _function) { function = &_function; }
}), "Function name not found.");
yulAssert(function, "");
return *function;
}
Scope::Variable const& SSAControlFlowGraphBuilder::lookupVariable(YulName _name) const
{
yulAssert(m_scope, "");
Scope::Variable const* var = nullptr;
if (m_scope->lookup(_name, util::GenericVisitor{
[&](Scope::Variable& _var) { var = &_var; },
[](Scope::Function&)
{
yulAssert(false, "Function not removed during desugaring.");
}
}))
{
yulAssert(var, "");
return *var;
};
yulAssert(false, "External identifier access unimplemented.");
}
void SSAControlFlowGraphBuilder::sealBlock(SSACFG::BlockId _block)
{
// this method deviates from Algorithm 4 in the reference paper,
// as it would lead to tryRemoveTrivialPhi being called on unsealed blocks
auto& info = blockInfo(_block);
yulAssert(!info.sealed, "Trying to seal already sealed block.");
for (auto&& [phi, variable] : info.incompletePhis)
addPhiOperands(variable, phi);
info.sealed = true;
for (auto& [phi, _]: info.incompletePhis)
phi = tryRemoveTrivialPhi(phi);
}
void SSAControlFlowGraphBuilder::conditionalJump(
langutil::DebugData::ConstPtr _debugData,
SSACFG::ValueId _condition,
SSACFG::BlockId _nonZero,
SSACFG::BlockId _zero
)
{
currentBlock().exit = SSACFG::BasicBlock::ConditionalJump{
std::move(_debugData),
_condition,
_nonZero,
_zero
};
m_graph.block(_nonZero).entries.insert(m_currentBlock);
m_graph.block(_zero).entries.insert(m_currentBlock);
m_currentBlock = {};
}
void SSAControlFlowGraphBuilder::jump(
langutil::DebugData::ConstPtr _debugData,
SSACFG::BlockId _target
)
{
currentBlock().exit = SSACFG::BasicBlock::Jump{std::move(_debugData), _target};
yulAssert(!blockInfo(_target).sealed);
m_graph.block(_target).entries.insert(m_currentBlock);
m_currentBlock = _target;
}
void SSAControlFlowGraphBuilder::tableJump(
langutil::DebugData::ConstPtr _debugData,
SSACFG::ValueId _value,
std::map<u256, SSACFG::BlockId> _cases,
SSACFG::BlockId _defaultCase)
{
for (auto caseBlock: _cases | ranges::views::values)
{
yulAssert(!blockInfo(caseBlock).sealed);
m_graph.block(caseBlock).entries.insert(m_currentBlock);
}
yulAssert(!blockInfo(_defaultCase).sealed);
m_graph.block(_defaultCase).entries.insert(m_currentBlock);
currentBlock().exit = SSACFG::BasicBlock::JumpTable{std::move(_debugData), _value, std::move(_cases), _defaultCase};
m_currentBlock = {};
}
FunctionDefinition const* SSAControlFlowGraphBuilder::findFunctionDefinition(Scope::Function const* _function) const
{
auto it = std::find_if(
m_functionDefinitions.begin(),
m_functionDefinitions.end(),
[&_function](auto const& _entry) { return std::get<0>(_entry) == _function; }
);
if (it != m_functionDefinitions.end())
return std::get<1>(*it);
return nullptr;
}
}
| 25,703
|
C++
|
.cpp
| 676
| 35.378698
| 151
| 0.746494
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,079
|
StackLayoutGenerator.cpp
|
ethereum_solidity/libyul/backends/evm/StackLayoutGenerator.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Stack layout generator for Yul to EVM code generation.
*/
#include <libyul/backends/evm/StackLayoutGenerator.h>
#include <libyul/backends/evm/StackHelpers.h>
#include <libevmasm/GasMeter.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/cxx20.h>
#include <libsolutil/Visitor.h>
#include <range/v3/algorithm/any_of.hpp>
#include <range/v3/algorithm/find.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/all.hpp>
#include <range/v3/view/concat.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/drop_last.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/take.hpp>
#include <range/v3/view/take_last.hpp>
#include <range/v3/view/transform.hpp>
using namespace solidity;
using namespace solidity::yul;
StackLayout StackLayoutGenerator::run(CFG const& _cfg)
{
StackLayout stackLayout;
StackLayoutGenerator{stackLayout, nullptr}.processEntryPoint(*_cfg.entry);
for (auto& functionInfo: _cfg.functionInfo | ranges::views::values)
StackLayoutGenerator{stackLayout, &functionInfo}.processEntryPoint(*functionInfo.entry, &functionInfo);
return stackLayout;
}
std::map<YulName, std::vector<StackLayoutGenerator::StackTooDeep>> StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg)
{
std::map<YulName, std::vector<StackLayoutGenerator::StackTooDeep>> stackTooDeepErrors;
stackTooDeepErrors[YulName{}] = reportStackTooDeep(_cfg, YulName{});
for (auto const& function: _cfg.functions)
if (auto errors = reportStackTooDeep(_cfg, function->name); !errors.empty())
stackTooDeepErrors[function->name] = std::move(errors);
return stackTooDeepErrors;
}
std::vector<StackLayoutGenerator::StackTooDeep> StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg, YulName _functionName)
{
StackLayout stackLayout;
CFG::FunctionInfo const* functionInfo = nullptr;
if (!_functionName.empty())
{
functionInfo = &ranges::find(
_cfg.functionInfo,
_functionName,
util::mapTuple([](auto&&, auto&& info) { return info.function.name; })
)->second;
yulAssert(functionInfo, "Function not found.");
}
StackLayoutGenerator generator{stackLayout, functionInfo};
CFG::BasicBlock const* entry = functionInfo ? functionInfo->entry : _cfg.entry;
generator.processEntryPoint(*entry);
return generator.reportStackTooDeep(*entry);
}
StackLayoutGenerator::StackLayoutGenerator(StackLayout& _layout, CFG::FunctionInfo const* _functionInfo):
m_layout(_layout),
m_currentFunctionInfo(_functionInfo)
{
}
namespace
{
/// @returns all stack too deep errors that would occur when shuffling @a _source to @a _target.
std::vector<StackLayoutGenerator::StackTooDeep> findStackTooDeep(Stack const& _source, Stack const& _target)
{
Stack currentStack = _source;
std::vector<StackLayoutGenerator::StackTooDeep> stackTooDeepErrors;
auto getVariableChoices = [](auto&& _range) {
std::vector<YulName> result;
for (auto const& slot: _range)
if (auto const* variableSlot = std::get_if<VariableSlot>(&slot))
if (!util::contains(result, variableSlot->variable.get().name))
result.push_back(variableSlot->variable.get().name);
return result;
};
::createStackLayout(
currentStack,
_target,
[&](unsigned _i)
{
if (_i > 16)
stackTooDeepErrors.emplace_back(StackLayoutGenerator::StackTooDeep{
_i - 16,
getVariableChoices(currentStack | ranges::views::take_last(_i + 1))
});
},
[&](StackSlot const& _slot)
{
if (canBeFreelyGenerated(_slot))
return;
if (
auto depth = util::findOffset(currentStack | ranges::views::reverse, _slot);
depth && *depth >= 16
)
stackTooDeepErrors.emplace_back(StackLayoutGenerator::StackTooDeep{
*depth - 15,
getVariableChoices(currentStack | ranges::views::take_last(*depth + 1))
});
},
[&]() {}
);
return stackTooDeepErrors;
}
/// @returns the ideal stack to have before executing an operation that outputs @a _operationOutput, s.t.
/// shuffling to @a _post is cheap (excluding the input of the operation itself).
/// If @a _generateSlotOnTheFly returns true for a slot, this slot should not occur in the ideal stack, but
/// rather be generated on the fly during shuffling.
template<typename Callable>
Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Callable _generateSlotOnTheFly)
{
struct PreviousSlot { size_t slot; };
// Determine the number of slots that have to be on stack before executing the operation (excluding
// the inputs of the operation itself).
// That is slots that should not be generated on the fly and are not outputs of the operation.
size_t preOperationLayoutSize = _post.size();
for (auto const& slot: _post)
if (util::contains(_operationOutput, slot) || _generateSlotOnTheFly(slot))
--preOperationLayoutSize;
// The symbolic layout directly after the operation has the form
// PreviousSlot{0}, ..., PreviousSlot{n}, [output<0>], ..., [output<m>]
auto layout = ranges::views::iota(0u, preOperationLayoutSize) |
ranges::views::transform([](size_t _index) { return PreviousSlot{_index}; }) |
ranges::to<std::vector<std::variant<PreviousSlot, StackSlot>>>;
layout += _operationOutput;
// Shortcut for trivial case.
if (layout.empty())
return Stack{};
// Next we will shuffle the layout to the post stack using ShuffleOperations
// that are aware of PreviousSlot's.
struct ShuffleOperations
{
std::vector<std::variant<PreviousSlot, StackSlot>>& layout;
Stack const& post;
std::set<StackSlot> outputs;
Multiplicity multiplicity;
Callable generateSlotOnTheFly;
ShuffleOperations(
std::vector<std::variant<PreviousSlot, StackSlot>>& _layout,
Stack const& _post,
Callable _generateSlotOnTheFly
): layout(_layout), post(_post), generateSlotOnTheFly(_generateSlotOnTheFly)
{
for (auto const& layoutSlot: layout)
if (StackSlot const* slot = std::get_if<StackSlot>(&layoutSlot))
outputs.insert(*slot);
for (auto const& layoutSlot: layout)
if (StackSlot const* slot = std::get_if<StackSlot>(&layoutSlot))
--multiplicity[*slot];
for (auto&& slot: post)
if (outputs.count(slot) || generateSlotOnTheFly(slot))
++multiplicity[slot];
}
bool isCompatible(size_t _source, size_t _target)
{
return
_source < layout.size() &&
_target < post.size() &&
(
std::holds_alternative<JunkSlot>(post.at(_target)) ||
std::visit(util::GenericVisitor{
[&](PreviousSlot const&) {
return !outputs.count(post.at(_target)) && !generateSlotOnTheFly(post.at(_target));
},
[&](StackSlot const& _s) { return _s == post.at(_target); }
}, layout.at(_source))
);
}
bool sourceIsSame(size_t _lhs, size_t _rhs)
{
return std::visit(util::GenericVisitor{
[&](PreviousSlot const&, PreviousSlot const&) { return true; },
[&](StackSlot const& _lhs, StackSlot const& _rhs) { return _lhs == _rhs; },
[&](auto const&, auto const&) { return false; }
}, layout.at(_lhs), layout.at(_rhs));
}
int sourceMultiplicity(size_t _offset)
{
return std::visit(util::GenericVisitor{
[&](PreviousSlot const&) { return 0; },
[&](StackSlot const& _s) { return multiplicity.at(_s); }
}, layout.at(_offset));
}
int targetMultiplicity(size_t _offset)
{
if (!outputs.count(post.at(_offset)) && !generateSlotOnTheFly(post.at(_offset)))
return 0;
return multiplicity.at(post.at(_offset));
}
bool targetIsArbitrary(size_t _offset)
{
return _offset < post.size() && std::holds_alternative<JunkSlot>(post.at(_offset));
}
void swap(size_t _i)
{
yulAssert(!std::holds_alternative<PreviousSlot>(layout.at(layout.size() - _i - 1)) || !std::holds_alternative<PreviousSlot>(layout.back()), "");
std::swap(layout.at(layout.size() - _i - 1), layout.back());
}
size_t sourceSize() { return layout.size(); }
size_t targetSize() { return post.size(); }
void pop() { layout.pop_back(); }
void pushOrDupTarget(size_t _offset) { layout.push_back(post.at(_offset)); }
};
Shuffler<ShuffleOperations>::shuffle(layout, _post, _generateSlotOnTheFly);
// Now we can construct the ideal layout before the operation.
// "layout" has shuffled the PreviousSlot{x} to new places using minimal operations to move the operation
// output in place. The resulting permutation of the PreviousSlot yields the ideal positions of slots
// before the operation, i.e. if PreviousSlot{2} is at a position at which _post contains VariableSlot{"tmp"},
// then we want the variable tmp in the slot at offset 2 in the layout before the operation.
std::vector<std::optional<StackSlot>> idealLayout(_post.size(), std::nullopt);
for (auto&& [slot, idealPosition]: ranges::zip_view(_post, layout))
if (PreviousSlot* previousSlot = std::get_if<PreviousSlot>(&idealPosition))
idealLayout.at(previousSlot->slot) = slot;
// The tail of layout must have contained the operation outputs and will not have been assigned slots in the last loop.
while (!idealLayout.empty() && !idealLayout.back())
idealLayout.pop_back();
yulAssert(idealLayout.size() == preOperationLayoutSize, "");
return idealLayout | ranges::views::transform([](std::optional<StackSlot> s) {
yulAssert(s, "");
return *s;
}) | ranges::to<Stack>;
}
}
Stack StackLayoutGenerator::propagateStackThroughOperation(Stack _exitStack, CFG::Operation const& _operation, bool _aggressiveStackCompression)
{
// Enable aggressive stack compression for recursive calls.
if (auto const* functionCall = std::get_if<CFG::FunctionCall>(&_operation.operation))
if (functionCall->recursive)
_aggressiveStackCompression = true;
// This is a huge tradeoff between code size, gas cost and stack size.
auto generateSlotOnTheFly = [&](StackSlot const& _slot) {
return _aggressiveStackCompression && canBeFreelyGenerated(_slot);
};
// Determine the ideal permutation of the slots in _exitLayout that are not operation outputs (and not to be
// generated on the fly), s.t. shuffling the `stack + _operation.output` to _exitLayout is cheap.
Stack stack = createIdealLayout(_operation.output, _exitStack, generateSlotOnTheFly);
// Make sure the resulting previous slots do not overlap with any assignmed variables.
if (auto const* assignment = std::get_if<CFG::Assignment>(&_operation.operation))
for (auto& stackSlot: stack)
if (auto const* varSlot = std::get_if<VariableSlot>(&stackSlot))
yulAssert(!util::contains(assignment->variables, *varSlot), "");
// Since stack+_operation.output can be easily shuffled to _exitLayout, the desired layout before the operation
// is stack+_operation.input;
stack += _operation.input;
// Store the exact desired operation entry layout. The stored layout will be recreated by the code transform
// before executing the operation. However, this recreation can produce slots that can be freely generated or
// are duplicated, i.e. we can compress the stack afterwards without causing problems for code generation later.
m_layout.operationEntryLayout[&_operation] = stack;
// Remove anything from the stack top that can be freely generated or dupped from deeper on the stack.
while (!stack.empty())
{
if (canBeFreelyGenerated(stack.back()))
stack.pop_back();
else if (auto offset = util::findOffset(stack | ranges::views::reverse | ranges::views::drop(1), stack.back()))
{
if (*offset + 2 < 16)
stack.pop_back();
else
break;
}
else
break;
}
return stack;
}
Stack StackLayoutGenerator::propagateStackThroughBlock(Stack _exitStack, CFG::BasicBlock const& _block, bool _aggressiveStackCompression)
{
Stack stack = _exitStack;
for (auto&& [idx, operation]: _block.operations | ranges::views::enumerate | ranges::views::reverse)
{
Stack newStack = propagateStackThroughOperation(stack, operation, _aggressiveStackCompression);
if (!_aggressiveStackCompression && !findStackTooDeep(newStack, stack).empty())
// If we had stack errors, run again with aggressive stack compression.
return propagateStackThroughBlock(std::move(_exitStack), _block, true);
stack = std::move(newStack);
}
return stack;
}
void StackLayoutGenerator::processEntryPoint(CFG::BasicBlock const& _entry, CFG::FunctionInfo const* _functionInfo)
{
std::list<CFG::BasicBlock const*> toVisit{&_entry};
std::set<CFG::BasicBlock const*> visited;
// TODO: check whether visiting only a subset of these in the outer iteration below is enough.
std::list<std::pair<CFG::BasicBlock const*, CFG::BasicBlock const*>> backwardsJumps = collectBackwardsJumps(_entry);
while (!toVisit.empty())
{
// First calculate stack layouts without walking backwards jumps, i.e. assuming the current preliminary
// entry layout of the backwards jump target as the initial exit layout of the backwards-jumping block.
while (!toVisit.empty())
{
CFG::BasicBlock const *block = *toVisit.begin();
toVisit.pop_front();
if (visited.count(block))
continue;
if (std::optional<Stack> exitLayout = getExitLayoutOrStageDependencies(*block, visited, toVisit))
{
visited.emplace(block);
auto& info = m_layout.blockInfos[block];
info.exitLayout = *exitLayout;
info.entryLayout = propagateStackThroughBlock(info.exitLayout, *block);
for (auto entry: block->entries)
toVisit.emplace_back(entry);
}
else
continue;
}
// Determine which backwards jumps still require fixing and stage revisits of appropriate nodes.
for (auto [jumpingBlock, target]: backwardsJumps)
// This block jumps backwards, but does not provide all slots required by the jump target on exit.
// Therefore we need to visit the subgraph between ``target`` and ``jumpingBlock`` again.
if (ranges::any_of(
m_layout.blockInfos[target].entryLayout,
[exitLayout = m_layout.blockInfos[jumpingBlock].exitLayout](StackSlot const& _slot) {
return !util::contains(exitLayout, _slot);
}
))
{
// In particular we can visit backwards starting from ``jumpingBlock`` and mark all entries to-be-visited-
// again until we hit ``target``.
toVisit.emplace_front(jumpingBlock);
// Since we are likely to permute the entry layout of ``target``, we also visit its entries again.
// This is not required for correctness, since the set of stack slots will match, but it may move some
// required stack shuffling from the loop condition to outside the loop.
for (CFG::BasicBlock const* entry: target->entries)
visited.erase(entry);
util::BreadthFirstSearch<CFG::BasicBlock const*>{{jumpingBlock}}.run(
[&visited, target = target](CFG::BasicBlock const* _block, auto _addChild) {
visited.erase(_block);
if (_block == target)
return;
for (auto const* entry: _block->entries)
_addChild(entry);
}
);
// While the shuffled layout for ``target`` will be compatible, it can be worthwhile propagating
// it further up once more.
// This would mean not stopping at _block == target above, resp. even doing visited.clear() here, revisiting the entire graph.
// This is a tradeoff between the runtime of this process and the optimality of the result.
// Also note that while visiting the entire graph again *can* be helpful, it can also be detrimental.
}
}
stitchConditionalJumps(_entry);
fillInJunk(_entry, _functionInfo);
}
std::optional<Stack> StackLayoutGenerator::getExitLayoutOrStageDependencies(
CFG::BasicBlock const& _block,
std::set<CFG::BasicBlock const*> const& _visited,
std::list<CFG::BasicBlock const*>& _toVisit
) const
{
return std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) -> std::optional<Stack>
{
// On the exit of the outermost block the stack can be empty.
return Stack{};
},
[&](CFG::BasicBlock::Jump const& _jump) -> std::optional<Stack>
{
if (_jump.backwards)
{
// Choose the best currently known entry layout of the jump target as initial exit.
// Note that this may not yet be the final layout.
if (auto* info = util::valueOrNullptr(m_layout.blockInfos, _jump.target))
return info->entryLayout;
return Stack{};
}
// If the current iteration has already visited the jump target, start from its entry layout.
if (_visited.count(_jump.target))
return m_layout.blockInfos.at(_jump.target).entryLayout;
// Otherwise stage the jump target for visit and defer the current block.
_toVisit.emplace_front(_jump.target);
return std::nullopt;
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump) -> std::optional<Stack>
{
bool zeroVisited = _visited.count(_conditionalJump.zero);
bool nonZeroVisited = _visited.count(_conditionalJump.nonZero);
if (zeroVisited && nonZeroVisited)
{
// If the current iteration has already visited both jump targets, start from its entry layout.
Stack stack = combineStack(
m_layout.blockInfos.at(_conditionalJump.zero).entryLayout,
m_layout.blockInfos.at(_conditionalJump.nonZero).entryLayout
);
// Additionally, the jump condition has to be at the stack top at exit.
stack.emplace_back(_conditionalJump.condition);
return stack;
}
// If one of the jump targets has not been visited, stage it for visit and defer the current block.
if (!zeroVisited)
_toVisit.emplace_front(_conditionalJump.zero);
if (!nonZeroVisited)
_toVisit.emplace_front(_conditionalJump.nonZero);
return std::nullopt;
},
[&](CFG::BasicBlock::FunctionReturn const& _functionReturn) -> std::optional<Stack>
{
// A function return needs the return variables and the function return label slot on stack.
yulAssert(_functionReturn.info, "");
Stack stack = _functionReturn.info->returnVariables | ranges::views::transform([](auto const& _varSlot){
return StackSlot{_varSlot};
}) | ranges::to<Stack>;
stack.emplace_back(FunctionReturnLabelSlot{_functionReturn.info->function});
return stack;
},
[&](CFG::BasicBlock::Terminated const&) -> std::optional<Stack>
{
// A terminating block can have an empty stack on exit.
return Stack{};
},
}, _block.exit);
}
std::list<std::pair<CFG::BasicBlock const*, CFG::BasicBlock const*>> StackLayoutGenerator::collectBackwardsJumps(CFG::BasicBlock const& _entry) const
{
std::list<std::pair<CFG::BasicBlock const*, CFG::BasicBlock const*>> backwardsJumps;
util::BreadthFirstSearch<CFG::BasicBlock const*>{{&_entry}}.run([&](CFG::BasicBlock const* _block, auto _addChild) {
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) {},
[&](CFG::BasicBlock::Jump const& _jump)
{
if (_jump.backwards)
backwardsJumps.emplace_back(_block, _jump.target);
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) {},
[&](CFG::BasicBlock::Terminated const&) {},
}, _block->exit);
});
return backwardsJumps;
}
void StackLayoutGenerator::stitchConditionalJumps(CFG::BasicBlock const& _block)
{
util::BreadthFirstSearch<CFG::BasicBlock const*> breadthFirstSearch{{&_block}};
breadthFirstSearch.run([&](CFG::BasicBlock const* _block, auto _addChild) {
auto& info = m_layout.blockInfos.at(_block);
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) {},
[&](CFG::BasicBlock::Jump const& _jump)
{
if (!_jump.backwards)
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
auto& zeroTargetInfo = m_layout.blockInfos.at(_conditionalJump.zero);
auto& nonZeroTargetInfo = m_layout.blockInfos.at(_conditionalJump.nonZero);
Stack exitLayout = info.exitLayout;
// The last block must have produced the condition at the stack top.
yulAssert(!exitLayout.empty(), "");
yulAssert(exitLayout.back() == _conditionalJump.condition, "");
// The condition is consumed by the jump.
exitLayout.pop_back();
auto fixJumpTargetEntry = [&](Stack const& _originalEntryLayout) -> Stack {
Stack newEntryLayout = exitLayout;
// Whatever the block being jumped to does not actually require, can be marked as junk.
for (auto& slot: newEntryLayout)
if (!util::contains(_originalEntryLayout, slot))
slot = JunkSlot{};
// Make sure everything the block being jumped to requires is actually present or can be generated.
for (auto const& slot: _originalEntryLayout)
yulAssert(canBeFreelyGenerated(slot) || util::contains(newEntryLayout, slot), "");
return newEntryLayout;
};
zeroTargetInfo.entryLayout = fixJumpTargetEntry(zeroTargetInfo.entryLayout);
nonZeroTargetInfo.entryLayout = fixJumpTargetEntry(nonZeroTargetInfo.entryLayout);
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) {},
[&](CFG::BasicBlock::Terminated const&) { },
}, _block->exit);
});
}
Stack StackLayoutGenerator::combineStack(Stack const& _stack1, Stack const& _stack2)
{
// TODO: it would be nicer to replace this by a constructive algorithm.
// Currently it uses a reduced version of the Heap Algorithm to partly brute-force, which seems
// to work decently well.
Stack commonPrefix;
for (auto&& [slot1, slot2]: ranges::zip_view(_stack1, _stack2))
{
if (!(slot1 == slot2))
break;
commonPrefix.emplace_back(slot1);
}
Stack stack1Tail = _stack1 | ranges::views::drop(commonPrefix.size()) | ranges::to<Stack>;
Stack stack2Tail = _stack2 | ranges::views::drop(commonPrefix.size()) | ranges::to<Stack>;
if (stack1Tail.empty())
return commonPrefix + compressStack(stack2Tail);
if (stack2Tail.empty())
return commonPrefix + compressStack(stack1Tail);
Stack candidate;
for (auto slot: stack1Tail)
if (!util::contains(candidate, slot))
candidate.emplace_back(slot);
for (auto slot: stack2Tail)
if (!util::contains(candidate, slot))
candidate.emplace_back(slot);
cxx20::erase_if(candidate, [](StackSlot const& slot) {
return std::holds_alternative<LiteralSlot>(slot) || std::holds_alternative<FunctionCallReturnLabelSlot>(slot);
});
auto evaluate = [&](Stack const& _candidate) -> size_t {
size_t numOps = 0;
Stack testStack = _candidate;
auto swap = [&](unsigned _swapDepth) { ++numOps; if (_swapDepth > 16) numOps += 1000; };
auto dupOrPush = [&](StackSlot const& _slot)
{
if (canBeFreelyGenerated(_slot))
return;
auto depth = util::findOffset(ranges::concat_view(commonPrefix, testStack) | ranges::views::reverse, _slot);
if (depth && *depth >= 16)
numOps += 1000;
};
createStackLayout(testStack, stack1Tail, swap, dupOrPush, [&](){});
testStack = _candidate;
createStackLayout(testStack, stack2Tail, swap, dupOrPush, [&](){});
return numOps;
};
// See https://en.wikipedia.org/wiki/Heap's_algorithm
size_t n = candidate.size();
Stack bestCandidate = candidate;
size_t bestCost = evaluate(candidate);
std::vector<size_t> c(n, 0);
size_t i = 1;
while (i < n)
{
if (c[i] < i)
{
if (i & 1)
std::swap(candidate.front(), candidate[i]);
else
std::swap(candidate[c[i]], candidate[i]);
size_t cost = evaluate(candidate);
if (cost < bestCost)
{
bestCost = cost;
bestCandidate = candidate;
}
++c[i];
// Note that for a proper implementation of the Heap algorithm this would need to revert back to ``i = 1.``
// However, the incorrect implementation produces decent result and the proper version would have n!
// complexity and is thereby not feasible.
++i;
}
else
{
c[i] = 0;
++i;
}
}
return commonPrefix + bestCandidate;
}
std::vector<StackLayoutGenerator::StackTooDeep> StackLayoutGenerator::reportStackTooDeep(CFG::BasicBlock const& _entry) const
{
std::vector<StackTooDeep> stackTooDeepErrors;
util::BreadthFirstSearch<CFG::BasicBlock const*> breadthFirstSearch{{&_entry}};
breadthFirstSearch.run([&](CFG::BasicBlock const* _block, auto _addChild) {
Stack currentStack = m_layout.blockInfos.at(_block).entryLayout;
for (auto const& operation: _block->operations)
{
Stack& operationEntry = m_layout.operationEntryLayout.at(&operation);
stackTooDeepErrors += findStackTooDeep(currentStack, operationEntry);
currentStack = operationEntry;
for (size_t i = 0; i < operation.input.size(); i++)
currentStack.pop_back();
currentStack += operation.output;
}
// Do not attempt to create the exit layout m_layout.blockInfos.at(_block).exitLayout here,
// since the code generator will directly move to the target entry layout.
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) {},
[&](CFG::BasicBlock::Jump const& _jump)
{
Stack const& targetLayout = m_layout.blockInfos.at(_jump.target).entryLayout;
stackTooDeepErrors += findStackTooDeep(currentStack, targetLayout);
if (!_jump.backwards)
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
for (Stack const& targetLayout: {
m_layout.blockInfos.at(_conditionalJump.zero).entryLayout,
m_layout.blockInfos.at(_conditionalJump.nonZero).entryLayout
})
stackTooDeepErrors += findStackTooDeep(currentStack, targetLayout);
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) {},
[&](CFG::BasicBlock::Terminated const&) {},
}, _block->exit);
});
return stackTooDeepErrors;
}
Stack StackLayoutGenerator::compressStack(Stack _stack)
{
std::optional<size_t> firstDupOffset;
do
{
if (firstDupOffset)
{
std::swap(_stack.at(*firstDupOffset), _stack.back());
_stack.pop_back();
firstDupOffset.reset();
}
for (auto&& [depth, slot]: _stack | ranges::views::reverse | ranges::views::enumerate)
if (canBeFreelyGenerated(slot))
{
firstDupOffset = _stack.size() - depth - 1;
break;
}
else if (auto dupDepth = util::findOffset(_stack | ranges::views::reverse | ranges::views::drop(depth + 1), slot))
if (depth + *dupDepth <= 16)
{
firstDupOffset = _stack.size() - depth - 1;
break;
}
}
while (firstDupOffset);
return _stack;
}
void StackLayoutGenerator::fillInJunk(CFG::BasicBlock const& _block, CFG::FunctionInfo const* _functionInfo)
{
/// Recursively adds junk to the subgraph starting on @a _entry.
/// Since it is only called on cut-vertices, the full subgraph retains proper stack balance.
auto addJunkRecursive = [&](CFG::BasicBlock const* _entry, size_t _numJunk) {
util::BreadthFirstSearch<CFG::BasicBlock const*> breadthFirstSearch{{_entry}};
breadthFirstSearch.run([&](CFG::BasicBlock const* _block, auto _addChild) {
auto& blockInfo = m_layout.blockInfos.at(_block);
blockInfo.entryLayout = Stack{_numJunk, JunkSlot{}} + std::move(blockInfo.entryLayout);
for (auto const& operation: _block->operations)
{
auto& operationEntryLayout = m_layout.operationEntryLayout.at(&operation);
operationEntryLayout = Stack{_numJunk, JunkSlot{}} + std::move(operationEntryLayout);
}
blockInfo.exitLayout = Stack{_numJunk, JunkSlot{}} + std::move(blockInfo.exitLayout);
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) {},
[&](CFG::BasicBlock::Jump const& _jump)
{
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) { yulAssert(false); },
[&](CFG::BasicBlock::Terminated const&) {},
}, _block->exit);
});
};
/// @returns the number of operations required to transform @a _source to @a _target.
auto evaluateTransform = [&](Stack _source, Stack const& _target) -> size_t {
size_t opGas = 0;
auto swap = [&](unsigned _swapDepth)
{
if (_swapDepth > 16)
opGas += 1000;
else
opGas += evmasm::GasMeter::runGas(evmasm::swapInstruction(_swapDepth), langutil::EVMVersion());
};
auto dupOrPush = [&](StackSlot const& _slot)
{
if (canBeFreelyGenerated(_slot))
opGas += evmasm::GasMeter::runGas(evmasm::pushInstruction(32), langutil::EVMVersion());
else
{
if (auto depth = util::findOffset(_source | ranges::views::reverse, _slot))
{
if (*depth < 16)
opGas += evmasm::GasMeter::runGas(evmasm::dupInstruction(static_cast<unsigned>(*depth + 1)), langutil::EVMVersion());
else
opGas += 1000;
}
else
{
// This has to be a previously unassigned return variable.
// We at least sanity-check that it is among the return variables at all.
yulAssert(m_currentFunctionInfo && std::holds_alternative<VariableSlot>(_slot));
yulAssert(util::contains(m_currentFunctionInfo->returnVariables, std::get<VariableSlot>(_slot)));
// Strictly speaking the cost of the PUSH0 depends on the targeted EVM version, but the difference
// will not matter here.
opGas += evmasm::GasMeter::pushGas(u256(0), langutil::EVMVersion());
}
}
};
auto pop = [&]() { opGas += evmasm::GasMeter::runGas(evmasm::Instruction::POP,langutil::EVMVersion()); };
createStackLayout(_source, _target, swap, dupOrPush, pop);
return opGas;
};
/// @returns the number of junk slots to be prepended to @a _targetLayout for an optimal transition from
/// @a _entryLayout to @a _targetLayout.
auto getBestNumJunk = [&](Stack const& _entryLayout, Stack const& _targetLayout) -> size_t {
size_t bestCost = evaluateTransform(_entryLayout, _targetLayout);
size_t bestNumJunk = 0;
size_t maxJunk = _entryLayout.size();
for (size_t numJunk = 1; numJunk <= maxJunk; ++numJunk)
{
size_t cost = evaluateTransform(_entryLayout, Stack{numJunk, JunkSlot{}} + _targetLayout);
if (cost < bestCost)
{
bestCost = cost;
bestNumJunk = numJunk;
}
}
return bestNumJunk;
};
if (_functionInfo && !_functionInfo->canContinue && _block.allowsJunk())
{
size_t bestNumJunk = getBestNumJunk(
_functionInfo->parameters | ranges::views::reverse | ranges::to<Stack>,
m_layout.blockInfos.at(&_block).entryLayout
);
if (bestNumJunk > 0)
addJunkRecursive(&_block, bestNumJunk);
}
/// Traverses the CFG and at each block that allows junk, i.e. that is a cut-vertex that never leads to a function
/// return, checks if adding junk reduces the shuffling cost upon entering and if so recursively adds junk
/// to the spanned subgraph.
util::BreadthFirstSearch<CFG::BasicBlock const*>{{&_block}}.run([&](CFG::BasicBlock const* _block, auto _addChild) {
if (_block->allowsJunk())
{
auto& blockInfo = m_layout.blockInfos.at(_block);
Stack entryLayout = blockInfo.entryLayout;
Stack const& nextLayout = _block->operations.empty() ? blockInfo.exitLayout : m_layout.operationEntryLayout.at(&_block->operations.front());
if (entryLayout != nextLayout)
{
size_t bestNumJunk = getBestNumJunk(
entryLayout,
nextLayout
);
if (bestNumJunk > 0)
{
addJunkRecursive(_block, bestNumJunk);
blockInfo.entryLayout = entryLayout;
}
}
}
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) {},
[&](CFG::BasicBlock::Jump const& _jump)
{
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) {},
[&](CFG::BasicBlock::Terminated const&) {},
}, _block->exit);
});
}
| 32,290
|
C++
|
.cpp
| 778
| 38.03856
| 149
| 0.719651
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,080
|
EVMMetrics.cpp
|
ethereum_solidity/libyul/backends/evm/EVMMetrics.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Module providing metrics for the EVM optimizer.
*/
#include <libyul/backends/evm/EVMMetrics.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libevmasm/Instruction.h>
#include <libevmasm/GasMeter.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
bigint GasMeter::costs(Expression const& _expression) const
{
return combineCosts(GasMeterVisitor::costs(_expression, m_dialect, m_isCreation));
}
bigint GasMeter::instructionCosts(evmasm::Instruction _instruction) const
{
return combineCosts(GasMeterVisitor::instructionCosts(_instruction, m_dialect, m_isCreation));
}
bigint GasMeter::combineCosts(std::pair<bigint, bigint> _costs) const
{
return _costs.first * m_runs + _costs.second;
}
std::pair<bigint, bigint> GasMeterVisitor::costs(
Expression const& _expression,
EVMDialect const& _dialect,
bool _isCreation
)
{
GasMeterVisitor gmv(_dialect, _isCreation);
gmv.visit(_expression);
return {gmv.m_runGas, gmv.m_dataGas};
}
std::pair<bigint, bigint> GasMeterVisitor::instructionCosts(
evmasm::Instruction _instruction,
EVMDialect const& _dialect,
bool _isCreation
)
{
GasMeterVisitor gmv(_dialect, _isCreation);
gmv.instructionCostsInternal(_instruction);
return {gmv.m_runGas, gmv.m_dataGas};
}
void GasMeterVisitor::operator()(FunctionCall const& _funCall)
{
ASTWalker::operator()(_funCall);
if (std::optional<BuiltinHandle> handle = m_dialect.findBuiltin(_funCall.functionName.name.str()))
if (std::optional<evmasm::Instruction> const& instruction = m_dialect.builtin(*handle).instruction)
{
instructionCostsInternal(*instruction);
return;
}
yulAssert(false, "Functions not implemented.");
}
void GasMeterVisitor::operator()(Literal const& _lit)
{
m_runGas += evmasm::GasMeter::pushGas(_lit.value.value(), m_dialect.evmVersion());
m_dataGas += singleByteDataGas();
if (!m_dialect.evmVersion().hasPush0() || _lit.value.value() != u256(0))
m_dataGas += evmasm::GasMeter::dataGas(
toCompactBigEndian(_lit.value.value(), 1),
m_isCreation,
m_dialect.evmVersion()
);
}
void GasMeterVisitor::operator()(Identifier const&)
{
m_runGas += evmasm::GasMeter::runGas(evmasm::Instruction::DUP1, m_dialect.evmVersion());
m_dataGas += singleByteDataGas();
}
bigint GasMeterVisitor::singleByteDataGas() const
{
if (m_isCreation)
return evmasm::GasCosts::txDataNonZeroGas(m_dialect.evmVersion());
else
return evmasm::GasCosts::createDataGas;
}
void GasMeterVisitor::instructionCostsInternal(evmasm::Instruction _instruction)
{
if (_instruction == evmasm::Instruction::EXP)
m_runGas += evmasm::GasCosts::expGas + evmasm::GasCosts::expByteGas(m_dialect.evmVersion());
else if (_instruction == evmasm::Instruction::KECCAK256)
// Assumes that Keccak-256 is computed on a single word (rounded up).
m_runGas += evmasm::GasCosts::keccak256Gas + evmasm::GasCosts::keccak256WordGas;
else
m_runGas += evmasm::GasMeter::runGas(_instruction, m_dialect.evmVersion());
m_dataGas += singleByteDataGas();
}
| 3,819
|
C++
|
.cpp
| 105
| 34.447619
| 101
| 0.774228
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,081
|
ControlFlow.cpp
|
ethereum_solidity/libyul/backends/evm/ControlFlow.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/backends/evm/ControlFlow.h>
#include <range/v3/range/conversion.hpp>
using namespace solidity::yul;
ControlFlowLiveness::ControlFlowLiveness(ControlFlow const& _controlFlow):
controlFlow(_controlFlow),
mainLiveness(std::make_unique<SSACFGLiveness>(*_controlFlow.mainGraph)),
functionLiveness(_controlFlow.functionGraphs | ranges::views::transform([](auto const& _cfg) { return std::make_unique<SSACFGLiveness>(*_cfg); }) | ranges::to<std::vector>)
{ }
| 1,160
|
C++
|
.cpp
| 22
| 50.818182
| 173
| 0.787986
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,082
|
OptimizedEVMCodeTransform.cpp
|
ethereum_solidity/libyul/backends/evm/OptimizedEVMCodeTransform.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/backends/evm/OptimizedEVMCodeTransform.h>
#include <libyul/backends/evm/ControlFlowGraphBuilder.h>
#include <libyul/backends/evm/StackHelpers.h>
#include <libyul/backends/evm/StackLayoutGenerator.h>
#include <libyul/Utilities.h>
#include <libevmasm/Instruction.h>
#include <libsolutil/Visitor.h>
#include <libsolutil/cxx20.h>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/take_last.hpp>
using namespace solidity;
using namespace solidity::yul;
std::vector<StackTooDeepError> OptimizedEVMCodeTransform::run(
AbstractAssembly& _assembly,
AsmAnalysisInfo& _analysisInfo,
Block const& _block,
EVMDialect const& _dialect,
BuiltinContext& _builtinContext,
UseNamedLabels _useNamedLabelsForFunctions
)
{
std::unique_ptr<CFG> dfg = ControlFlowGraphBuilder::build(_analysisInfo, _dialect, _block);
StackLayout stackLayout = StackLayoutGenerator::run(*dfg);
OptimizedEVMCodeTransform optimizedCodeTransform(
_assembly,
_builtinContext,
_useNamedLabelsForFunctions,
*dfg,
stackLayout
);
// Create initial entry layout.
optimizedCodeTransform.createStackLayout(debugDataOf(*dfg->entry), stackLayout.blockInfos.at(dfg->entry).entryLayout);
optimizedCodeTransform(*dfg->entry);
for (Scope::Function const* function: dfg->functions)
optimizedCodeTransform(dfg->functionInfo.at(function));
return std::move(optimizedCodeTransform.m_stackErrors);
}
void OptimizedEVMCodeTransform::operator()(CFG::FunctionCall const& _call)
{
// Validate stack.
{
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
yulAssert(m_stack.size() >= _call.function.get().numArguments + (_call.canContinue ? 1 : 0), "");
// Assert that we got the correct arguments on stack for the call.
for (auto&& [arg, slot]: ranges::zip_view(
_call.functionCall.get().arguments | ranges::views::reverse,
m_stack | ranges::views::take_last(_call.functionCall.get().arguments.size())
))
validateSlot(slot, arg);
// Assert that we got the correct return label on stack.
if (_call.canContinue)
{
auto const* returnLabelSlot = std::get_if<FunctionCallReturnLabelSlot>(
&m_stack.at(m_stack.size() - _call.functionCall.get().arguments.size() - 1)
);
yulAssert(returnLabelSlot && &returnLabelSlot->call.get() == &_call.functionCall.get(), "");
}
}
// Emit code.
{
m_assembly.setSourceLocation(originLocationOf(_call));
m_assembly.appendJumpTo(
getFunctionLabel(_call.function),
static_cast<int>(_call.function.get().numReturns) - static_cast<int>(_call.function.get().numArguments) - (_call.canContinue ? 1 : 0),
AbstractAssembly::JumpType::IntoFunction
);
if (_call.canContinue)
m_assembly.appendLabel(m_returnLabels.at(&_call.functionCall.get()));
}
// Update stack.
{
// Remove arguments and return label from m_stack.
for (size_t i = 0; i < _call.function.get().numArguments + (_call.canContinue ? 1 : 0); ++i)
m_stack.pop_back();
// Push return values to m_stack.
for (size_t index: ranges::views::iota(0u, _call.function.get().numReturns))
m_stack.emplace_back(TemporarySlot{_call.functionCall, index});
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
}
}
void OptimizedEVMCodeTransform::operator()(CFG::BuiltinCall const& _call)
{
// Validate stack.
{
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
yulAssert(m_stack.size() >= _call.arguments, "");
// Assert that we got a correct stack for the call.
for (auto&& [arg, slot]: ranges::zip_view(
_call.functionCall.get().arguments |
ranges::views::enumerate |
ranges::views::filter(util::mapTuple([&](size_t idx, auto&) -> bool {
return !_call.builtin.get().literalArgument(idx);
})) |
ranges::views::reverse |
ranges::views::values,
m_stack | ranges::views::take_last(_call.arguments)
))
validateSlot(slot, arg);
}
// Emit code.
{
m_assembly.setSourceLocation(originLocationOf(_call));
static_cast<BuiltinFunctionForEVM const&>(_call.builtin.get()).generateCode(
_call.functionCall,
m_assembly,
m_builtinContext
);
}
// Update stack.
{
// Remove arguments from m_stack.
for (size_t i = 0; i < _call.arguments; ++i)
m_stack.pop_back();
// Push return values to m_stack.
for (size_t index: ranges::views::iota(0u, _call.builtin.get().numReturns))
m_stack.emplace_back(TemporarySlot{_call.functionCall, index});
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
}
}
void OptimizedEVMCodeTransform::operator()(CFG::Assignment const& _assignment)
{
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
// Invalidate occurrences of the assigned variables.
for (auto& currentSlot: m_stack)
if (VariableSlot const* varSlot = std::get_if<VariableSlot>(¤tSlot))
if (util::contains(_assignment.variables, *varSlot))
currentSlot = JunkSlot{};
// Assign variables to current stack top.
yulAssert(m_stack.size() >= _assignment.variables.size(), "");
for (auto&& [currentSlot, varSlot]: ranges::zip_view(
m_stack | ranges::views::take_last(_assignment.variables.size()),
_assignment.variables
))
currentSlot = varSlot;
}
OptimizedEVMCodeTransform::OptimizedEVMCodeTransform(
AbstractAssembly& _assembly,
BuiltinContext& _builtinContext,
UseNamedLabels _useNamedLabelsForFunctions,
CFG const& _dfg,
StackLayout const& _stackLayout
):
m_assembly(_assembly),
m_builtinContext(_builtinContext),
m_dfg(_dfg),
m_stackLayout(_stackLayout),
m_functionLabels([&](){
std::map<CFG::FunctionInfo const*, AbstractAssembly::LabelID> functionLabels;
std::set<YulName> assignedFunctionNames;
for (Scope::Function const* function: m_dfg.functions)
{
CFG::FunctionInfo const& functionInfo = m_dfg.functionInfo.at(function);
bool nameAlreadySeen = !assignedFunctionNames.insert(function->name).second;
if (_useNamedLabelsForFunctions == UseNamedLabels::YesAndForceUnique)
yulAssert(!nameAlreadySeen);
bool useNamedLabel = _useNamedLabelsForFunctions != UseNamedLabels::Never && !nameAlreadySeen;
functionLabels[&functionInfo] = useNamedLabel ?
m_assembly.namedLabel(
function->name.str(),
function->numArguments,
function->numReturns,
functionInfo.debugData ? functionInfo.debugData->astID : std::nullopt
) :
m_assembly.newLabelId();
}
return functionLabels;
}())
{
}
void OptimizedEVMCodeTransform::assertLayoutCompatibility(Stack const& _currentStack, Stack const& _desiredStack)
{
yulAssert(_currentStack.size() == _desiredStack.size(), "");
for (auto&& [currentSlot, desiredSlot]: ranges::zip_view(_currentStack, _desiredStack))
yulAssert(std::holds_alternative<JunkSlot>(desiredSlot) || currentSlot == desiredSlot, "");
}
AbstractAssembly::LabelID OptimizedEVMCodeTransform::getFunctionLabel(Scope::Function const& _function)
{
return m_functionLabels.at(&m_dfg.functionInfo.at(&_function));
}
void OptimizedEVMCodeTransform::validateSlot(StackSlot const& _slot, Expression const& _expression)
{
std::visit(util::GenericVisitor{
[&](yul::Literal const& _literal) {
auto* literalSlot = std::get_if<LiteralSlot>(&_slot);
yulAssert(literalSlot && _literal.value.value() == literalSlot->value, "");
},
[&](yul::Identifier const& _identifier) {
auto* variableSlot = std::get_if<VariableSlot>(&_slot);
yulAssert(variableSlot && variableSlot->variable.get().name == _identifier.name, "");
},
[&](yul::FunctionCall const& _call) {
auto* temporarySlot = std::get_if<TemporarySlot>(&_slot);
yulAssert(temporarySlot && &temporarySlot->call.get() == &_call && temporarySlot->index == 0, "");
}
}, _expression);
}
void OptimizedEVMCodeTransform::createStackLayout(langutil::DebugData::ConstPtr _debugData, Stack _targetStack)
{
static constexpr auto slotVariableName = [](StackSlot const& _slot) {
return std::visit(util::GenericVisitor{
[](VariableSlot const& _var) { return _var.variable.get().name; },
[](auto const&) { return YulName{}; }
}, _slot);
};
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
// ::createStackLayout asserts that it has successfully achieved the target layout.
langutil::SourceLocation sourceLocation = _debugData ? _debugData->originLocation : langutil::SourceLocation{};
m_assembly.setSourceLocation(sourceLocation);
::createStackLayout(
m_stack,
_targetStack | ranges::to<Stack>,
// Swap callback.
[&](unsigned _i)
{
yulAssert(static_cast<int>(m_stack.size()) == m_assembly.stackHeight(), "");
yulAssert(_i > 0 && _i < m_stack.size(), "");
if (_i <= 16)
m_assembly.appendInstruction(evmasm::swapInstruction(_i));
else
{
int deficit = static_cast<int>(_i) - 16;
StackSlot const& deepSlot = m_stack.at(m_stack.size() - _i - 1);
YulName varNameDeep = slotVariableName(deepSlot);
YulName varNameTop = slotVariableName(m_stack.back());
std::string msg =
"Cannot swap " + (varNameDeep.empty() ? "Slot " + stackSlotToString(deepSlot) : "Variable " + varNameDeep.str()) +
" with " + (varNameTop.empty() ? "Slot " + stackSlotToString(m_stack.back()) : "Variable " + varNameTop.str()) +
": too deep in the stack by " + std::to_string(deficit) + " slots in " + stackToString(m_stack);
m_stackErrors.emplace_back(StackTooDeepError(
m_currentFunctionInfo ? m_currentFunctionInfo->function.name : YulName{},
varNameDeep.empty() ? varNameTop : varNameDeep,
deficit,
msg
) << langutil::errinfo_sourceLocation(sourceLocation));
m_assembly.markAsInvalid();
}
},
// Push or dup callback.
[&](StackSlot const& _slot)
{
yulAssert(static_cast<int>(m_stack.size()) == m_assembly.stackHeight(), "");
// Dup the slot, if already on stack and reachable.
if (auto depth = util::findOffset(m_stack | ranges::views::reverse, _slot))
{
if (*depth < 16)
{
m_assembly.appendInstruction(evmasm::dupInstruction(static_cast<unsigned>(*depth + 1)));
return;
}
else if (!canBeFreelyGenerated(_slot))
{
int deficit = static_cast<int>(*depth - 15);
YulName varName = slotVariableName(_slot);
std::string msg =
(varName.empty() ? "Slot " + stackSlotToString(_slot) : "Variable " + varName.str())
+ " is " + std::to_string(*depth - 15) + " too deep in the stack " + stackToString(m_stack);
m_stackErrors.emplace_back(StackTooDeepError(
m_currentFunctionInfo ? m_currentFunctionInfo->function.name : YulName{},
varName,
deficit,
msg
));
m_assembly.markAsInvalid();
m_assembly.appendConstant(u256(0xCAFFEE));
return;
}
// else: the slot is too deep in stack, but can be freely generated, we fall through to push it again.
}
// The slot can be freely generated or is an unassigned return variable. Push it.
std::visit(util::GenericVisitor{
[&](LiteralSlot const& _literal)
{
m_assembly.setSourceLocation(originLocationOf(_literal));
m_assembly.appendConstant(_literal.value);
m_assembly.setSourceLocation(sourceLocation);
},
[&](FunctionReturnLabelSlot const&)
{
yulAssert(false, "Cannot produce function return label.");
},
[&](FunctionCallReturnLabelSlot const& _returnLabel)
{
if (!m_returnLabels.count(&_returnLabel.call.get()))
m_returnLabels[&_returnLabel.call.get()] = m_assembly.newLabelId();
m_assembly.setSourceLocation(originLocationOf(_returnLabel.call.get()));
m_assembly.appendLabelReference(m_returnLabels.at(&_returnLabel.call.get()));
m_assembly.setSourceLocation(sourceLocation);
},
[&](VariableSlot const& _variable)
{
if (m_currentFunctionInfo && util::contains(m_currentFunctionInfo->returnVariables, _variable))
{
m_assembly.setSourceLocation(originLocationOf(_variable));
m_assembly.appendConstant(0);
m_assembly.setSourceLocation(sourceLocation);
return;
}
yulAssert(false, "Variable not found on stack.");
},
[&](TemporarySlot const&)
{
yulAssert(false, "Function call result requested, but not found on stack.");
},
[&](JunkSlot const&)
{
// Note: this will always be popped, so we can push anything.
if (m_assembly.evmVersion().hasPush0())
m_assembly.appendConstant(0);
else
m_assembly.appendInstruction(evmasm::Instruction::CODESIZE);
}
}, _slot);
},
// Pop callback.
[&]()
{
m_assembly.appendInstruction(evmasm::Instruction::POP);
}
);
yulAssert(m_assembly.stackHeight() == static_cast<int>(m_stack.size()), "");
}
void OptimizedEVMCodeTransform::operator()(CFG::BasicBlock const& _block)
{
// Assert that this is the first visit of the block and mark as generated.
yulAssert(m_generated.insert(&_block).second, "");
m_assembly.setSourceLocation(originLocationOf(_block));
auto const& blockInfo = m_stackLayout.blockInfos.at(&_block);
// Assert that the stack is valid for entering the block.
assertLayoutCompatibility(m_stack, blockInfo.entryLayout);
m_stack = blockInfo.entryLayout; // Might set some slots to junk, if not required by the block.
yulAssert(static_cast<int>(m_stack.size()) == m_assembly.stackHeight(), "");
// Emit jump label, if required.
if (auto label = util::valueOrNullptr(m_blockLabels, &_block))
m_assembly.appendLabel(*label);
for (auto const& operation: _block.operations)
{
// Create required layout for entering the operation.
createStackLayout(debugDataOf(operation.operation), m_stackLayout.operationEntryLayout.at(&operation));
// Assert that we have the inputs of the operation on stack top.
yulAssert(static_cast<int>(m_stack.size()) == m_assembly.stackHeight(), "");
yulAssert(m_stack.size() >= operation.input.size(), "");
size_t baseHeight = m_stack.size() - operation.input.size();
assertLayoutCompatibility(
m_stack | ranges::views::take_last(operation.input.size()) | ranges::to<Stack>,
operation.input
);
// Perform the operation.
std::visit(*this, operation.operation);
// Assert that the operation produced its proclaimed output.
yulAssert(static_cast<int>(m_stack.size()) == m_assembly.stackHeight(), "");
yulAssert(m_stack.size() == baseHeight + operation.output.size(), "");
yulAssert(m_stack.size() >= operation.output.size(), "");
assertLayoutCompatibility(
m_stack | ranges::views::take_last(operation.output.size()) | ranges::to<Stack>,
operation.output
);
}
// Exit the block.
m_assembly.setSourceLocation(originLocationOf(_block));
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&)
{
m_assembly.appendInstruction(evmasm::Instruction::STOP);
},
[&](CFG::BasicBlock::Jump const& _jump)
{
// Create the stack expected at the jump target.
createStackLayout(debugDataOf(_jump), m_stackLayout.blockInfos.at(_jump.target).entryLayout);
// If this is the only jump to the block, we do not need a label and can directly continue with the target block.
if (!m_blockLabels.count(_jump.target) && _jump.target->entries.size() == 1)
{
yulAssert(!_jump.backwards, "");
(*this)(*_jump.target);
}
else
{
// Generate a jump label for the target, if not already present.
if (!m_blockLabels.count(_jump.target))
m_blockLabels[_jump.target] = m_assembly.newLabelId();
// If we already have generated the target block, jump to it, otherwise generate it in place.
if (m_generated.count(_jump.target))
m_assembly.appendJumpTo(m_blockLabels[_jump.target]);
else
(*this)(*_jump.target);
}
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
// Create the shared entry layout of the jump targets, which is stored as exit layout of the current block.
createStackLayout(debugDataOf(_conditionalJump), blockInfo.exitLayout);
// Create labels for the targets, if not already present.
if (!m_blockLabels.count(_conditionalJump.nonZero))
m_blockLabels[_conditionalJump.nonZero] = m_assembly.newLabelId();
if (!m_blockLabels.count(_conditionalJump.zero))
m_blockLabels[_conditionalJump.zero] = m_assembly.newLabelId();
// Assert that we have the correct condition on stack.
yulAssert(!m_stack.empty(), "");
yulAssert(m_stack.back() == _conditionalJump.condition, "");
// Emit the conditional jump to the non-zero label and update the stored stack.
m_assembly.appendJumpToIf(m_blockLabels[_conditionalJump.nonZero]);
m_stack.pop_back();
// Assert that we have a valid stack for both jump targets.
assertLayoutCompatibility(m_stack, m_stackLayout.blockInfos.at(_conditionalJump.nonZero).entryLayout);
assertLayoutCompatibility(m_stack, m_stackLayout.blockInfos.at(_conditionalJump.zero).entryLayout);
{
// Restore the stack afterwards for the non-zero case below.
ScopeGuard stackRestore([storedStack = m_stack, this]() {
m_stack = std::move(storedStack);
m_assembly.setStackHeight(static_cast<int>(m_stack.size()));
});
// If we have already generated the zero case, jump to it, otherwise generate it in place.
if (m_generated.count(_conditionalJump.zero))
m_assembly.appendJumpTo(m_blockLabels[_conditionalJump.zero]);
else
(*this)(*_conditionalJump.zero);
}
// Note that each block visit terminates control flow, so we cannot fall through from the zero case.
// Generate the non-zero block, if not done already.
if (!m_generated.count(_conditionalJump.nonZero))
(*this)(*_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const& _functionReturn)
{
yulAssert(m_currentFunctionInfo);
yulAssert(m_currentFunctionInfo == _functionReturn.info);
yulAssert(m_currentFunctionInfo->canContinue);
// Construct the function return layout, which is fully determined by the function signature.
Stack exitStack = m_currentFunctionInfo->returnVariables | ranges::views::transform([](auto const& _varSlot){
return StackSlot{_varSlot};
}) | ranges::to<Stack>;
exitStack.emplace_back(FunctionReturnLabelSlot{_functionReturn.info->function});
// Create the function return layout and jump.
createStackLayout(debugDataOf(_functionReturn), exitStack);
m_assembly.appendJump(0, AbstractAssembly::JumpType::OutOfFunction);
},
[&](CFG::BasicBlock::Terminated const&)
{
yulAssert(!_block.operations.empty());
if (CFG::BuiltinCall const* builtinCall = std::get_if<CFG::BuiltinCall>(&_block.operations.back().operation))
yulAssert(builtinCall->builtin.get().controlFlowSideEffects.terminatesOrReverts(), "");
else if (CFG::FunctionCall const* functionCall = std::get_if<CFG::FunctionCall>(&_block.operations.back().operation))
yulAssert(!functionCall->canContinue);
else
yulAssert(false);
}
}, _block.exit);
// TODO: We could assert that the last emitted assembly item terminated or was an (unconditional) jump.
// But currently AbstractAssembly does not allow peeking at the last emitted assembly item.
m_stack.clear();
m_assembly.setStackHeight(0);
}
void OptimizedEVMCodeTransform::operator()(CFG::FunctionInfo const& _functionInfo)
{
yulAssert(!m_currentFunctionInfo, "");
ScopedSaveAndRestore currentFunctionInfoRestore(m_currentFunctionInfo, &_functionInfo);
yulAssert(m_stack.empty() && m_assembly.stackHeight() == 0, "");
// Create function entry layout in m_stack.
if (_functionInfo.canContinue)
m_stack.emplace_back(FunctionReturnLabelSlot{_functionInfo.function});
for (auto const& param: _functionInfo.parameters | ranges::views::reverse)
m_stack.emplace_back(param);
m_assembly.setStackHeight(static_cast<int>(m_stack.size()));
m_assembly.setSourceLocation(originLocationOf(_functionInfo));
m_assembly.appendLabel(getFunctionLabel(_functionInfo.function));
// Create the entry layout of the function body block and visit.
createStackLayout(debugDataOf(_functionInfo), m_stackLayout.blockInfos.at(_functionInfo.entry).entryLayout);
(*this)(*_functionInfo.entry);
m_stack.clear();
m_assembly.setStackHeight(0);
}
| 20,909
|
C++
|
.cpp
| 489
| 39.269939
| 137
| 0.725536
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,083
|
EVMObjectCompiler.cpp
|
ethereum_solidity/libyul/backends/evm/EVMObjectCompiler.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Compiler that transforms Yul Objects to EVM bytecode objects.
*/
#include <libyul/backends/evm/EVMObjectCompiler.h>
#include <libyul/backends/evm/EVMCodeTransform.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/OptimizedEVMCodeTransform.h>
#include <libyul/optimiser/FunctionCallFinder.h>
#include <libyul/Object.h>
#include <libyul/Exceptions.h>
#include <boost/algorithm/string.hpp>
using namespace solidity::yul;
void EVMObjectCompiler::compile(
Object const& _object,
AbstractAssembly& _assembly,
EVMDialect const& _dialect,
bool _optimize,
std::optional<uint8_t> _eofVersion
)
{
EVMObjectCompiler compiler(_assembly, _dialect, _eofVersion);
compiler.run(_object, _optimize);
}
void EVMObjectCompiler::run(Object const& _object, bool _optimize)
{
BuiltinContext context;
context.currentObject = &_object;
for (auto const& subNode: _object.subObjects)
if (auto* subObject = dynamic_cast<Object*>(subNode.get()))
{
bool isCreation = !boost::ends_with(subObject->name, "_deployed");
auto subAssemblyAndID = m_assembly.createSubAssembly(isCreation, subObject->name);
context.subIDs[subObject->name] = subAssemblyAndID.second;
subObject->subId = subAssemblyAndID.second;
compile(*subObject, *subAssemblyAndID.first, m_dialect, _optimize, m_eofVersion);
}
else
{
Data const& data = dynamic_cast<Data const&>(*subNode);
// Special handling of metadata.
if (data.name == Object::metadataName())
m_assembly.appendToAuxiliaryData(data.data);
else
context.subIDs[data.name] = m_assembly.appendData(data.data);
}
yulAssert(_object.analysisInfo, "No analysis info.");
yulAssert(_object.hasCode(), "No code.");
if (m_eofVersion.has_value())
yulAssert(
_optimize && (m_dialect.evmVersion() >= langutil::EVMVersion::prague()),
"Experimental EOF support is only available for optimized via-IR compilation and the most recent EVM version."
);
if (_optimize && m_dialect.evmVersion().canOverchargeGasForCall())
{
auto stackErrors = OptimizedEVMCodeTransform::run(
m_assembly,
*_object.analysisInfo,
_object.code()->root(),
m_dialect,
context,
OptimizedEVMCodeTransform::UseNamedLabels::ForFirstFunctionOfEachName
);
if (!stackErrors.empty())
{
std::vector<FunctionCall const*> memoryGuardCalls = findFunctionCalls(
_object.code()->root(),
"memoryguard"_yulname
);
auto stackError = stackErrors.front();
std::string msg = stackError.comment() ? *stackError.comment() : "";
if (memoryGuardCalls.empty())
msg += "\nNo memoryguard was present. "
"Consider using memory-safe assembly only and annotating it via "
"'assembly (\"memory-safe\") { ... }'.";
else
msg += "\nmemoryguard was present.";
stackError << util::errinfo_comment(msg);
BOOST_THROW_EXCEPTION(stackError);
}
}
else
{
// We do not catch and re-throw the stack too deep exception here because it is a YulException,
// which should be native to this part of the code.
CodeTransform transform{
m_assembly,
*_object.analysisInfo,
_object.code()->root(),
m_dialect,
context,
_optimize,
{},
CodeTransform::UseNamedLabels::ForFirstFunctionOfEachName
};
transform(_object.code()->root());
if (!transform.stackErrors().empty())
BOOST_THROW_EXCEPTION(transform.stackErrors().front());
}
}
| 4,051
|
C++
|
.cpp
| 113
| 32.902655
| 113
| 0.744139
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,084
|
ControlFlowGraphBuilder.cpp
|
ethereum_solidity/libyul/backends/evm/ControlFlowGraphBuilder.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Transformation of a Yul AST into a control flow graph.
*/
#include <libyul/backends/evm/ControlFlowGraphBuilder.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libsolutil/cxx20.h>
#include <libsolutil/Visitor.h>
#include <libsolutil/Algorithms.h>
#include <range/v3/action/push_back.hpp>
#include <range/v3/action/erase.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/concat.hpp>
#include <range/v3/view/drop_last.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/single.hpp>
#include <range/v3/view/take_last.hpp>
#include <range/v3/view/transform.hpp>
using namespace solidity;
using namespace solidity::yul;
namespace
{
/// Removes edges to blocks that are not reachable.
void cleanUnreachable(CFG& _cfg)
{
// Determine which blocks are reachable from the entry.
util::BreadthFirstSearch<CFG::BasicBlock*> reachabilityCheck{{_cfg.entry}};
for (auto const& functionInfo: _cfg.functionInfo | ranges::views::values)
reachabilityCheck.verticesToTraverse.emplace_back(functionInfo.entry);
reachabilityCheck.run([&](CFG::BasicBlock* _node, auto&& _addChild) {
visit(util::GenericVisitor{
[&](CFG::BasicBlock::Jump const& _jump) {
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _jump) {
_addChild(_jump.zero);
_addChild(_jump.nonZero);
},
[](CFG::BasicBlock::FunctionReturn const&) {},
[](CFG::BasicBlock::Terminated const&) {},
[](CFG::BasicBlock::MainExit const&) {}
}, _node->exit);
});
// Remove all entries from unreachable nodes from the graph.
for (CFG::BasicBlock* node: reachabilityCheck.visited)
cxx20::erase_if(node->entries, [&](CFG::BasicBlock* entry) -> bool {
return !reachabilityCheck.visited.count(entry);
});
}
/// Sets the ``recursive`` member to ``true`` for all recursive function calls.
void markRecursiveCalls(CFG& _cfg)
{
std::map<CFG::BasicBlock*, std::vector<CFG::FunctionCall*>> callsPerBlock;
auto const& findCalls = [&](CFG::BasicBlock* _block)
{
if (auto* calls = util::valueOrNullptr(callsPerBlock, _block))
return *calls;
std::vector<CFG::FunctionCall*>& calls = callsPerBlock[_block];
util::BreadthFirstSearch<CFG::BasicBlock*>{{_block}}.run([&](CFG::BasicBlock* _block, auto _addChild) {
for (auto& operation: _block->operations)
if (auto* functionCall = std::get_if<CFG::FunctionCall>(&operation.operation))
calls.emplace_back(functionCall);
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&) {},
[&](CFG::BasicBlock::Jump const& _jump)
{
_addChild(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
_addChild(_conditionalJump.zero);
_addChild(_conditionalJump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) {},
[&](CFG::BasicBlock::Terminated const&) {},
}, _block->exit);
});
return calls;
};
for (auto& functionInfo: _cfg.functionInfo | ranges::views::values)
for (CFG::FunctionCall* call: findCalls(functionInfo.entry))
{
util::BreadthFirstSearch<CFG::FunctionCall*> breadthFirstSearch{{call}};
breadthFirstSearch.run([&](CFG::FunctionCall* _call, auto _addChild) {
auto& calledFunctionInfo = _cfg.functionInfo.at(&_call->function.get());
if (&calledFunctionInfo == &functionInfo)
{
call->recursive = true;
breadthFirstSearch.abort();
return;
}
for (CFG::FunctionCall* nestedCall: findCalls(_cfg.functionInfo.at(&_call->function.get()).entry))
_addChild(nestedCall);
});
}
}
/// Marks each cut-vertex in the CFG, i.e. each block that begins a disconnected sub-graph of the CFG.
/// Entering such a block means that control flow will never return to a previously visited block.
void markStartsOfSubGraphs(CFG& _cfg)
{
std::vector<CFG::BasicBlock*> entries;
entries.emplace_back(_cfg.entry);
for (auto&& functionInfo: _cfg.functionInfo | ranges::views::values)
entries.emplace_back(functionInfo.entry);
for (auto& entry: entries)
{
/**
* Detect bridges following Algorithm 1 in https://arxiv.org/pdf/2108.07346.pdf
* and mark the bridge targets as starts of sub-graphs.
*/
std::set<CFG::BasicBlock*> visited;
std::map<CFG::BasicBlock*, size_t> disc;
std::map<CFG::BasicBlock*, size_t> low;
std::map<CFG::BasicBlock*, CFG::BasicBlock*> parent;
size_t time = 0;
auto dfs = [&](CFG::BasicBlock* _u, auto _recurse) -> void {
visited.insert(_u);
disc[_u] = low[_u] = time;
time++;
std::vector<CFG::BasicBlock*> children = _u->entries;
visit(util::GenericVisitor{
[&](CFG::BasicBlock::Jump const& _jump) {
children.emplace_back(_jump.target);
},
[&](CFG::BasicBlock::ConditionalJump const& _jump) {
children.emplace_back(_jump.zero);
children.emplace_back(_jump.nonZero);
},
[&](CFG::BasicBlock::FunctionReturn const&) {},
[&](CFG::BasicBlock::Terminated const&) { _u->isStartOfSubGraph = true; },
[&](CFG::BasicBlock::MainExit const&) { _u->isStartOfSubGraph = true; }
}, _u->exit);
yulAssert(!util::contains(children, _u));
for (CFG::BasicBlock* v: children)
if (!visited.count(v))
{
parent[v] = _u;
_recurse(v, _recurse);
low[_u] = std::min(low[_u], low[v]);
if (low[v] > disc[_u])
{
// _u <-> v is a cut edge in the undirected graph
bool edgeVtoU = util::contains(_u->entries, v);
bool edgeUtoV = util::contains(v->entries, _u);
if (edgeVtoU && !edgeUtoV)
// Cut edge v -> _u
_u->isStartOfSubGraph = true;
else if (edgeUtoV && !edgeVtoU)
// Cut edge _u -> v
v->isStartOfSubGraph = true;
}
}
else if (v != parent[_u])
low[_u] = std::min(low[_u], disc[v]);
};
dfs(entry, dfs);
}
}
/// Marks each block that needs to maintain a clean stack. That is each block that has an outgoing
/// path to a function return.
void markNeedsCleanStack(CFG& _cfg)
{
for (auto& functionInfo: _cfg.functionInfo | ranges::views::values)
for (CFG::BasicBlock* exit: functionInfo.exits)
util::BreadthFirstSearch<CFG::BasicBlock*>{{exit}}.run([&](CFG::BasicBlock* _block, auto _addChild) {
_block->needsCleanStack = true;
for (CFG::BasicBlock* entry: _block->entries)
_addChild(entry);
});
}
}
std::unique_ptr<CFG> ControlFlowGraphBuilder::build(
AsmAnalysisInfo const& _analysisInfo,
Dialect const& _dialect,
Block const& _block
)
{
auto result = std::make_unique<CFG>();
result->entry = &result->makeBlock(debugDataOf(_block));
ControlFlowSideEffectsCollector sideEffects(_dialect, _block);
ControlFlowGraphBuilder builder(*result, _analysisInfo, sideEffects.functionSideEffects(), _dialect);
builder.m_currentBlock = result->entry;
builder(_block);
cleanUnreachable(*result);
markRecursiveCalls(*result);
markStartsOfSubGraphs(*result);
markNeedsCleanStack(*result);
// TODO: It might be worthwhile to run some further simplifications on the graph itself here.
// E.g. if there is a jump to a node that has the jumping node as its only entry, the nodes can be fused, etc.
return result;
}
ControlFlowGraphBuilder::ControlFlowGraphBuilder(
CFG& _graph,
AsmAnalysisInfo const& _analysisInfo,
std::map<FunctionDefinition const*, ControlFlowSideEffects> const& _functionSideEffects,
Dialect const& _dialect
):
m_graph(_graph),
m_info(_analysisInfo),
m_functionSideEffects(_functionSideEffects),
m_dialect(_dialect)
{
}
StackSlot ControlFlowGraphBuilder::operator()(Literal const& _literal)
{
return LiteralSlot{_literal.value.value(), _literal.debugData};
}
StackSlot ControlFlowGraphBuilder::operator()(Identifier const& _identifier)
{
return VariableSlot{lookupVariable(_identifier.name), _identifier.debugData};
}
StackSlot ControlFlowGraphBuilder::operator()(Expression const& _expression)
{
return std::visit(*this, _expression);
}
StackSlot ControlFlowGraphBuilder::operator()(FunctionCall const& _call)
{
Stack const& output = visitFunctionCall(_call);
yulAssert(output.size() == 1, "");
return output.front();
}
void ControlFlowGraphBuilder::operator()(VariableDeclaration const& _varDecl)
{
yulAssert(m_currentBlock, "");
auto declaredVariables = _varDecl.variables | ranges::views::transform([&](NameWithDebugData const& _var) {
return VariableSlot{lookupVariable(_var.name), _var.debugData};
}) | ranges::to<std::vector<VariableSlot>>;
Stack input;
if (_varDecl.value)
input = visitAssignmentRightHandSide(*_varDecl.value, declaredVariables.size());
else
input = Stack(_varDecl.variables.size(), LiteralSlot{0, _varDecl.debugData});
m_currentBlock->operations.emplace_back(CFG::Operation{
std::move(input),
declaredVariables | ranges::to<Stack>,
CFG::Assignment{_varDecl.debugData, declaredVariables}
});
}
void ControlFlowGraphBuilder::operator()(Assignment const& _assignment)
{
auto assignedVariables = _assignment.variableNames | ranges::views::transform([&](Identifier const& _var) {
return VariableSlot{lookupVariable(_var.name), _var.debugData};
}) | ranges::to<std::vector<VariableSlot>>;
Stack input = visitAssignmentRightHandSide(*_assignment.value, assignedVariables.size());
yulAssert(m_currentBlock);
m_currentBlock->operations.emplace_back(CFG::Operation{
std::move(input),
// output
assignedVariables | ranges::to<Stack>,
// operation
CFG::Assignment{_assignment.debugData, assignedVariables}
});
}
void ControlFlowGraphBuilder::operator()(ExpressionStatement const& _exprStmt)
{
std::visit(util::GenericVisitor{
[&](FunctionCall const& _call) {
Stack const& output = visitFunctionCall(_call);
yulAssert(output.empty(), "");
},
[&](auto const&) { yulAssert(false, ""); }
}, _exprStmt.expression);
}
void ControlFlowGraphBuilder::operator()(Block const& _block)
{
ScopedSaveAndRestore saveScope(m_scope, m_info.scopes.at(&_block).get());
for (auto const& statement: _block.statements)
if (auto const* function = std::get_if<FunctionDefinition>(&statement))
registerFunction(*function);
for (auto const& statement: _block.statements)
std::visit(*this, statement);
}
void ControlFlowGraphBuilder::operator()(If const& _if)
{
auto& ifBranch = m_graph.makeBlock(debugDataOf(_if.body));
auto& afterIf = m_graph.makeBlock(debugDataOf(*m_currentBlock));
StackSlot condition = std::visit(*this, *_if.condition);
makeConditionalJump(debugDataOf(_if), std::move(condition), ifBranch, afterIf);
m_currentBlock = &ifBranch;
(*this)(_if.body);
jump(debugDataOf(_if.body), afterIf);
}
void ControlFlowGraphBuilder::operator()(Switch const& _switch)
{
yulAssert(m_currentBlock, "");
langutil::DebugData::ConstPtr preSwitchDebugData = debugDataOf(_switch);
auto ghostVariableId = m_graph.ghostVariables.size();
YulName ghostVariableName("GHOST[" + std::to_string(ghostVariableId) + "]");
auto& ghostVar = m_graph.ghostVariables.emplace_back(Scope::Variable{ghostVariableName});
// Artificially generate:
// let <ghostVariable> := <switchExpression>
VariableSlot ghostVarSlot{ghostVar, debugDataOf(*_switch.expression)};
StackSlot expression = std::visit(*this, *_switch.expression);
m_currentBlock->operations.emplace_back(CFG::Operation{
Stack{std::move(expression)},
Stack{ghostVarSlot},
CFG::Assignment{_switch.debugData, {ghostVarSlot}}
});
std::optional<BuiltinHandle> const& equalityBuiltinHandle = m_dialect.equalityFunctionHandle();
yulAssert(equalityBuiltinHandle);
// Artificially generate:
// eq(<literal>, <ghostVariable>)
auto makeValueCompare = [&](Case const& _case) {
yul::FunctionCall const& ghostCall = m_graph.ghostCalls.emplace_back(yul::FunctionCall{
debugDataOf(_case),
yul::Identifier{{}, "eq"_yulname},
{*_case.value, Identifier{{}, ghostVariableName}}
});
BuiltinFunction const& equalityBuiltin = m_dialect.builtin(*equalityBuiltinHandle);
CFG::Operation& operation = m_currentBlock->operations.emplace_back(CFG::Operation{
Stack{ghostVarSlot, LiteralSlot{_case.value->value.value(), debugDataOf(*_case.value)}},
Stack{TemporarySlot{ghostCall, 0}},
CFG::BuiltinCall{debugDataOf(_case), equalityBuiltin, ghostCall, 2},
});
return operation.output.front();
};
CFG::BasicBlock& afterSwitch = m_graph.makeBlock(preSwitchDebugData);
yulAssert(!_switch.cases.empty(), "");
for (auto const& switchCase: _switch.cases | ranges::views::drop_last(1))
{
yulAssert(switchCase.value, "");
auto& caseBranch = m_graph.makeBlock(debugDataOf(switchCase.body));
auto& elseBranch = m_graph.makeBlock(debugDataOf(_switch));
makeConditionalJump(debugDataOf(switchCase), makeValueCompare(switchCase), caseBranch, elseBranch);
m_currentBlock = &caseBranch;
(*this)(switchCase.body);
jump(debugDataOf(switchCase.body), afterSwitch);
m_currentBlock = &elseBranch;
}
Case const& switchCase = _switch.cases.back();
if (switchCase.value)
{
CFG::BasicBlock& caseBranch = m_graph.makeBlock(debugDataOf(switchCase.body));
makeConditionalJump(debugDataOf(switchCase), makeValueCompare(switchCase), caseBranch, afterSwitch);
m_currentBlock = &caseBranch;
}
(*this)(switchCase.body);
jump(debugDataOf(switchCase.body), afterSwitch);
}
void ControlFlowGraphBuilder::operator()(ForLoop const& _loop)
{
langutil::DebugData::ConstPtr preLoopDebugData = debugDataOf(_loop);
ScopedSaveAndRestore scopeRestore(m_scope, m_info.scopes.at(&_loop.pre).get());
(*this)(_loop.pre);
std::optional<bool> constantCondition;
if (auto const* literalCondition = std::get_if<yul::Literal>(_loop.condition.get()))
constantCondition = literalCondition->value.value() != 0;
CFG::BasicBlock& loopCondition = m_graph.makeBlock(debugDataOf(*_loop.condition));
CFG::BasicBlock& loopBody = m_graph.makeBlock(debugDataOf(_loop.body));
CFG::BasicBlock& post = m_graph.makeBlock(debugDataOf(_loop.post));
CFG::BasicBlock& afterLoop = m_graph.makeBlock(preLoopDebugData);
ScopedSaveAndRestore scopedSaveAndRestore(m_forLoopInfo, ForLoopInfo{afterLoop, post});
if (constantCondition.has_value())
{
if (*constantCondition)
{
jump(debugDataOf(_loop.pre), loopBody);
(*this)(_loop.body);
jump(debugDataOf(_loop.body), post);
(*this)(_loop.post);
jump(debugDataOf(_loop.post), loopBody, true);
}
else
jump(debugDataOf(_loop.pre), afterLoop);
}
else
{
jump(debugDataOf(_loop.pre), loopCondition);
StackSlot condition = std::visit(*this, *_loop.condition);
makeConditionalJump(debugDataOf(*_loop.condition), std::move(condition), loopBody, afterLoop);
m_currentBlock = &loopBody;
(*this)(_loop.body);
jump(debugDataOf(_loop.body), post);
(*this)(_loop.post);
jump(debugDataOf(_loop.post), loopCondition, true);
}
m_currentBlock = &afterLoop;
}
void ControlFlowGraphBuilder::operator()(Break const& _break)
{
yulAssert(m_forLoopInfo.has_value(), "");
jump(debugDataOf(_break), m_forLoopInfo->afterLoop);
m_currentBlock = &m_graph.makeBlock(debugDataOf(*m_currentBlock));
}
void ControlFlowGraphBuilder::operator()(Continue const& _continue)
{
yulAssert(m_forLoopInfo.has_value(), "");
jump(debugDataOf(_continue), m_forLoopInfo->post);
m_currentBlock = &m_graph.makeBlock(debugDataOf(*m_currentBlock));
}
// '_leave' and '__leave' are reserved in VisualStudio
void ControlFlowGraphBuilder::operator()(Leave const& leave_)
{
yulAssert(m_currentFunction.has_value(), "");
m_currentBlock->exit = CFG::BasicBlock::FunctionReturn{debugDataOf(leave_), *m_currentFunction};
(*m_currentFunction)->exits.emplace_back(m_currentBlock);
m_currentBlock = &m_graph.makeBlock(debugDataOf(*m_currentBlock));
}
void ControlFlowGraphBuilder::operator()(FunctionDefinition const& _function)
{
yulAssert(m_scope, "");
yulAssert(m_scope->identifiers.count(_function.name), "");
Scope::Function& function = std::get<Scope::Function>(m_scope->identifiers.at(_function.name));
m_graph.functions.emplace_back(&function);
CFG::FunctionInfo& functionInfo = m_graph.functionInfo.at(&function);
ControlFlowGraphBuilder builder{m_graph, m_info, m_functionSideEffects, m_dialect};
builder.m_currentFunction = &functionInfo;
builder.m_currentBlock = functionInfo.entry;
builder(_function.body);
functionInfo.exits.emplace_back(builder.m_currentBlock);
builder.m_currentBlock->exit = CFG::BasicBlock::FunctionReturn{debugDataOf(_function), &functionInfo};
}
void ControlFlowGraphBuilder::registerFunction(FunctionDefinition const& _functionDefinition)
{
yulAssert(m_scope, "");
yulAssert(m_scope->identifiers.count(_functionDefinition.name), "");
Scope::Function& function = std::get<Scope::Function>(m_scope->identifiers.at(_functionDefinition.name));
yulAssert(m_info.scopes.at(&_functionDefinition.body), "");
Scope* virtualFunctionScope = m_info.scopes.at(m_info.virtualBlocks.at(&_functionDefinition).get()).get();
yulAssert(virtualFunctionScope, "");
bool inserted = m_graph.functionInfo.emplace(std::make_pair(&function, CFG::FunctionInfo{
_functionDefinition.debugData,
function,
_functionDefinition,
&m_graph.makeBlock(debugDataOf(_functionDefinition.body)),
_functionDefinition.parameters | ranges::views::transform([&](auto const& _param) {
return VariableSlot{
std::get<Scope::Variable>(virtualFunctionScope->identifiers.at(_param.name)),
_param.debugData
};
}) | ranges::to<std::vector>,
_functionDefinition.returnVariables | ranges::views::transform([&](auto const& _retVar) {
return VariableSlot{
std::get<Scope::Variable>(virtualFunctionScope->identifiers.at(_retVar.name)),
_retVar.debugData
};
}) | ranges::to<std::vector>,
{},
m_functionSideEffects.at(&_functionDefinition).canContinue
})).second;
yulAssert(inserted);
}
Stack const& ControlFlowGraphBuilder::visitFunctionCall(FunctionCall const& _call)
{
yulAssert(m_scope, "");
yulAssert(m_currentBlock, "");
Stack const* output = nullptr;
bool canContinue = true;
if (std::optional<BuiltinHandle> const& builtinHandle = m_dialect.findBuiltin(_call.functionName.name.str()))
{
auto const& builtin = m_dialect.builtin(*builtinHandle);
Stack inputs;
for (auto&& [idx, arg]: _call.arguments | ranges::views::enumerate | ranges::views::reverse)
if (!builtin.literalArgument(idx).has_value())
inputs.emplace_back(std::visit(*this, arg));
CFG::BuiltinCall builtinCall{_call.debugData, builtin, _call, inputs.size()};
output = &m_currentBlock->operations.emplace_back(CFG::Operation{
// input
std::move(inputs),
// output
ranges::views::iota(0u, builtin.numReturns) | ranges::views::transform([&](size_t _i) {
return TemporarySlot{_call, _i};
}) | ranges::to<Stack>,
// operation
std::move(builtinCall)
}).output;
canContinue = builtin.controlFlowSideEffects.canContinue;
}
else
{
Scope::Function const& function = lookupFunction(_call.functionName.name);
canContinue = m_graph.functionInfo.at(&function).canContinue;
Stack inputs;
if (canContinue)
inputs.emplace_back(FunctionCallReturnLabelSlot{_call});
for (auto const& arg: _call.arguments | ranges::views::reverse)
inputs.emplace_back(std::visit(*this, arg));
output = &m_currentBlock->operations.emplace_back(CFG::Operation{
// input
std::move(inputs),
// output
ranges::views::iota(0u, function.numReturns) | ranges::views::transform([&](size_t _i) {
return TemporarySlot{_call, _i};
}) | ranges::to<Stack>,
// operation
CFG::FunctionCall{_call.debugData, function, _call, /* recursive */ false, canContinue}
}).output;
}
if (!canContinue)
{
m_currentBlock->exit = CFG::BasicBlock::Terminated{};
m_currentBlock = &m_graph.makeBlock(debugDataOf(*m_currentBlock));
}
return *output;
}
Stack ControlFlowGraphBuilder::visitAssignmentRightHandSide(Expression const& _expression, size_t _expectedSlotCount)
{
return std::visit(util::GenericVisitor{
[&](FunctionCall const& _call) -> Stack {
Stack const& output = visitFunctionCall(_call);
yulAssert(_expectedSlotCount == output.size(), "");
return output;
},
[&](auto const& _identifierOrLiteral) -> Stack {
yulAssert(_expectedSlotCount == 1, "");
return {(*this)(_identifierOrLiteral)};
}
}, _expression);
}
Scope::Function const& ControlFlowGraphBuilder::lookupFunction(YulName _name) const
{
Scope::Function const* function = nullptr;
yulAssert(m_scope->lookup(_name, util::GenericVisitor{
[](Scope::Variable&) { yulAssert(false, "Expected function name."); },
[&](Scope::Function& _function) { function = &_function; }
}), "Function name not found.");
yulAssert(function, "");
return *function;
}
Scope::Variable const& ControlFlowGraphBuilder::lookupVariable(YulName _name) const
{
yulAssert(m_scope, "");
Scope::Variable const* var = nullptr;
if (m_scope->lookup(_name, util::GenericVisitor{
[&](Scope::Variable& _var) { var = &_var; },
[](Scope::Function&)
{
yulAssert(false, "Function not removed during desugaring.");
}
}))
{
yulAssert(var, "");
return *var;
};
yulAssert(false, "External identifier access unimplemented.");
}
void ControlFlowGraphBuilder::makeConditionalJump(
langutil::DebugData::ConstPtr _debugData,
StackSlot _condition,
CFG::BasicBlock& _nonZero,
CFG::BasicBlock& _zero
)
{
yulAssert(m_currentBlock, "");
m_currentBlock->exit = CFG::BasicBlock::ConditionalJump{
std::move(_debugData),
std::move(_condition),
&_nonZero,
&_zero
};
_nonZero.entries.emplace_back(m_currentBlock);
_zero.entries.emplace_back(m_currentBlock);
m_currentBlock = nullptr;
}
void ControlFlowGraphBuilder::jump(
langutil::DebugData::ConstPtr _debugData,
CFG::BasicBlock& _target,
bool backwards
)
{
yulAssert(m_currentBlock, "");
m_currentBlock->exit = CFG::BasicBlock::Jump{std::move(_debugData), &_target, backwards};
_target.entries.emplace_back(m_currentBlock);
m_currentBlock = &_target;
}
| 22,651
|
C++
|
.cpp
| 585
| 35.991453
| 117
| 0.734711
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,085
|
EVMDialect.cpp
|
ethereum_solidity/libyul/backends/evm/EVMDialect.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Yul dialects for EVM.
*/
#include <libyul/backends/evm/EVMDialect.h>
#include <libevmasm/Instruction.h>
#include <libevmasm/SemanticInformation.h>
#include <libsolutil/StringUtils.h>
#include <libyul/AST.h>
#include <libyul/Exceptions.h>
#include <libyul/Object.h>
#include <libyul/Utilities.h>
#include <libyul/backends/evm/AbstractAssembly.h>
#include <range/v3/algorithm/all_of.hpp>
#include <range/v3/view/enumerate.hpp>
#include <regex>
#include <utility>
#include <vector>
using namespace std::string_literals;
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
namespace
{
size_t constexpr toContinuousVerbatimIndex(size_t _arguments, size_t _returnVariables)
{
return _arguments + _returnVariables * EVMDialect::verbatimMaxInputSlots;
}
std::tuple<size_t, size_t> constexpr verbatimIndexToArgsAndRets(size_t _index)
{
size_t const numRets = _index / EVMDialect::verbatimMaxInputSlots;
return std::make_tuple(_index - numRets * EVMDialect::verbatimMaxInputSlots, numRets);
}
BuiltinFunctionForEVM createEVMFunction(
langutil::EVMVersion _evmVersion,
std::string const& _name,
evmasm::Instruction _instruction
)
{
BuiltinFunctionForEVM f;
evmasm::InstructionInfo info = evmasm::instructionInfo(_instruction, _evmVersion);
f.name = _name;
f.numParameters = static_cast<size_t>(info.args);
f.numReturns = static_cast<size_t>(info.ret);
f.sideEffects = EVMDialect::sideEffectsOfInstruction(_instruction);
f.controlFlowSideEffects = ControlFlowSideEffects::fromInstruction(_instruction);
f.isMSize = _instruction == evmasm::Instruction::MSIZE;
f.literalArguments.clear();
f.instruction = _instruction;
f.generateCode = [_instruction](
FunctionCall const&,
AbstractAssembly& _assembly,
BuiltinContext&
) {
_assembly.appendInstruction(_instruction);
};
return f;
}
BuiltinFunctionForEVM createFunction(
std::string const& _name,
size_t _params,
size_t _returns,
SideEffects _sideEffects,
ControlFlowSideEffects _controlFlowSideEffects,
std::vector<std::optional<LiteralKind>> _literalArguments,
std::function<void(FunctionCall const&, AbstractAssembly&, BuiltinContext&)> _generateCode
)
{
yulAssert(_literalArguments.size() == _params || _literalArguments.empty(), "");
BuiltinFunctionForEVM f;
f.name = _name;
f.numParameters = _params;
f.numReturns = _returns;
f.sideEffects = _sideEffects;
f.controlFlowSideEffects = _controlFlowSideEffects;
f.literalArguments = std::move(_literalArguments);
f.isMSize = false;
f.instruction = {};
f.generateCode = std::move(_generateCode);
return f;
}
std::set<std::string, std::less<>> createReservedIdentifiers(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion)
{
// TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name
// basefee for VMs before london.
auto baseFeeException = [&](evmasm::Instruction _instr) -> bool
{
return _instr == evmasm::Instruction::BASEFEE && _evmVersion < langutil::EVMVersion::london();
};
// TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name
// blobbasefee for VMs before cancun.
auto blobBaseFeeException = [&](evmasm::Instruction _instr) -> bool
{
return _instr == evmasm::Instruction::BLOBBASEFEE && _evmVersion < langutil::EVMVersion::cancun();
};
// TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name
// mcopy for VMs before london.
auto mcopyException = [&](evmasm::Instruction _instr) -> bool
{
return _instr == evmasm::Instruction::MCOPY && _evmVersion < langutil::EVMVersion::cancun();
};
// TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name
// prevrandao for VMs before paris.
auto prevRandaoException = [&](std::string const& _instrName) -> bool
{
// Using string comparison as the opcode is the same as for "difficulty"
return _instrName == "prevrandao" && _evmVersion < langutil::EVMVersion::paris();
};
// TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name
// blobhash for VMs before cancun.
auto blobHashException = [&](evmasm::Instruction _instr) -> bool
{
return _instr == evmasm::Instruction::BLOBHASH && _evmVersion < langutil::EVMVersion::cancun();
};
// TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the names
// tstore or tload for VMs before cancun.
auto transientStorageException = [&](evmasm::Instruction _instr) -> bool
{
return
_evmVersion < langutil::EVMVersion::cancun() &&
(_instr == evmasm::Instruction::TSTORE || _instr == evmasm::Instruction::TLOAD);
};
std::set<std::string, std::less<>> reserved;
for (auto const& instr: evmasm::c_instructions)
{
std::string name = toLower(instr.first);
if (
!baseFeeException(instr.second) &&
!prevRandaoException(name) &&
!blobHashException(instr.second) &&
!blobBaseFeeException(instr.second) &&
!mcopyException(instr.second) &&
!transientStorageException(instr.second)
)
reserved.emplace(name);
}
reserved += std::vector<std::string>{
"linkersymbol",
"datasize",
"dataoffset",
"datacopy",
"setimmutable",
"loadimmutable",
};
if (_eofVersion.has_value())
reserved += std::vector<std::string>{
"auxdataloadn",
};
return reserved;
}
std::vector<std::optional<BuiltinFunctionForEVM>> createBuiltins(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, bool _objectAccess)
{
// Exclude prevrandao as builtin for VMs before paris and difficulty for VMs after paris.
auto prevRandaoException = [&](std::string const& _instrName) -> bool
{
return (_instrName == "prevrandao" && _evmVersion < langutil::EVMVersion::paris()) || (_instrName == "difficulty" && _evmVersion >= langutil::EVMVersion::paris());
};
std::vector<std::optional<BuiltinFunctionForEVM>> builtins;
for (auto const& instr: evmasm::c_instructions)
{
std::string name = toLower(instr.first);
auto const opcode = instr.second;
if (
!evmasm::isDupInstruction(opcode) &&
!evmasm::isSwapInstruction(opcode) &&
!evmasm::isPushInstruction(opcode) &&
opcode != evmasm::Instruction::JUMP &&
opcode != evmasm::Instruction::JUMPI &&
opcode != evmasm::Instruction::JUMPDEST &&
opcode != evmasm::Instruction::DATALOADN &&
opcode != evmasm::Instruction::EOFCREATE &&
opcode != evmasm::Instruction::RETURNCONTRACT &&
_evmVersion.hasOpcode(opcode, _eofVersion) &&
!prevRandaoException(name)
)
builtins.emplace_back(createEVMFunction(_evmVersion, name, opcode));
else
builtins.emplace_back(std::nullopt);
}
auto const createIfObjectAccess = [_objectAccess](
std::string const& _name,
size_t _params,
size_t _returns,
SideEffects _sideEffects,
ControlFlowSideEffects _controlFlowSideEffects,
std::vector<std::optional<LiteralKind>> _literalArguments,
std::function<void(FunctionCall const&, AbstractAssembly&, BuiltinContext&)> _generateCode
) -> std::optional<BuiltinFunctionForEVM>
{
if (!_objectAccess)
return std::nullopt;
return createFunction(_name, _params, _returns, _sideEffects, _controlFlowSideEffects, std::move(_literalArguments), std::move(_generateCode));
};
builtins.emplace_back(createIfObjectAccess("linkersymbol", 1, 1, SideEffects{}, ControlFlowSideEffects{}, {LiteralKind::String}, [](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext&
) {
yulAssert(_call.arguments.size() == 1, "");
Expression const& arg = _call.arguments.front();
_assembly.appendLinkerSymbol(formatLiteral(std::get<Literal>(arg)));
}));
builtins.emplace_back(createIfObjectAccess(
"memoryguard",
1,
1,
SideEffects{},
ControlFlowSideEffects{},
{LiteralKind::Number},
[](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext&
) {
yulAssert(_call.arguments.size() == 1, "");
Literal const* literal = std::get_if<Literal>(&_call.arguments.front());
yulAssert(literal, "");
_assembly.appendConstant(literal->value.value());
})
);
if (!_eofVersion.has_value())
{
builtins.emplace_back(createIfObjectAccess("datasize", 1, 1, SideEffects{}, ControlFlowSideEffects{}, {LiteralKind::String}, [](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext& _context
) {
yulAssert(_context.currentObject, "No object available.");
yulAssert(_call.arguments.size() == 1, "");
Expression const& arg = _call.arguments.front();
YulName const dataName (formatLiteral(std::get<Literal>(arg)));
if (_context.currentObject->name == dataName.str())
_assembly.appendAssemblySize();
else
{
std::vector<size_t> subIdPath =
_context.subIDs.count(dataName.str()) == 0 ?
_context.currentObject->pathToSubObject(dataName.str()) :
std::vector<size_t>{_context.subIDs.at(dataName.str())};
yulAssert(!subIdPath.empty(), "Could not find assembly object <" + dataName.str() + ">.");
_assembly.appendDataSize(subIdPath);
}
}));
builtins.emplace_back(createIfObjectAccess("dataoffset", 1, 1, SideEffects{}, ControlFlowSideEffects{}, {LiteralKind::String}, [](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext& _context
) {
yulAssert(_context.currentObject, "No object available.");
yulAssert(_call.arguments.size() == 1, "");
Expression const& arg = _call.arguments.front();
YulName const dataName (formatLiteral(std::get<Literal>(arg)));
if (_context.currentObject->name == dataName.str())
_assembly.appendConstant(0);
else
{
std::vector<size_t> subIdPath =
_context.subIDs.count(dataName.str()) == 0 ?
_context.currentObject->pathToSubObject(dataName.str()) :
std::vector<size_t>{_context.subIDs.at(dataName.str())};
yulAssert(!subIdPath.empty(), "Could not find assembly object <" + dataName.str() + ">.");
_assembly.appendDataOffset(subIdPath);
}
}));
builtins.emplace_back(createIfObjectAccess(
"datacopy",
3,
0,
SideEffects{
false, // movable
true, // movableApartFromEffects
false, // canBeRemoved
false, // canBeRemovedIfNotMSize
true, // cannotLoop
SideEffects::None, // otherState
SideEffects::None, // storage
SideEffects::Write, // memory
SideEffects::None // transientStorage
},
ControlFlowSideEffects::fromInstruction(evmasm::Instruction::CODECOPY),
{},
[](
FunctionCall const&,
AbstractAssembly& _assembly,
BuiltinContext&
) {
_assembly.appendInstruction(evmasm::Instruction::CODECOPY);
}
));
builtins.emplace_back(createIfObjectAccess(
"setimmutable",
3,
0,
SideEffects{
false, // movable
false, // movableApartFromEffects
false, // canBeRemoved
false, // canBeRemovedIfNotMSize
true, // cannotLoop
SideEffects::None, // otherState
SideEffects::None, // storage
SideEffects::Write, // memory
SideEffects::None // transientStorage
},
ControlFlowSideEffects{},
{std::nullopt, LiteralKind::String, std::nullopt},
[](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext&
) {
yulAssert(_call.arguments.size() == 3, "");
auto const identifier = (formatLiteral(std::get<Literal>(_call.arguments[1])));
_assembly.appendImmutableAssignment(identifier);
}
));
builtins.emplace_back(createIfObjectAccess(
"loadimmutable",
1,
1,
SideEffects{},
ControlFlowSideEffects{},
{LiteralKind::String},
[](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext&
) {
yulAssert(_call.arguments.size() == 1, "");
_assembly.appendImmutable(formatLiteral(std::get<Literal>(_call.arguments.front())));
}
));
}
else // EOF context
{
builtins.emplace_back(createFunction(
"auxdataloadn",
1,
1,
EVMDialect::sideEffectsOfInstruction(evmasm::Instruction::DATALOADN),
ControlFlowSideEffects::fromInstruction(evmasm::Instruction::DATALOADN),
{LiteralKind::Number},
[](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext&
) {
yulAssert(_call.arguments.size() == 1);
Literal const* literal = std::get_if<Literal>(&_call.arguments.front());
yulAssert(literal, "");
yulAssert(literal->value.value() <= std::numeric_limits<uint16_t>::max());
_assembly.appendAuxDataLoadN(static_cast<uint16_t>(literal->value.value()));
}
));
builtins.emplace_back(createFunction(
"eofcreate",
5,
1,
EVMDialect::sideEffectsOfInstruction(evmasm::Instruction::EOFCREATE),
ControlFlowSideEffects::fromInstruction(evmasm::Instruction::EOFCREATE),
{LiteralKind::String, std::nullopt, std::nullopt, std::nullopt, std::nullopt},
[](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext& context
) {
yulAssert(_call.arguments.size() == 5);
Literal const* literal = std::get_if<Literal>(&_call.arguments.front());
auto const formattedLiteral = formatLiteral(*literal);
yulAssert(!util::contains(formattedLiteral, '.'));
auto const* containerID = valueOrNullptr(context.subIDs, formattedLiteral);
yulAssert(containerID != nullptr);
yulAssert(*containerID <= std::numeric_limits<AbstractAssembly::ContainerID>::max());
_assembly.appendEOFCreate(static_cast<AbstractAssembly::ContainerID>(*containerID));
}
));
if (_objectAccess)
builtins.emplace_back(createFunction(
"returncontract",
3,
0,
EVMDialect::sideEffectsOfInstruction(evmasm::Instruction::RETURNCONTRACT),
ControlFlowSideEffects::fromInstruction(evmasm::Instruction::RETURNCONTRACT),
{LiteralKind::String, std::nullopt, std::nullopt},
[](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext& context
) {
yulAssert(_call.arguments.size() == 3);
Literal const* literal = std::get_if<Literal>(&_call.arguments.front());
yulAssert(literal);
auto const formattedLiteral = formatLiteral(*literal);
yulAssert(!util::contains(formattedLiteral, '.'));
auto const* containerID = valueOrNullptr(context.subIDs, formattedLiteral);
yulAssert(containerID != nullptr);
yulAssert(*containerID <= std::numeric_limits<AbstractAssembly::ContainerID>::max());
_assembly.appendReturnContract(static_cast<AbstractAssembly::ContainerID>(*containerID));
}
));
}
yulAssert(
ranges::all_of(builtins, [](std::optional<BuiltinFunctionForEVM> const& _builtinFunction){
return !_builtinFunction || _builtinFunction->name.substr(0, "verbatim_"s.size()) != "verbatim_";
}),
"Builtin functions besides verbatim should not start with the verbatim_ prefix."
);
return builtins;
}
std::regex const& verbatimPattern()
{
std::regex static const pattern{"([1-9]?[0-9])i_([1-9]?[0-9])o"};
return pattern;
}
}
EVMDialect::EVMDialect(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion, bool _objectAccess):
m_objectAccess(_objectAccess),
m_evmVersion(_evmVersion),
m_eofVersion(_eofVersion),
m_functions(createBuiltins(_evmVersion, _eofVersion, _objectAccess)),
m_reserved(createReservedIdentifiers(_evmVersion, _eofVersion))
{
for (auto const& [index, maybeBuiltin]: m_functions | ranges::views::enumerate)
if (maybeBuiltin)
// ids are offset by the maximum number of verbatim functions
m_builtinFunctionsByName[maybeBuiltin->name] = BuiltinHandle{index + verbatimIDOffset};
m_discardFunction = findBuiltin("pop");
m_equalityFunction = findBuiltin("eq");
m_booleanNegationFunction = findBuiltin("iszero");
m_memoryStoreFunction = findBuiltin("mstore");
m_memoryLoadFunction = findBuiltin("mload");
m_storageStoreFunction = findBuiltin("sstore");
m_storageLoadFunction = findBuiltin("sload");
m_hashFunction = findBuiltin("keccak256");
}
std::optional<BuiltinHandle> EVMDialect::findBuiltin(std::string_view _name) const
{
if (m_objectAccess && _name.substr(0, "verbatim_"s.size()) == "verbatim_")
{
std::smatch match;
std::string name(_name.substr("verbatim_"s.size()));
if (regex_match(name, match, verbatimPattern()))
return verbatimFunction(stoul(match[1]), stoul(match[2]));
}
if (
auto it = m_builtinFunctionsByName.find(_name);
it != m_builtinFunctionsByName.end()
)
return it->second;
return std::nullopt;
}
BuiltinFunctionForEVM const& EVMDialect::builtin(BuiltinHandle const& _handle) const
{
if (isVerbatimHandle(_handle))
{
yulAssert(_handle.id < verbatimIDOffset);
auto const& verbatimFunctionPtr = m_verbatimFunctions[_handle.id];
yulAssert(verbatimFunctionPtr);
return *verbatimFunctionPtr;
}
yulAssert(_handle.id - verbatimIDOffset < m_functions.size());
auto const& maybeBuiltin = m_functions[_handle.id - verbatimIDOffset];
yulAssert(maybeBuiltin.has_value());
return *maybeBuiltin;
}
bool EVMDialect::reservedIdentifier(std::string_view _name) const
{
if (m_objectAccess)
if (_name.substr(0, "verbatim"s.size()) == "verbatim")
return true;
return m_reserved.count(_name) != 0;
}
EVMDialect const& EVMDialect::strictAssemblyForEVM(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion)
{
static std::map<std::pair<langutil::EVMVersion, std::optional<uint8_t>>, std::unique_ptr<EVMDialect const>> dialects;
static YulStringRepository::ResetCallback callback{[&] { dialects.clear(); }};
if (!dialects[{_evmVersion, _eofVersion}])
dialects[{_evmVersion, _eofVersion}] = std::make_unique<EVMDialect>(_evmVersion, _eofVersion, false);
return *dialects[{_evmVersion, _eofVersion}];
}
EVMDialect const& EVMDialect::strictAssemblyForEVMObjects(langutil::EVMVersion _evmVersion, std::optional<uint8_t> _eofVersion)
{
static std::map<std::pair<langutil::EVMVersion, std::optional<uint8_t>>, std::unique_ptr<EVMDialect const>> dialects;
static YulStringRepository::ResetCallback callback{[&] { dialects.clear(); }};
if (!dialects[{_evmVersion, _eofVersion}])
dialects[{_evmVersion, _eofVersion}] = std::make_unique<EVMDialect>(_evmVersion, _eofVersion, true);
return *dialects[{_evmVersion, _eofVersion}];
}
SideEffects EVMDialect::sideEffectsOfInstruction(evmasm::Instruction _instruction)
{
auto translate = [](evmasm::SemanticInformation::Effect _e) -> SideEffects::Effect
{
return static_cast<SideEffects::Effect>(_e);
};
return SideEffects{
evmasm::SemanticInformation::movable(_instruction),
evmasm::SemanticInformation::movableApartFromEffects(_instruction),
evmasm::SemanticInformation::canBeRemoved(_instruction),
evmasm::SemanticInformation::canBeRemovedIfNoMSize(_instruction),
true, // cannotLoop
translate(evmasm::SemanticInformation::otherState(_instruction)),
translate(evmasm::SemanticInformation::storage(_instruction)),
translate(evmasm::SemanticInformation::memory(_instruction)),
translate(evmasm::SemanticInformation::transientStorage(_instruction)),
};
}
BuiltinFunctionForEVM EVMDialect::createVerbatimFunctionFromHandle(BuiltinHandle const& _handle)
{
return std::apply(createVerbatimFunction, verbatimIndexToArgsAndRets(_handle.id));
}
BuiltinFunctionForEVM EVMDialect::createVerbatimFunction(size_t _arguments, size_t _returnVariables)
{
BuiltinFunctionForEVM builtinFunction = createFunction(
"verbatim_" + std::to_string(_arguments) + "i_" + std::to_string(_returnVariables) + "o",
1 + _arguments,
_returnVariables,
SideEffects::worst(),
ControlFlowSideEffects{},
std::vector<std::optional<LiteralKind>>{LiteralKind::String} + std::vector<std::optional<LiteralKind>>(_arguments),
[=](
FunctionCall const& _call,
AbstractAssembly& _assembly,
BuiltinContext&
) {
yulAssert(_call.arguments.size() == (1 + _arguments), "");
Expression const& bytecode = _call.arguments.front();
_assembly.appendVerbatim(
asBytes(formatLiteral(std::get<Literal>(bytecode))),
_arguments,
_returnVariables
);
}
);
builtinFunction.isMSize = true;
return builtinFunction;
}
BuiltinHandle EVMDialect::verbatimFunction(size_t _arguments, size_t _returnVariables) const
{
yulAssert(_arguments <= verbatimMaxInputSlots);
yulAssert(_returnVariables <= verbatimMaxOutputSlots);
auto const verbatimIndex = toContinuousVerbatimIndex(_arguments, _returnVariables);
yulAssert(verbatimIndex < verbatimIDOffset);
if (
auto& verbatimFunctionPtr = m_verbatimFunctions[verbatimIndex];
!verbatimFunctionPtr
)
verbatimFunctionPtr = std::make_unique<BuiltinFunctionForEVM>(createVerbatimFunction(_arguments, _returnVariables));
return {verbatimIndex};
}
| 21,359
|
C++
|
.cpp
| 562
| 34.934164
| 165
| 0.734044
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,090
|
ConditionalSimplifier.cpp
|
ethereum_solidity/libyul/optimiser/ConditionalSimplifier.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/ConditionalSimplifier.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/AST.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
void ConditionalSimplifier::run(OptimiserStepContext& _context, Block& _ast)
{
ConditionalSimplifier{
_context.dialect,
ControlFlowSideEffectsCollector{_context.dialect, _ast}.functionSideEffectsNamed()
}(_ast);
}
void ConditionalSimplifier::operator()(Switch& _switch)
{
visit(*_switch.expression);
if (!std::holds_alternative<Identifier>(*_switch.expression))
{
ASTModifier::operator()(_switch);
return;
}
YulName expr = std::get<Identifier>(*_switch.expression).name;
for (auto& _case: _switch.cases)
{
if (_case.value)
{
(*this)(*_case.value);
_case.body.statements.insert(_case.body.statements.begin(),
Assignment{
_case.body.debugData,
{Identifier{_case.body.debugData, expr}},
std::make_unique<Expression>(*_case.value)
}
);
}
(*this)(_case.body);
}
}
void ConditionalSimplifier::operator()(Block& _block)
{
iterateReplacing(
_block.statements,
[&](Statement& _s) -> std::optional<std::vector<Statement>>
{
visit(_s);
if (std::holds_alternative<If>(_s))
{
If& _if = std::get<If>(_s);
if (
std::holds_alternative<Identifier>(*_if.condition) &&
!_if.body.statements.empty() &&
TerminationFinder(m_dialect, &m_functionSideEffects).controlFlowKind(_if.body.statements.back()) !=
TerminationFinder::ControlFlow::FlowOut
)
{
YulName condition = std::get<Identifier>(*_if.condition).name;
langutil::DebugData::ConstPtr debugData = _if.debugData;
return make_vector<Statement>(
std::move(_s),
Assignment{
debugData,
{Identifier{debugData, condition}},
std::make_unique<Expression>(m_dialect.zeroLiteral())
}
);
}
}
return {};
}
);
}
| 2,740
|
C++
|
.cpp
| 88
| 27.852273
| 104
| 0.724008
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,091
|
Semantics.cpp
|
ethereum_solidity/libyul/optimiser/Semantics.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Specific AST walkers that collect semantical facts.
*/
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/Exceptions.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libevmasm/SemanticInformation.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Algorithms.h>
#include <limits>
using namespace solidity;
using namespace solidity::yul;
SideEffectsCollector::SideEffectsCollector(
Dialect const& _dialect,
Expression const& _expression,
std::map<YulName, SideEffects> const* _functionSideEffects
):
SideEffectsCollector(_dialect, _functionSideEffects)
{
visit(_expression);
}
SideEffectsCollector::SideEffectsCollector(Dialect const& _dialect, Statement const& _statement):
SideEffectsCollector(_dialect)
{
visit(_statement);
}
SideEffectsCollector::SideEffectsCollector(
Dialect const& _dialect,
Block const& _ast,
std::map<YulName, SideEffects> const* _functionSideEffects
):
SideEffectsCollector(_dialect, _functionSideEffects)
{
operator()(_ast);
}
SideEffectsCollector::SideEffectsCollector(
Dialect const& _dialect,
ForLoop const& _ast,
std::map<YulName, SideEffects> const* _functionSideEffects
):
SideEffectsCollector(_dialect, _functionSideEffects)
{
operator()(_ast);
}
void SideEffectsCollector::operator()(FunctionCall const& _functionCall)
{
ASTWalker::operator()(_functionCall);
YulName functionName = _functionCall.functionName.name;
if (std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(functionName.str()))
m_sideEffects += m_dialect.builtin(*builtinHandle).sideEffects;
else if (m_functionSideEffects && m_functionSideEffects->count(functionName))
m_sideEffects += m_functionSideEffects->at(functionName);
else
m_sideEffects += SideEffects::worst();
}
bool MSizeFinder::containsMSize(Dialect const& _dialect, Block const& _ast)
{
MSizeFinder finder(_dialect);
finder(_ast);
return finder.m_msizeFound;
}
bool MSizeFinder::containsMSize(Dialect const& _dialect, Object const& _object)
{
if (containsMSize(_dialect, _object.code()->root()))
return true;
for (std::shared_ptr<ObjectNode> const& node: _object.subObjects)
if (auto const* object = dynamic_cast<Object const*>(node.get()))
if (containsMSize(_dialect, *object))
return true;
return false;
}
void MSizeFinder::operator()(FunctionCall const& _functionCall)
{
ASTWalker::operator()(_functionCall);
if (std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(_functionCall.functionName.name.str()))
if (m_dialect.builtin(*builtinHandle).isMSize)
m_msizeFound = true;
}
std::map<YulName, SideEffects> SideEffectsPropagator::sideEffects(
Dialect const& _dialect,
CallGraph const& _directCallGraph
)
{
// Any loop currently makes a function non-movable, because
// it could be a non-terminating loop.
// The same is true for any function part of a call cycle.
// In the future, we should refine that, because the property
// is actually a bit different from "not movable".
std::map<YulName, SideEffects> ret;
for (auto const& function: _directCallGraph.functionsWithLoops + _directCallGraph.recursiveFunctions())
{
ret[function].movable = false;
ret[function].canBeRemoved = false;
ret[function].canBeRemovedIfNoMSize = false;
ret[function].cannotLoop = false;
}
for (auto const& call: _directCallGraph.functionCalls)
{
YulName funName = call.first;
SideEffects sideEffects;
auto _visit = [&, visited = std::set<YulName>{}](YulName _function, auto&& _recurse) mutable {
if (!visited.insert(_function).second)
return;
if (sideEffects == SideEffects::worst())
return;
if (std::optional<BuiltinHandle> builtinHandle = _dialect.findBuiltin(_function.str()))
sideEffects += _dialect.builtin(*builtinHandle).sideEffects;
else
{
if (ret.count(_function))
sideEffects += ret[_function];
for (YulName callee: _directCallGraph.functionCalls.at(_function))
_recurse(callee, _recurse);
}
};
for (auto const& _v: call.second)
_visit(_v, _visit);
ret[funName] += sideEffects;
}
return ret;
}
MovableChecker::MovableChecker(Dialect const& _dialect, Expression const& _expression):
MovableChecker(_dialect)
{
visit(_expression);
}
void MovableChecker::operator()(Identifier const& _identifier)
{
SideEffectsCollector::operator()(_identifier);
m_variableReferences.emplace(_identifier.name);
}
void MovableChecker::visit(Statement const&)
{
assertThrow(false, OptimizerException, "Movability for statement requested.");
}
std::pair<TerminationFinder::ControlFlow, size_t> TerminationFinder::firstUnconditionalControlFlowChange(
std::vector<Statement> const& _statements
)
{
for (size_t i = 0; i < _statements.size(); ++i)
{
ControlFlow controlFlow = controlFlowKind(_statements[i]);
if (controlFlow != ControlFlow::FlowOut)
return {controlFlow, i};
}
return {ControlFlow::FlowOut, std::numeric_limits<size_t>::max()};
}
TerminationFinder::ControlFlow TerminationFinder::controlFlowKind(Statement const& _statement)
{
if (
std::holds_alternative<VariableDeclaration>(_statement) &&
std::get<VariableDeclaration>(_statement).value &&
containsNonContinuingFunctionCall(*std::get<VariableDeclaration>(_statement).value)
)
return ControlFlow::Terminate;
else if (
std::holds_alternative<Assignment>(_statement) &&
containsNonContinuingFunctionCall(*std::get<Assignment>(_statement).value)
)
return ControlFlow::Terminate;
else if (
std::holds_alternative<ExpressionStatement>(_statement) &&
containsNonContinuingFunctionCall(std::get<ExpressionStatement>(_statement).expression)
)
return ControlFlow::Terminate;
else if (std::holds_alternative<Break>(_statement))
return ControlFlow::Break;
else if (std::holds_alternative<Continue>(_statement))
return ControlFlow::Continue;
else if (std::holds_alternative<Leave>(_statement))
return ControlFlow::Leave;
else
return ControlFlow::FlowOut;
}
bool TerminationFinder::containsNonContinuingFunctionCall(Expression const& _expr)
{
if (auto functionCall = std::get_if<FunctionCall>(&_expr))
{
for (auto const& arg: functionCall->arguments)
if (containsNonContinuingFunctionCall(arg))
return true;
if (std::optional<BuiltinHandle> const builtinHandle = m_dialect.findBuiltin(functionCall->functionName.name.str()))
return !m_dialect.builtin(*builtinHandle).controlFlowSideEffects.canContinue;
else if (m_functionSideEffects && m_functionSideEffects->count(functionCall->functionName.name))
return !m_functionSideEffects->at(functionCall->functionName.name).canContinue;
}
return false;
}
| 7,327
|
C++
|
.cpp
| 204
| 33.622549
| 118
| 0.776336
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,092
|
UnusedStoreBase.cpp
|
ethereum_solidity/libyul/optimiser/UnusedStoreBase.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Base class for both UnusedAssignEliminator and UnusedStoreEliminator.
*/
#include <libyul/optimiser/UnusedStoreBase.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
#include <range/v3/action/remove_if.hpp>
using namespace solidity;
using namespace solidity::yul;
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::operator()(If const& _if)
{
visit(*_if.condition);
ActiveStores skipBranch{m_activeStores};
(*this)(_if.body);
merge(m_activeStores, std::move(skipBranch));
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::operator()(Switch const& _switch)
{
visit(*_switch.expression);
ActiveStores const preState{m_activeStores};
bool hasDefault = false;
std::vector<ActiveStores> branches;
for (auto const& c: _switch.cases)
{
if (!c.value)
hasDefault = true;
(*this)(c.body);
branches.emplace_back(std::move(m_activeStores));
m_activeStores = preState;
}
if (hasDefault)
{
m_activeStores = std::move(branches.back());
branches.pop_back();
}
for (auto& branch: branches)
merge(m_activeStores, std::move(branch));
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::operator()(FunctionDefinition const& _functionDefinition)
{
ScopedSaveAndRestore allStores(m_allStores, {});
ScopedSaveAndRestore usedStores(m_usedStores, {});
ScopedSaveAndRestore outerAssignments(m_activeStores, {});
ScopedSaveAndRestore forLoopInfo(m_forLoopInfo, {});
ScopedSaveAndRestore forLoopNestingDepth(m_forLoopNestingDepth, 0);
(*this)(_functionDefinition.body);
finalizeFunctionDefinition(_functionDefinition);
m_storesToRemove += m_allStores - m_usedStores;
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::operator()(ForLoop const& _forLoop)
{
ScopedSaveAndRestore outerForLoopInfo(m_forLoopInfo, {});
ScopedSaveAndRestore forLoopNestingDepth(m_forLoopNestingDepth, m_forLoopNestingDepth + 1);
// If the pre block was not empty,
// we would have to deal with more complicated scoping rules.
assertThrow(_forLoop.pre.statements.empty(), OptimizerException, "");
// We just run the loop twice to account for the back edge.
// There need not be more runs because we only have three different states.
visit(*_forLoop.condition);
ActiveStores zeroRuns{m_activeStores};
(*this)(_forLoop.body);
merge(m_activeStores, std::move(m_forLoopInfo.pendingContinueStmts));
m_forLoopInfo.pendingContinueStmts = {};
(*this)(_forLoop.post);
visit(*_forLoop.condition);
if (m_forLoopNestingDepth < 6)
{
// Do the second run only for small nesting depths to avoid horrible runtime.
ActiveStores oneRun{m_activeStores};
(*this)(_forLoop.body);
merge(m_activeStores, std::move(m_forLoopInfo.pendingContinueStmts));
m_forLoopInfo.pendingContinueStmts.clear();
(*this)(_forLoop.post);
visit(*_forLoop.condition);
// Order of merging does not matter because "max" is commutative and associative.
merge(m_activeStores, std::move(oneRun));
}
else
// Shortcut to avoid horrible runtime.
shortcutNestedLoop(zeroRuns);
// Order of merging does not matter because "max" is commutative and associative.
merge(m_activeStores, std::move(zeroRuns));
merge(m_activeStores, std::move(m_forLoopInfo.pendingBreakStmts));
m_forLoopInfo.pendingBreakStmts.clear();
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::operator()(Break const&)
{
m_forLoopInfo.pendingBreakStmts.emplace_back(std::move(m_activeStores));
m_activeStores.clear();
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::operator()(Continue const&)
{
m_forLoopInfo.pendingContinueStmts.emplace_back(std::move(m_activeStores));
m_activeStores.clear();
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::merge(ActiveStores& _target, ActiveStores&& _other)
{
util::joinMap(_target, std::move(_other), [](
std::set<Statement const*>& _storesHere,
std::set<Statement const*>&& _storesThere
)
{
_storesHere += _storesThere;
});
}
template<typename ActiveStoresKeyType>
void UnusedStoreBase<ActiveStoresKeyType>::merge(ActiveStores& _target, std::vector<ActiveStores>&& _source)
{
for (ActiveStores& ts: _source)
merge(_target, std::move(ts));
_source.clear();
}
template class solidity::yul::UnusedStoreBase<UnusedStoreEliminatorKey>;
template class solidity::yul::UnusedStoreBase<YulName>;
| 5,249
|
C++
|
.cpp
| 137
| 36.218978
| 108
| 0.787867
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,094
|
ForLoopConditionOutOfBody.cpp
|
ethereum_solidity/libyul/optimiser/ForLoopConditionOutOfBody.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/ForLoopConditionOutOfBody.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
void ForLoopConditionOutOfBody::run(OptimiserStepContext& _context, Block& _ast)
{
ForLoopConditionOutOfBody{_context.dialect}(_ast);
}
void ForLoopConditionOutOfBody::operator()(ForLoop& _forLoop)
{
ASTModifier::operator()(_forLoop);
if (
!m_dialect.booleanNegationFunctionHandle() ||
!std::holds_alternative<Literal>(*_forLoop.condition) ||
std::get<Literal>(*_forLoop.condition).value.value() == 0 ||
_forLoop.body.statements.empty() ||
!std::holds_alternative<If>(_forLoop.body.statements.front())
)
return;
If& firstStatement = std::get<If>(_forLoop.body.statements.front());
if (
firstStatement.body.statements.empty() ||
!std::holds_alternative<Break>(firstStatement.body.statements.front())
)
return;
if (!SideEffectsCollector(m_dialect, *firstStatement.condition).movable())
return;
YulName const iszero{m_dialect.builtin(*m_dialect.booleanNegationFunctionHandle()).name};
langutil::DebugData::ConstPtr debugData = debugDataOf(*firstStatement.condition);
if (
std::holds_alternative<FunctionCall>(*firstStatement.condition) &&
std::get<FunctionCall>(*firstStatement.condition).functionName.name == iszero
)
_forLoop.condition = std::make_unique<Expression>(std::move(std::get<FunctionCall>(*firstStatement.condition).arguments.front()));
else
_forLoop.condition = std::make_unique<Expression>(FunctionCall{
debugData,
Identifier{debugData, iszero},
util::make_vector<Expression>(
std::move(*firstStatement.condition)
)
});
_forLoop.body.statements.erase(_forLoop.body.statements.begin());
}
| 2,498
|
C++
|
.cpp
| 61
| 38.557377
| 132
| 0.775485
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,095
|
ExpressionSimplifier.cpp
|
ethereum_solidity/libyul/optimiser/ExpressionSimplifier.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that uses the simplification rules to simplify expressions.
*/
#include <libyul/optimiser/ExpressionSimplifier.h>
#include <libyul/optimiser/SimplificationRules.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libevmasm/SemanticInformation.h>
using namespace solidity;
using namespace solidity::yul;
void ExpressionSimplifier::run(OptimiserStepContext& _context, Block& _ast)
{
ExpressionSimplifier{_context.dialect}(_ast);
}
void ExpressionSimplifier::visit(Expression& _expression)
{
ASTModifier::visit(_expression);
while (auto const* match = SimplificationRules::findFirstMatch(
_expression,
m_dialect,
[this](YulName _var) { return variableValue(_var); }
))
_expression = match->action().toExpression(debugDataOf(_expression), evmVersionFromDialect(m_dialect));
if (auto* functionCall = std::get_if<FunctionCall>(&_expression))
if (std::optional<evmasm::Instruction> instruction = toEVMInstruction(m_dialect, functionCall->functionName.name))
for (auto op: evmasm::SemanticInformation::readWriteOperations(*instruction))
if (op.startParameter && op.lengthParameter)
{
Expression& startArgument = functionCall->arguments.at(*op.startParameter);
Expression const& lengthArgument = functionCall->arguments.at(*op.lengthParameter);
if (
knownToBeZero(lengthArgument) &&
!knownToBeZero(startArgument) &&
!std::holds_alternative<FunctionCall>(startArgument)
)
startArgument = Literal{debugDataOf(startArgument), LiteralKind::Number, LiteralValue{0, std::nullopt}};
}
}
bool ExpressionSimplifier::knownToBeZero(Expression const& _expression) const
{
if (auto const* literal = std::get_if<Literal>(&_expression))
return literal->value.value() == 0;
else if (auto const* identifier = std::get_if<Identifier>(&_expression))
return valueOfIdentifier(identifier->name) == 0;
else
return false;
}
| 2,705
|
C++
|
.cpp
| 63
| 40.222222
| 116
| 0.774905
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,096
|
CommonSubexpressionEliminator.cpp
|
ethereum_solidity/libyul/optimiser/CommonSubexpressionEliminator.cpp
|
/*(
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Optimisation stage that replaces expressions known to be the current value of a variable
* in scope by a reference to that variable.
*/
#include <libyul/optimiser/CommonSubexpressionEliminator.h>
#include <libyul/optimiser/SyntacticalEquality.h>
#include <libyul/optimiser/BlockHasher.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/SideEffects.h>
#include <libyul/Exceptions.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libyul/Utilities.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
void CommonSubexpressionEliminator::run(OptimiserStepContext& _context, Block& _ast)
{
CommonSubexpressionEliminator cse{
_context.dialect,
SideEffectsPropagator::sideEffects(_context.dialect, CallGraphGenerator::callGraph(_ast))
};
cse(_ast);
}
CommonSubexpressionEliminator::CommonSubexpressionEliminator(
Dialect const& _dialect,
std::map<YulName, SideEffects> _functionSideEffects
):
DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore, std::move(_functionSideEffects))
{
}
void CommonSubexpressionEliminator::operator()(FunctionDefinition& _fun)
{
ScopedSaveAndRestore returnVariables(m_returnVariables, {});
ScopedSaveAndRestore replacementCandidates(m_replacementCandidates, {});
for (auto const& v: _fun.returnVariables)
m_returnVariables.insert(v.name);
DataFlowAnalyzer::operator()(_fun);
}
void CommonSubexpressionEliminator::visit(Expression& _e)
{
bool descend = true;
// If this is a function call to a function that requires literal arguments,
// do not try to simplify there.
if (std::holds_alternative<FunctionCall>(_e))
{
FunctionCall& funCall = std::get<FunctionCall>(_e);
if (std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(funCall.functionName.name.str()))
{
BuiltinFunction const& builtin = m_dialect.builtin(*builtinHandle);
for (size_t i = funCall.arguments.size(); i > 0; i--)
// We should not modify function arguments that have to be literals
// Note that replacing the function call entirely is fine,
// if the function call is movable.
if (!builtin.literalArgument(i - 1))
visit(funCall.arguments[i - 1]);
descend = false;
}
}
// We visit the inner expression first to first simplify inner expressions,
// which hopefully allows more matches.
// Note that the DataFlowAnalyzer itself only has code for visiting Statements,
// so this basically invokes the AST walker directly and thus post-visiting
// is also fine with regards to data flow analysis.
if (descend)
DataFlowAnalyzer::visit(_e);
if (Identifier const* identifier = std::get_if<Identifier>(&_e))
{
YulName identifierName = identifier->name;
if (AssignedValue const* assignedValue = variableValue(identifierName))
{
assertThrow(assignedValue->value, OptimizerException, "");
if (Identifier const* value = std::get_if<Identifier>(assignedValue->value))
if (inScope(value->name))
_e = Identifier{debugDataOf(_e), value->name};
}
}
else if (auto const* candidates = util::valueOrNullptr(m_replacementCandidates, _e))
for (auto const& variable: *candidates)
if (AssignedValue const* value = variableValue(variable))
{
assertThrow(value->value, OptimizerException, "");
// Prevent using the default value of return variables
// instead of literal zeros.
if (
m_returnVariables.count(variable) &&
std::holds_alternative<Literal>(*value->value) &&
std::get<Literal>(*value->value).value.value() == 0
)
continue;
// We check for syntactic equality again because the value might have changed.
if (inScope(variable) && SyntacticallyEqual{}(_e, *value->value))
{
_e = Identifier{debugDataOf(_e), variable};
break;
}
}
}
void CommonSubexpressionEliminator::assignValue(YulName _variable, Expression const* _value)
{
if (_value)
m_replacementCandidates[*_value].insert(_variable);
DataFlowAnalyzer::assignValue(_variable, _value);
}
| 4,689
|
C++
|
.cpp
| 118
| 36.983051
| 106
| 0.762407
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,097
|
EqualStoreEliminator.cpp
|
ethereum_solidity/libyul/optimiser/EqualStoreEliminator.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimisation stage that removes mstore and sstore operations if they store the same
* value that is already known to be in that slot.
*/
#include <libyul/optimiser/EqualStoreEliminator.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::evmasm;
using namespace solidity::yul;
void EqualStoreEliminator::run(OptimiserStepContext const& _context, Block& _ast)
{
EqualStoreEliminator eliminator{
_context.dialect,
SideEffectsPropagator::sideEffects(_context.dialect, CallGraphGenerator::callGraph(_ast))
};
eliminator(_ast);
StatementRemover remover{eliminator.m_pendingRemovals};
remover(_ast);
}
void EqualStoreEliminator::visit(Statement& _statement)
{
// No need to consider potential changes through complex arguments since
// isSimpleStore only returns something if the arguments are identifiers.
if (ExpressionStatement const* expression = std::get_if<ExpressionStatement>(&_statement))
{
if (auto vars = isSimpleStore(StoreLoadLocation::Storage, *expression))
{
if (std::optional<YulName> currentValue = storageValue(vars->first))
if (*currentValue == vars->second)
m_pendingRemovals.insert(&_statement);
}
else if (auto vars = isSimpleStore(StoreLoadLocation::Memory, *expression))
{
if (std::optional<YulName> currentValue = memoryValue(vars->first))
if (*currentValue == vars->second)
m_pendingRemovals.insert(&_statement);
}
}
DataFlowAnalyzer::visit(_statement);
}
| 2,354
|
C++
|
.cpp
| 59
| 37.627119
| 91
| 0.78512
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,099
|
ExpressionSplitter.cpp
|
ethereum_solidity/libyul/optimiser/ExpressionSplitter.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that turns complex expressions into multiple variable
* declarations.
*/
#include <libyul/optimiser/ExpressionSplitter.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
using namespace solidity::langutil;
void ExpressionSplitter::run(OptimiserStepContext& _context, Block& _ast)
{
ExpressionSplitter{_context.dialect, _context.dispenser}(_ast);
}
void ExpressionSplitter::operator()(FunctionCall& _funCall)
{
std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(_funCall.functionName.name.str());
for (size_t i = _funCall.arguments.size(); i > 0; i--)
if (!builtinHandle || !m_dialect.builtin(*builtinHandle).literalArgument(i - 1))
outlineExpression(_funCall.arguments[i - 1]);
}
void ExpressionSplitter::operator()(If& _if)
{
outlineExpression(*_if.condition);
(*this)(_if.body);
}
void ExpressionSplitter::operator()(Switch& _switch)
{
outlineExpression(*_switch.expression);
for (auto& _case: _switch.cases)
// Do not visit the case expression, nothing to split there.
(*this)(_case.body);
}
void ExpressionSplitter::operator()(ForLoop& _loop)
{
(*this)(_loop.pre);
// Do not visit the condition because we cannot split expressions there.
(*this)(_loop.post);
(*this)(_loop.body);
}
void ExpressionSplitter::operator()(Block& _block)
{
std::vector<Statement> saved;
swap(saved, m_statementsToPrefix);
std::function<std::optional<std::vector<Statement>>(Statement&)> f =
[&](Statement& _statement) -> std::optional<std::vector<Statement>> {
m_statementsToPrefix.clear();
visit(_statement);
if (m_statementsToPrefix.empty())
return {};
m_statementsToPrefix.emplace_back(std::move(_statement));
return std::move(m_statementsToPrefix);
};
iterateReplacing(_block.statements, f);
swap(saved, m_statementsToPrefix);
}
void ExpressionSplitter::outlineExpression(Expression& _expr)
{
if (std::holds_alternative<Identifier>(_expr))
return;
visit(_expr);
langutil::DebugData::ConstPtr debugData = debugDataOf(_expr);
YulName var = m_nameDispenser.newName({});
m_statementsToPrefix.emplace_back(VariableDeclaration{
debugData,
{{NameWithDebugData{debugData, var}}},
std::make_unique<Expression>(std::move(_expr))
});
_expr = Identifier{debugData, var};
}
| 3,124
|
C++
|
.cpp
| 87
| 33.850575
| 102
| 0.764589
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,100
|
NameSimplifier.cpp
|
ethereum_solidity/libyul/optimiser/NameSimplifier.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libyul/optimiser/NameSimplifier.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libyul/YulName.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libsolutil/CommonData.h>
#include <regex>
using namespace solidity::yul;
NameSimplifier::NameSimplifier(OptimiserStepContext& _context, Block const& _ast):
m_context(_context)
{
for (YulName name: _context.reservedIdentifiers)
m_translations[name] = name;
for (YulName const& name: NameCollector(_ast).names())
findSimplification(name);
}
void NameSimplifier::operator()(FunctionDefinition& _funDef)
{
translate(_funDef.name);
renameVariables(_funDef.parameters);
renameVariables(_funDef.returnVariables);
ASTModifier::operator()(_funDef);
}
void NameSimplifier::operator()(VariableDeclaration& _varDecl)
{
renameVariables(_varDecl.variables);
ASTModifier::operator()(_varDecl);
}
void NameSimplifier::renameVariables(std::vector<NameWithDebugData>& _variables)
{
for (NameWithDebugData& typedName: _variables)
translate(typedName.name);
}
void NameSimplifier::operator()(Identifier& _identifier)
{
translate(_identifier.name);
}
void NameSimplifier::operator()(FunctionCall& _funCall)
{
// The visitor on its own does not visit the function name.
if (!m_context.dialect.findBuiltin(_funCall.functionName.name.str()))
(*this)(_funCall.functionName);
ASTModifier::operator()(_funCall);
}
void NameSimplifier::findSimplification(YulName const& _name)
{
if (m_translations.count(_name))
return;
std::string name = _name.str();
static auto replacements = std::vector<std::pair<std::regex, std::string>>{
{std::regex("_\\$|\\$_"), "_"}, // remove type mangling delimiters
{std::regex("_[0-9]+([^0-9a-fA-Fx])"), "$1"}, // removes AST IDs that are not hex.
{std::regex("_[0-9]+$"), ""}, // removes AST IDs that are not hex.
{std::regex("_t_"), "_"}, // remove type prefixes
{std::regex("__"), "_"},
{std::regex("(abi_..code.*)_to_.*"), "$1"}, // removes _to... for abi functions
{std::regex("(stringliteral_?[0-9a-f][0-9a-f][0-9a-f][0-9a-f])[0-9a-f]*"), "$1"}, // shorten string literal
{std::regex("tuple_"), ""},
{std::regex("_memory_ptr"), ""},
{std::regex("_calldata_ptr"), "_calldata"},
{std::regex("_fromStack"), ""},
{std::regex("_storage_storage"), "_storage"},
{std::regex("(storage.*)_?storage"), "$1"},
{std::regex("_memory_memory"), "_memory"},
{std::regex("_contract\\$_([^_]*)_?"), "$1_"},
{std::regex("index_access_(t_)?array"), "index_access"},
{std::regex("[0-9]*_$"), ""}
};
for (auto const& [pattern, substitute]: replacements)
{
std::string candidate = regex_replace(name, pattern, substitute);
if (!candidate.empty() && !m_context.dispenser.illegalName(YulName(candidate)))
name = candidate;
}
if (name != _name.str())
{
YulName newName{name};
m_context.dispenser.markUsed(newName);
m_translations[_name] = std::move(newName);
}
}
void NameSimplifier::translate(YulName& _name)
{
auto it = m_translations.find(_name);
if (it != m_translations.end())
_name = it->second;
}
| 3,809
|
C++
|
.cpp
| 102
| 35.205882
| 109
| 0.71169
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,103
|
FullInliner.cpp
|
ethereum_solidity/libyul/optimiser/FullInliner.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that performs function inlining for arbitrary functions.
*/
#include <libyul/optimiser/FullInliner.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/FunctionCallFinder.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/Metrics.h>
#include <libyul/optimiser/SSAValueTracker.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/Exceptions.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Visitor.h>
#include <range/v3/action/remove.hpp>
#include <range/v3/view/reverse.hpp>
#include <range/v3/view/zip.hpp>
using namespace solidity;
using namespace solidity::yul;
void FullInliner::run(OptimiserStepContext& _context, Block& _ast)
{
FullInliner inliner{_ast, _context.dispenser, _context.dialect};
inliner.run(Pass::InlineTiny);
inliner.run(Pass::InlineRest);
}
FullInliner::FullInliner(Block& _ast, NameDispenser& _dispenser, Dialect const& _dialect):
m_ast(_ast),
m_recursiveFunctions(CallGraphGenerator::callGraph(_ast).recursiveFunctions()),
m_nameDispenser(_dispenser),
m_dialect(_dialect)
{
// Determine constants
SSAValueTracker tracker;
tracker(m_ast);
for (auto const& ssaValue: tracker.values())
if (ssaValue.second && std::holds_alternative<Literal>(*ssaValue.second))
m_constants.emplace(ssaValue.first);
// Store size of global statements.
m_functionSizes[YulName{}] = CodeSize::codeSize(_ast);
std::map<YulName, size_t> references = ReferencesCounter::countReferences(m_ast);
for (auto& statement: m_ast.statements)
{
if (!std::holds_alternative<FunctionDefinition>(statement))
continue;
FunctionDefinition& fun = std::get<FunctionDefinition>(statement);
m_functions[fun.name] = &fun;
if (LeaveFinder::containsLeave(fun))
m_noInlineFunctions.insert(fun.name);
// Always inline functions that are only called once.
if (references[fun.name] == 1)
m_singleUse.emplace(fun.name);
updateCodeSize(fun);
}
// Check for memory guard.
std::vector<FunctionCall*> memoryGuardCalls = findFunctionCalls(_ast, "memoryguard"_yulname);
// We will perform less aggressive inlining, if no ``memoryguard`` call is found.
if (!memoryGuardCalls.empty())
m_hasMemoryGuard = true;
}
void FullInliner::run(Pass _pass)
{
m_pass = _pass;
// Note that the order of inlining can result in very different code.
// Since AST IDs and thus function names depend on whether or not a contract
// is compiled together with other source files, a change in AST IDs
// should have as little an impact as possible. This is the case
// if we handle inlining in source (and thus, for the IR generator,
// function name) order.
// We use stable_sort below to keep the inlining order of two functions
// with the same depth.
std::map<YulName, size_t> depths = callDepths();
std::vector<FunctionDefinition*> functions;
for (auto& statement: m_ast.statements)
if (std::holds_alternative<FunctionDefinition>(statement))
functions.emplace_back(&std::get<FunctionDefinition>(statement));
std::stable_sort(functions.begin(), functions.end(), [&depths](
FunctionDefinition const* _a,
FunctionDefinition const* _b
) {
return depths.at(_a->name) < depths.at(_b->name);
});
for (FunctionDefinition* fun: functions)
{
handleBlock(fun->name, fun->body);
updateCodeSize(*fun);
}
for (auto& statement: m_ast.statements)
if (std::holds_alternative<Block>(statement))
handleBlock({}, std::get<Block>(statement));
}
std::map<YulName, size_t> FullInliner::callDepths() const
{
CallGraph cg = CallGraphGenerator::callGraph(m_ast);
cg.functionCalls.erase(""_yulname);
// Remove calls to builtin functions.
for (auto& call: cg.functionCalls)
for (auto it = call.second.begin(); it != call.second.end();)
if (m_dialect.findBuiltin(it->str()))
it = call.second.erase(it);
else
++it;
std::map<YulName, size_t> depths;
size_t currentDepth = 0;
while (true)
{
std::vector<YulName> removed;
for (auto it = cg.functionCalls.begin(); it != cg.functionCalls.end();)
{
auto const& [fun, callees] = *it;
if (callees.empty())
{
removed.emplace_back(fun);
depths[fun] = currentDepth;
it = cg.functionCalls.erase(it);
}
else
++it;
}
for (auto& call: cg.functionCalls)
for (YulName toBeRemoved: removed)
ranges::actions::remove(call.second, toBeRemoved);
currentDepth++;
if (removed.empty())
break;
}
// Only recursive functions left here.
for (auto const& fun: cg.functionCalls)
depths[fun.first] = currentDepth;
return depths;
}
bool FullInliner::shallInline(FunctionCall const& _funCall, YulName _callSite)
{
// No recursive inlining
if (_funCall.functionName.name == _callSite)
return false;
FunctionDefinition* calledFunction = function(_funCall.functionName.name);
if (!calledFunction)
return false;
if (m_noInlineFunctions.count(_funCall.functionName.name) || recursive(*calledFunction))
return false;
// No inlining of calls where argument expressions may have side-effects.
// To avoid running into this, make sure that ExpressionSplitter runs before FullInliner.
for (auto const& argument: _funCall.arguments)
if (!std::holds_alternative<Literal>(argument) && !std::holds_alternative<Identifier>(argument))
return false;
// Inline really, really tiny functions
size_t size = m_functionSizes.at(calledFunction->name);
if (size <= 1)
return true;
// In the first pass, only inline tiny functions.
if (m_pass == Pass::InlineTiny)
return false;
bool aggressiveInlining = true;
if (
EVMDialect const* evmDialect = dynamic_cast<EVMDialect const*>(&m_dialect);
!evmDialect || !evmDialect->providesObjectAccess() || evmDialect->evmVersion() <= langutil::EVMVersion::homestead()
)
// No aggressive inlining with the old code transform.
aggressiveInlining = false;
// No aggressive inlining, if we cannot perform stack-to-memory.
if (!m_hasMemoryGuard || m_recursiveFunctions.count(_callSite))
aggressiveInlining = false;
if (!aggressiveInlining && m_functionSizes.at(_callSite) > 45)
return false;
if (m_singleUse.count(calledFunction->name))
return true;
// Constant arguments might provide a means for further optimization, so they cause a bonus.
bool constantArg = false;
for (auto const& argument: _funCall.arguments)
if (std::holds_alternative<Literal>(argument) || (
std::holds_alternative<Identifier>(argument) &&
m_constants.count(std::get<Identifier>(argument).name)
))
{
constantArg = true;
break;
}
return (size < (aggressiveInlining ? 8u : 6u) || (constantArg && size < (aggressiveInlining ? 16u : 12u)));
}
void FullInliner::tentativelyUpdateCodeSize(YulName _function, YulName _callSite)
{
m_functionSizes.at(_callSite) += m_functionSizes.at(_function);
}
void FullInliner::updateCodeSize(FunctionDefinition const& _fun)
{
m_functionSizes[_fun.name] = CodeSize::codeSize(_fun.body);
}
void FullInliner::handleBlock(YulName _currentFunctionName, Block& _block)
{
InlineModifier{*this, m_nameDispenser, _currentFunctionName, m_dialect}(_block);
}
bool FullInliner::recursive(FunctionDefinition const& _fun) const
{
std::map<YulName, size_t> references = ReferencesCounter::countReferences(_fun);
return references[_fun.name] > 0;
}
void InlineModifier::operator()(Block& _block)
{
std::function<std::optional<std::vector<Statement>>(Statement&)> f = [&](Statement& _statement) -> std::optional<std::vector<Statement>> {
visit(_statement);
return tryInlineStatement(_statement);
};
util::iterateReplacing(_block.statements, f);
}
std::optional<std::vector<Statement>> InlineModifier::tryInlineStatement(Statement& _statement)
{
// Only inline for expression statements, assignments and variable declarations.
Expression* e = std::visit(util::GenericVisitor{
util::VisitorFallback<Expression*>{},
[](ExpressionStatement& _s) { return &_s.expression; },
[](Assignment& _s) { return _s.value.get(); },
[](VariableDeclaration& _s) { return _s.value.get(); }
}, _statement);
if (e)
{
// Only inline direct function calls.
FunctionCall* funCall = std::visit(util::GenericVisitor{
util::VisitorFallback<FunctionCall*>{},
[](FunctionCall& _e) { return &_e; }
}, *e);
if (funCall && m_driver.shallInline(*funCall, m_currentFunction))
return performInline(_statement, *funCall);
}
return {};
}
std::vector<Statement> InlineModifier::performInline(Statement& _statement, FunctionCall& _funCall)
{
std::vector<Statement> newStatements;
std::map<YulName, YulName> variableReplacements;
FunctionDefinition* function = m_driver.function(_funCall.functionName.name);
assertThrow(!!function, OptimizerException, "Attempt to inline invalid function.");
m_driver.tentativelyUpdateCodeSize(function->name, m_currentFunction);
// helper function to create a new variable that is supposed to model
// an existing variable.
auto newVariable = [&](NameWithDebugData const& _existingVariable, Expression* _value) {
YulName newName = m_nameDispenser.newName(_existingVariable.name);
variableReplacements[_existingVariable.name] = newName;
VariableDeclaration varDecl{_funCall.debugData, {{_funCall.debugData, newName}}, {}};
if (_value)
varDecl.value = std::make_unique<Expression>(std::move(*_value));
else
varDecl.value = std::make_unique<Expression>(m_dialect.zeroLiteral());
newStatements.emplace_back(std::move(varDecl));
};
for (auto&& [parameter, argument]: ranges::views::zip(function->parameters, _funCall.arguments) | ranges::views::reverse)
newVariable(parameter, &argument);
for (auto const& var: function->returnVariables)
newVariable(var, nullptr);
Statement newBody = BodyCopier(m_nameDispenser, variableReplacements)(function->body);
newStatements += std::move(std::get<Block>(newBody).statements);
std::visit(util::GenericVisitor{
util::VisitorFallback<>{},
[&](Assignment& _assignment)
{
for (size_t i = 0; i < _assignment.variableNames.size(); ++i)
newStatements.emplace_back(Assignment{
_assignment.debugData,
{_assignment.variableNames[i]},
std::make_unique<Expression>(Identifier{
_assignment.debugData,
variableReplacements.at(function->returnVariables[i].name)
})
});
},
[&](VariableDeclaration& _varDecl)
{
for (size_t i = 0; i < _varDecl.variables.size(); ++i)
newStatements.emplace_back(VariableDeclaration{
_varDecl.debugData,
{std::move(_varDecl.variables[i])},
std::make_unique<Expression>(Identifier{
_varDecl.debugData,
variableReplacements.at(function->returnVariables[i].name)
})
});
}
// nothing to be done for expression statement
}, _statement);
return newStatements;
}
Statement BodyCopier::operator()(VariableDeclaration const& _varDecl)
{
for (auto const& var: _varDecl.variables)
m_variableReplacements[var.name] = m_nameDispenser.newName(var.name);
return ASTCopier::operator()(_varDecl);
}
Statement BodyCopier::operator()(FunctionDefinition const&)
{
assertThrow(false, OptimizerException, "Function hoisting has to be done before function inlining.");
return {};
}
YulName BodyCopier::translateIdentifier(YulName _name)
{
return util::valueOrDefault(m_variableReplacements, _name, _name);
}
| 12,112
|
C++
|
.cpp
| 313
| 36.079872
| 139
| 0.749681
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,104
|
VarNameCleaner.cpp
|
ethereum_solidity/libyul/optimiser/VarNameCleaner.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/VarNameCleaner.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <algorithm>
#include <cctype>
#include <climits>
#include <iterator>
#include <string>
#include <regex>
#include <limits>
using namespace solidity::yul;
VarNameCleaner::VarNameCleaner(
Block const& _ast,
Dialect const& _dialect,
std::set<YulName> _namesToKeep
):
m_dialect{_dialect},
m_namesToKeep{std::move(_namesToKeep)},
m_translatedNames{}
{
for (auto const& statement: _ast.statements)
if (std::holds_alternative<FunctionDefinition>(statement))
m_namesToKeep.insert(std::get<FunctionDefinition>(statement).name);
m_usedNames = m_namesToKeep;
}
void VarNameCleaner::operator()(FunctionDefinition& _funDef)
{
yulAssert(!m_insideFunction, "");
m_insideFunction = true;
std::set<YulName> globalUsedNames = std::move(m_usedNames);
m_usedNames = m_namesToKeep;
std::map<YulName, YulName> globalTranslatedNames;
swap(globalTranslatedNames, m_translatedNames);
renameVariables(_funDef.parameters);
renameVariables(_funDef.returnVariables);
ASTModifier::operator()(_funDef);
swap(globalUsedNames, m_usedNames);
swap(globalTranslatedNames, m_translatedNames);
m_insideFunction = false;
}
void VarNameCleaner::operator()(VariableDeclaration& _varDecl)
{
renameVariables(_varDecl.variables);
ASTModifier::operator()(_varDecl);
}
void VarNameCleaner::renameVariables(std::vector<NameWithDebugData>& _variables)
{
for (NameWithDebugData& variable: _variables)
{
auto newName = findCleanName(variable.name);
if (newName != variable.name)
{
m_translatedNames[variable.name] = newName;
variable.name = newName;
}
m_usedNames.insert(variable.name);
}
}
void VarNameCleaner::operator()(Identifier& _identifier)
{
auto name = m_translatedNames.find(_identifier.name);
if (name != m_translatedNames.end())
_identifier.name = name->second;
}
YulName VarNameCleaner::findCleanName(YulName const& _name) const
{
auto newName = stripSuffix(_name);
if (!isUsedName(newName))
return newName;
// create new name with suffix (by finding a free identifier)
for (size_t i = 1; i < std::numeric_limits<decltype(i)>::max(); ++i)
{
YulName newNameSuffixed = YulName{newName.str() + "_" + std::to_string(i)};
if (!isUsedName(newNameSuffixed))
return newNameSuffixed;
}
yulAssert(false, "Exhausted by attempting to find an available suffix.");
}
bool VarNameCleaner::isUsedName(YulName const& _name) const
{
return isRestrictedIdentifier(m_dialect, _name) || m_usedNames.count(_name);
}
YulName VarNameCleaner::stripSuffix(YulName const& _name) const
{
static std::regex const suffixRegex("(_+[0-9]+)+$");
std::smatch suffixMatch;
if (regex_search(_name.str(), suffixMatch, suffixRegex))
return {YulName{suffixMatch.prefix().str()}};
return _name;
}
| 3,549
|
C++
|
.cpp
| 105
| 31.809524
| 80
| 0.770152
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,105
|
KnowledgeBase.cpp
|
ethereum_solidity/libyul/optimiser/KnowledgeBase.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Class that can answer questions about values of variables and their relations.
*/
#include <libyul/optimiser/KnowledgeBase.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libsolutil/CommonData.h>
#include <variant>
using namespace solidity;
using namespace solidity::yul;
KnowledgeBase::KnowledgeBase(std::map<YulName, AssignedValue> const& _ssaValues):
m_valuesAreSSA(true),
m_variableValues([_ssaValues](YulName _var) { return util::valueOrNullptr(_ssaValues, _var); })
{}
bool KnowledgeBase::knownToBeDifferent(YulName _a, YulName _b)
{
if (std::optional<u256> difference = differenceIfKnownConstant(_a, _b))
return difference != 0;
return false;
}
std::optional<u256> KnowledgeBase::differenceIfKnownConstant(YulName _a, YulName _b)
{
VariableOffset offA = explore(_a);
VariableOffset offB = explore(_b);
if (offA.reference == offB.reference)
return offA.offset - offB.offset;
else
return std::nullopt;
}
bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulName _a, YulName _b)
{
if (std::optional<u256> difference = differenceIfKnownConstant(_a, _b))
return difference >= 32 && difference <= u256(0) - 32;
return false;
}
bool KnowledgeBase::knownToBeZero(YulName _a)
{
return valueIfKnownConstant(_a) == 0;
}
std::optional<u256> KnowledgeBase::valueIfKnownConstant(YulName _a)
{
return explore(_a).absoluteValue();
}
std::optional<u256> KnowledgeBase::valueIfKnownConstant(Expression const& _expression)
{
if (Identifier const* ident = std::get_if<Identifier>(&_expression))
return valueIfKnownConstant(ident->name);
else if (Literal const* lit = std::get_if<Literal>(&_expression))
return lit->value.value();
else
return std::nullopt;
}
KnowledgeBase::VariableOffset KnowledgeBase::explore(YulName _var)
{
Expression const* value = nullptr;
if (m_valuesAreSSA)
{
// In SSA, a once determined offset is always valid, so we first see
// if we already computed it.
if (VariableOffset const* varOff = util::valueOrNullptr(m_offsets, _var))
return *varOff;
value = valueOf(_var);
}
else
{
// For non-SSA, we query the value first so that the variable is reset if it has changed
// since the last call.
value = valueOf(_var);
if (VariableOffset const* varOff = util::valueOrNullptr(m_offsets, _var))
return *varOff;
}
if (value)
if (std::optional<VariableOffset> offset = explore(*value))
return setOffset(_var, *offset);
return setOffset(_var, VariableOffset{_var, 0});
}
std::optional<KnowledgeBase::VariableOffset> KnowledgeBase::explore(Expression const& _value)
{
if (Literal const* literal = std::get_if<Literal>(&_value))
return VariableOffset{YulName{}, literal->value.value()};
else if (Identifier const* identifier = std::get_if<Identifier>(&_value))
return explore(identifier->name);
else if (FunctionCall const* f = std::get_if<FunctionCall>(&_value))
{
if (f->functionName.name == "add"_yulname)
{
if (std::optional<VariableOffset> a = explore(f->arguments[0]))
if (std::optional<VariableOffset> b = explore(f->arguments[1]))
{
u256 offset = a->offset + b->offset;
if (a->isAbsolute())
// a is constant
return VariableOffset{b->reference, offset};
else if (b->isAbsolute())
// b is constant
return VariableOffset{a->reference, offset};
}
}
else if (f->functionName.name == "sub"_yulname)
if (std::optional<VariableOffset> a = explore(f->arguments[0]))
if (std::optional<VariableOffset> b = explore(f->arguments[1]))
{
u256 offset = a->offset - b->offset;
if (a->reference == b->reference)
return VariableOffset{YulName{}, offset};
else if (b->isAbsolute())
// b is constant
return VariableOffset{a->reference, offset};
}
}
return std::nullopt;
}
Expression const* KnowledgeBase::valueOf(YulName _var)
{
AssignedValue const* assignedValue = m_variableValues(_var);
Expression const* currentValue = assignedValue ? assignedValue->value : nullptr;
if (m_valuesAreSSA)
return currentValue;
Expression const* lastValue = m_lastKnownValue[_var];
if (lastValue != currentValue)
reset(_var);
m_lastKnownValue[_var] = currentValue;
return currentValue;
}
void KnowledgeBase::reset(YulName _var)
{
yulAssert(!m_valuesAreSSA);
m_lastKnownValue.erase(_var);
if (VariableOffset const* offset = util::valueOrNullptr(m_offsets, _var))
{
// Remove var from its group
if (!offset->isAbsolute())
m_groupMembers[offset->reference].erase(_var);
m_offsets.erase(_var);
}
if (std::set<YulName>* group = util::valueOrNullptr(m_groupMembers, _var))
{
// _var was a representative, we might have to find a new one.
if (!group->empty())
{
YulName newRepresentative = *group->begin();
yulAssert(newRepresentative != _var);
u256 newOffset = m_offsets[newRepresentative].offset;
// newOffset = newRepresentative - _var
for (YulName groupMember: *group)
{
yulAssert(m_offsets[groupMember].reference == _var);
m_offsets[groupMember].reference = newRepresentative;
// groupMember = _var + m_offsets[groupMember].offset (old)
// = newRepresentative - newOffset + m_offsets[groupMember].offset (old)
// so subtracting newOffset from .offset yields the original relation again,
// just with _var replaced by newRepresentative
m_offsets[groupMember].offset -= newOffset;
}
m_groupMembers[newRepresentative] = std::move(*group);
}
m_groupMembers.erase(_var);
}
}
KnowledgeBase::VariableOffset KnowledgeBase::setOffset(YulName _variable, VariableOffset _value)
{
m_offsets[_variable] = _value;
// Constants are not tracked in m_groupMembers because
// the "representative" can never be reset.
if (!_value.reference.empty())
m_groupMembers[_value.reference].insert(_variable);
return _value;
}
| 6,548
|
C++
|
.cpp
| 183
| 33.016393
| 96
| 0.734575
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,106
|
ControlFlowSimplifier.cpp
|
ethereum_solidity/libyul/optimiser/ControlFlowSimplifier.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/ControlFlowSimplifier.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libyul/Dialect.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Visitor.h>
#include <range/v3/action/remove_if.hpp>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::yul;
using OptionalStatements = std::optional<std::vector<Statement>>;
namespace
{
ExpressionStatement makeDiscardCall(
langutil::DebugData::ConstPtr const& _debugData,
BuiltinFunction const& _discardFunction,
Expression&& _expression
)
{
return {_debugData, FunctionCall{
_debugData,
Identifier{_debugData, YulName{_discardFunction.name}},
{std::move(_expression)}
}};
}
void removeEmptyDefaultFromSwitch(Switch& _switchStmt)
{
ranges::actions::remove_if(
_switchStmt.cases,
[](Case const& _case) { return !_case.value && _case.body.statements.empty(); }
);
}
void removeEmptyCasesFromSwitch(Switch& _switchStmt)
{
if (hasDefaultCase(_switchStmt))
return;
ranges::actions::remove_if(
_switchStmt.cases,
[](Case const& _case) { return _case.body.statements.empty(); }
);
}
}
void ControlFlowSimplifier::run(OptimiserStepContext& _context, Block& _ast)
{
ControlFlowSimplifier{_context.dialect}(_ast);
}
void ControlFlowSimplifier::operator()(Block& _block)
{
simplify(_block.statements);
}
void ControlFlowSimplifier::operator()(FunctionDefinition& _funDef)
{
ASTModifier::operator()(_funDef);
if (!_funDef.body.statements.empty() && std::holds_alternative<Leave>(_funDef.body.statements.back()))
_funDef.body.statements.pop_back();
}
void ControlFlowSimplifier::visit(Statement& _st)
{
if (std::holds_alternative<ForLoop>(_st))
{
ForLoop& forLoop = std::get<ForLoop>(_st);
yulAssert(forLoop.pre.statements.empty(), "");
size_t outerBreak = m_numBreakStatements;
size_t outerContinue = m_numContinueStatements;
m_numBreakStatements = 0;
m_numContinueStatements = 0;
ASTModifier::visit(_st);
if (!forLoop.body.statements.empty())
{
bool isTerminating = false;
TerminationFinder::ControlFlow controlFlow = TerminationFinder{m_dialect}.controlFlowKind(forLoop.body.statements.back());
if (controlFlow == TerminationFinder::ControlFlow::Break)
{
isTerminating = true;
--m_numBreakStatements;
}
else if (
controlFlow == TerminationFinder::ControlFlow::Terminate ||
controlFlow == TerminationFinder::ControlFlow::Leave
)
isTerminating = true;
if (isTerminating && m_numContinueStatements == 0 && m_numBreakStatements == 0)
{
If replacement{forLoop.debugData, std::move(forLoop.condition), std::move(forLoop.body)};
if (controlFlow == TerminationFinder::ControlFlow::Break)
replacement.body.statements.resize(replacement.body.statements.size() - 1);
_st = std::move(replacement);
}
}
m_numBreakStatements = outerBreak;
m_numContinueStatements = outerContinue;
}
else
ASTModifier::visit(_st);
}
void ControlFlowSimplifier::simplify(std::vector<yul::Statement>& _statements)
{
GenericVisitor visitor{
VisitorFallback<OptionalStatements>{},
[&](If& _ifStmt) -> OptionalStatements {
if (_ifStmt.body.statements.empty() && m_dialect.discardFunctionHandle())
{
OptionalStatements s = std::vector<Statement>{};
s->emplace_back(makeDiscardCall(
_ifStmt.debugData,
m_dialect.builtin(*m_dialect.discardFunctionHandle()),
std::move(*_ifStmt.condition)
));
return s;
}
return {};
},
[&](Switch& _switchStmt) -> OptionalStatements {
removeEmptyDefaultFromSwitch(_switchStmt);
removeEmptyCasesFromSwitch(_switchStmt);
if (_switchStmt.cases.empty())
return reduceNoCaseSwitch(_switchStmt);
else if (_switchStmt.cases.size() == 1)
return reduceSingleCaseSwitch(_switchStmt);
return {};
}
};
iterateReplacing(
_statements,
[&](Statement& _stmt) -> OptionalStatements
{
OptionalStatements result = std::visit(visitor, _stmt);
if (result)
simplify(*result);
else
visit(_stmt);
return result;
}
);
}
OptionalStatements ControlFlowSimplifier::reduceNoCaseSwitch(Switch& _switchStmt) const
{
yulAssert(_switchStmt.cases.empty(), "Expected no case!");
std::optional<BuiltinHandle> discardFunctionHandle =
m_dialect.discardFunctionHandle();
if (!discardFunctionHandle)
return {};
return make_vector<Statement>(makeDiscardCall(
debugDataOf(*_switchStmt.expression),
m_dialect.builtin(*discardFunctionHandle),
std::move(*_switchStmt.expression)
));
}
OptionalStatements ControlFlowSimplifier::reduceSingleCaseSwitch(Switch& _switchStmt) const
{
yulAssert(_switchStmt.cases.size() == 1, "Expected only one case!");
auto& switchCase = _switchStmt.cases.front();
langutil::DebugData::ConstPtr debugData = debugDataOf(*_switchStmt.expression);
if (switchCase.value)
{
if (!m_dialect.equalityFunctionHandle())
return {};
return make_vector<Statement>(If{
std::move(_switchStmt.debugData),
std::make_unique<Expression>(FunctionCall{
debugData,
Identifier{debugData, YulName{m_dialect.builtin(*m_dialect.equalityFunctionHandle()).name}},
{std::move(*switchCase.value), std::move(*_switchStmt.expression)}
}),
std::move(switchCase.body)
});
}
else
{
if (!m_dialect.discardFunctionHandle())
return {};
return make_vector<Statement>(
makeDiscardCall(
debugData,
m_dialect.builtin(*m_dialect.discardFunctionHandle()),
std::move(*_switchStmt.expression)
),
std::move(switchCase.body)
);
}
}
| 6,292
|
C++
|
.cpp
| 197
| 29.086294
| 125
| 0.750536
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,110
|
LoadResolver.cpp
|
ethereum_solidity/libyul/optimiser/LoadResolver.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimisation stage that replaces expressions of type ``sload(x)`` by the value
* currently stored in storage, if known.
*/
#include <libyul/optimiser/LoadResolver.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/EVMMetrics.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/SideEffects.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libevmasm/GasMeter.h>
#include <libsolutil/Keccak256.h>
#include <limits>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::evmasm;
using namespace solidity::yul;
void LoadResolver::run(OptimiserStepContext& _context, Block& _ast)
{
bool containsMSize = MSizeFinder::containsMSize(_context.dialect, _ast);
LoadResolver{
_context.dialect,
SideEffectsPropagator::sideEffects(_context.dialect, CallGraphGenerator::callGraph(_ast)),
containsMSize,
_context.expectedExecutionsPerDeployment
}(_ast);
}
void LoadResolver::visit(Expression& _e)
{
DataFlowAnalyzer::visit(_e);
if (FunctionCall const* funCall = std::get_if<FunctionCall>(&_e))
{
if (funCall->functionName.name == m_loadFunctionName[static_cast<unsigned>(StoreLoadLocation::Memory)])
tryResolve(_e, StoreLoadLocation::Memory, funCall->arguments);
else if (funCall->functionName.name == m_loadFunctionName[static_cast<unsigned>(StoreLoadLocation::Storage)])
tryResolve(_e, StoreLoadLocation::Storage, funCall->arguments);
else if (!m_containsMSize && funCall->functionName.name.str() == m_dialect.builtin(*m_dialect.hashFunctionHandle()).name)
{
Identifier const* start = std::get_if<Identifier>(&funCall->arguments.at(0));
Identifier const* length = std::get_if<Identifier>(&funCall->arguments.at(1));
if (start && length)
if (auto const& value = keccakValue(start->name, length->name))
if (inScope(*value))
{
_e = Identifier{debugDataOf(_e), *value};
return;
}
tryEvaluateKeccak(_e, funCall->arguments);
}
}
}
void LoadResolver::tryResolve(
Expression& _e,
StoreLoadLocation _location,
std::vector<Expression> const& _arguments
)
{
if (_arguments.empty() || !std::holds_alternative<Identifier>(_arguments.at(0)))
return;
YulName key = std::get<Identifier>(_arguments.at(0)).name;
if (_location == StoreLoadLocation::Storage)
{
if (auto value = storageValue(key))
if (inScope(*value))
_e = Identifier{debugDataOf(_e), *value};
}
else if (!m_containsMSize && _location == StoreLoadLocation::Memory)
if (auto value = memoryValue(key))
if (inScope(*value))
_e = Identifier{debugDataOf(_e), *value};
}
void LoadResolver::tryEvaluateKeccak(
Expression& _e,
std::vector<Expression> const& _arguments
)
{
yulAssert(_arguments.size() == 2, "");
Identifier const* memoryKey = std::get_if<Identifier>(&_arguments.at(0));
Identifier const* length = std::get_if<Identifier>(&_arguments.at(1));
if (!memoryKey || !length)
return;
// The costs are only correct for hashes of 32 bytes or 1 word (when rounded up).
GasMeter gasMeter{
dynamic_cast<EVMDialect const&>(m_dialect),
!m_expectedExecutionsPerDeployment,
m_expectedExecutionsPerDeployment ? *m_expectedExecutionsPerDeployment : 1
};
bigint costOfKeccak = gasMeter.costs(_e);
bigint costOfLiteral = gasMeter.costs(
Literal{
{},
LiteralKind::Number,
// a dummy 256-bit number to represent the Keccak256 hash.
LiteralValue{std::numeric_limits<u256>::max()}
}
);
// We skip if there are no net gas savings.
// Note that for default `m_runs = 200`, the values are
// `costOfLiteral = 7200` and `costOfKeccak = 9000` for runtime context.
// For creation context: `costOfLiteral = 531` and `costOfKeccak = 90`.
if (costOfLiteral > costOfKeccak)
return;
std::optional<YulName> value = memoryValue(memoryKey->name);
if (value && inScope(*value))
{
std::optional<u256> memoryContent = valueOfIdentifier(*value);
std::optional<u256> byteLength = valueOfIdentifier(length->name);
if (memoryContent && byteLength && *byteLength <= 32)
{
bytes contentAsBytes = toBigEndian(*memoryContent);
contentAsBytes.resize(static_cast<size_t>(*byteLength));
u256 const contentHash (keccak256(contentAsBytes));
_e = Literal{
debugDataOf(_e),
LiteralKind::Number,
LiteralValue{contentHash}
};
}
}
}
| 5,090
|
C++
|
.cpp
| 137
| 34.547445
| 123
| 0.746453
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,111
|
UnusedFunctionParameterPruner.cpp
|
ethereum_solidity/libyul/optimiser/UnusedFunctionParameterPruner.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* UnusedFunctionParameterPruner: Optimiser step that removes unused parameters from function
* definition.
*/
#include <libyul/optimiser/UnusedFunctionParameterPruner.h>
#include <libyul/optimiser/UnusedFunctionsCommon.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/NameDisplacer.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/YulName.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
#include <range/v3/algorithm/all_of.hpp>
#include <optional>
#include <variant>
using namespace solidity::util;
using namespace solidity::yul;
using namespace solidity::yul::unusedFunctionsCommon;
void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ast)
{
std::map<YulName, size_t> references = VariableReferencesCounter::countReferences(_ast);
auto used = [&](auto v) -> bool { return references.count(v.name); };
// Function name and a pair of boolean masks, the first corresponds to parameters and the second
// corresponds to returnVariables.
//
// For the first vector in the pair, a value `false` at index `i` indicates that the function
// argument at index `i` in `FunctionDefinition::parameters` is unused inside the function body.
//
// Similarly for the second vector in the pair, a value `false` at index `i` indicates that the
// return parameter at index `i` in `FunctionDefinition::returnVariables` is unused inside
// function body.
std::map<YulName, std::pair<std::vector<bool>, std::vector<bool>>> usedParametersAndReturnVariables;
// Step 1 of UnusedFunctionParameterPruner: Find functions whose parameters (both arguments and
// return-parameters) are not used in its body.
for (auto const& statement: _ast.statements)
if (std::holds_alternative<FunctionDefinition>(statement))
{
FunctionDefinition const& f = std::get<FunctionDefinition>(statement);
if (tooSimpleToBePruned(f) || ranges::all_of(f.parameters + f.returnVariables, used))
continue;
usedParametersAndReturnVariables[f.name] = {
applyMap(f.parameters, used),
applyMap(f.returnVariables, used)
};
}
std::set<YulName> functionNamesToFree = util::keys(usedParametersAndReturnVariables);
// Step 2 of UnusedFunctionParameterPruner: Renames the function and replaces all references to
// the function, say `f`, by its new name, say `f_1`.
NameDisplacer replace{_context.dispenser, functionNamesToFree};
replace(_ast);
// Inverse-Map of the above translations. In the above example, this will store an element with
// key `f_1` and value `f`.
std::map<YulName, YulName> newToOriginalNames = invertMap(replace.translations());
// Step 3 of UnusedFunctionParameterPruner: introduce a new function in the block with body of
// the old one. Replace the body of the old one with a function call to the new one with reduced
// parameters.
//
// For example: introduce a new 'linking' function `f` with the same the body as `f_1`, but with
// reduced parameters, i.e., `function f() -> y { y := 1 }`. Now replace the body of `f_1` with
// a call to `f`, i.e., `f_1(x) -> y { y := f() }`.
iterateReplacing(_ast.statements, [&](Statement& _s) -> std::optional<std::vector<Statement>> {
if (std::holds_alternative<FunctionDefinition>(_s))
{
// The original function except that it has a new name (e.g., `f_1`)
FunctionDefinition& originalFunction = std::get<FunctionDefinition>(_s);
if (newToOriginalNames.count(originalFunction.name))
{
YulName linkingFunctionName = originalFunction.name;
YulName originalFunctionName = newToOriginalNames.at(linkingFunctionName);
std::pair<std::vector<bool>, std::vector<bool>> used =
usedParametersAndReturnVariables.at(originalFunctionName);
FunctionDefinition linkingFunction = createLinkingFunction(
originalFunction,
used,
originalFunctionName,
linkingFunctionName,
_context.dispenser
);
originalFunction.name = originalFunctionName;
originalFunction.parameters =
filter(originalFunction.parameters, used.first);
originalFunction.returnVariables =
filter(originalFunction.returnVariables, used.second);
return make_vector<Statement>(std::move(originalFunction), std::move(linkingFunction));
}
}
return std::nullopt;
});
}
| 5,015
|
C++
|
.cpp
| 104
| 45.326923
| 101
| 0.762324
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,112
|
CallGraphGenerator.cpp
|
ethereum_solidity/libyul/optimiser/CallGraphGenerator.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Specific AST walker that generates the call graph.
*/
#include <libyul/AST.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libsolutil/CommonData.h>
#include <stack>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
namespace
{
// TODO: This algorithm is non-optimal.
struct CallGraphCycleFinder
{
CallGraph const& callGraph;
std::set<YulName> containedInCycle{};
std::set<YulName> visited{};
std::vector<YulName> currentPath{};
void visit(YulName _function)
{
if (visited.count(_function))
return;
if (
auto it = find(currentPath.begin(), currentPath.end(), _function);
it != currentPath.end()
)
containedInCycle.insert(it, currentPath.end());
else
{
currentPath.emplace_back(_function);
if (callGraph.functionCalls.count(_function))
for (auto const& child: callGraph.functionCalls.at(_function))
visit(child);
currentPath.pop_back();
visited.insert(_function);
}
}
};
}
std::set<YulName> CallGraph::recursiveFunctions() const
{
CallGraphCycleFinder cycleFinder{*this};
// Visiting the root only is not enough, since there may be disconnected recursive functions.
for (auto const& call: functionCalls)
cycleFinder.visit(call.first);
return cycleFinder.containedInCycle;
}
CallGraph CallGraphGenerator::callGraph(Block const& _ast)
{
CallGraphGenerator gen;
gen(_ast);
return std::move(gen.m_callGraph);
}
void CallGraphGenerator::operator()(FunctionCall const& _functionCall)
{
auto& functionCalls = m_callGraph.functionCalls[m_currentFunction];
if (!util::contains(functionCalls, _functionCall.functionName.name))
functionCalls.emplace_back(_functionCall.functionName.name);
ASTWalker::operator()(_functionCall);
}
void CallGraphGenerator::operator()(ForLoop const& _forLoop)
{
m_callGraph.functionsWithLoops.insert(m_currentFunction);
ASTWalker::operator()(_forLoop);
}
void CallGraphGenerator::operator()(FunctionDefinition const& _functionDefinition)
{
YulName previousFunction = m_currentFunction;
m_currentFunction = _functionDefinition.name;
yulAssert(m_callGraph.functionCalls.count(m_currentFunction) == 0, "");
m_callGraph.functionCalls[m_currentFunction] = {};
ASTWalker::operator()(_functionDefinition);
m_currentFunction = previousFunction;
}
CallGraphGenerator::CallGraphGenerator()
{
m_callGraph.functionCalls[YulName{}] = {};
}
| 3,077
|
C++
|
.cpp
| 93
| 30.978495
| 94
| 0.781408
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,113
|
StackToMemoryMover.cpp
|
ethereum_solidity/libyul/optimiser/StackToMemoryMover.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libyul/optimiser/StackToMemoryMover.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libsolutil/CommonData.h>
#include <range/v3/algorithm/none_of.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/zip.hpp>
#include <range/v3/range/conversion.hpp>
using namespace solidity;
using namespace solidity::yul;
namespace
{
std::vector<Statement> generateMemoryStore(
Dialect const& _dialect,
langutil::DebugData::ConstPtr const& _debugData,
LiteralValue const& _mpos,
Expression _value
)
{
std::optional<BuiltinHandle> memoryStoreFunctionHandle = _dialect.memoryStoreFunctionHandle();
yulAssert(memoryStoreFunctionHandle);
std::vector<Statement> result;
result.emplace_back(ExpressionStatement{_debugData, FunctionCall{
_debugData,
Identifier{_debugData, YulName{_dialect.builtin(*memoryStoreFunctionHandle).name}},
{
Literal{_debugData, LiteralKind::Number, _mpos},
std::move(_value)
}
}});
return result;
}
FunctionCall generateMemoryLoad(Dialect const& _dialect, langutil::DebugData::ConstPtr const& _debugData, LiteralValue const& _mpos)
{
std::optional<BuiltinHandle> const& memoryLoadHandle = _dialect.memoryLoadFunctionHandle();
yulAssert(memoryLoadHandle);
return FunctionCall{
_debugData,
Identifier{_debugData, YulName{_dialect.builtin(*memoryLoadHandle).name}}, {
Literal{
_debugData,
LiteralKind::Number,
_mpos
}
}
};
}
}
void StackToMemoryMover::run(
OptimiserStepContext& _context,
u256 _reservedMemory,
std::map<YulName, uint64_t> const& _memorySlots,
uint64_t _numRequiredSlots,
Block& _block
)
{
VariableMemoryOffsetTracker memoryOffsetTracker(_reservedMemory, _memorySlots, _numRequiredSlots);
StackToMemoryMover stackToMemoryMover(
_context,
memoryOffsetTracker,
util::applyMap(
allFunctionDefinitions(_block),
util::mapTuple([](YulName _name, FunctionDefinition const* _funDef) {
return make_pair(_name, _funDef->returnVariables);
}),
std::map<YulName, NameWithDebugDataList>{}
)
);
stackToMemoryMover(_block);
_block.statements += std::move(stackToMemoryMover.m_newFunctionDefinitions);
}
StackToMemoryMover::StackToMemoryMover(
OptimiserStepContext& _context,
VariableMemoryOffsetTracker const& _memoryOffsetTracker,
std::map<YulName, NameWithDebugDataList> _functionReturnVariables
):
m_context(_context),
m_memoryOffsetTracker(_memoryOffsetTracker),
m_nameDispenser(_context.dispenser),
m_functionReturnVariables(std::move(_functionReturnVariables))
{
auto const* evmDialect = dynamic_cast<EVMDialect const*>(&_context.dialect);
yulAssert(
evmDialect && evmDialect->providesObjectAccess(),
"StackToMemoryMover can only be run on objects using the EVMDialect with object access."
);
}
void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition)
{
// It is important to first visit the function body, so that it doesn't replace the memory inits for
// variable arguments we might generate below.
ASTModifier::operator()(_functionDefinition);
std::vector<Statement> memoryVariableInits;
// All function parameters with a memory slot are moved at the beginning of the function body.
for (NameWithDebugData const& param: _functionDefinition.parameters)
if (auto slot = m_memoryOffsetTracker(param.name))
memoryVariableInits += generateMemoryStore(
m_context.dialect,
param.debugData,
*slot,
Identifier{param.debugData, param.name}
);
// All memory return variables have to be initialized to zero in memory.
for (NameWithDebugData const& returnVariable: _functionDefinition.returnVariables)
if (auto slot = m_memoryOffsetTracker(returnVariable.name))
memoryVariableInits += generateMemoryStore(
m_context.dialect,
returnVariable.debugData,
*slot,
Literal{returnVariable.debugData, LiteralKind::Number, LiteralValue(u256{0})}
);
// Special case of a function with a single return argument that needs to move to memory.
if (_functionDefinition.returnVariables.size() == 1 && m_memoryOffsetTracker(_functionDefinition.returnVariables.front().name))
{
NameWithDebugDataList stackParameters = _functionDefinition.parameters | ranges::views::filter(
std::not_fn(m_memoryOffsetTracker)
) | ranges::to<NameWithDebugDataList>;
// Generate new function without return variable and with only the non-moved parameters.
YulName newFunctionName = m_context.dispenser.newName(_functionDefinition.name);
m_newFunctionDefinitions.emplace_back(FunctionDefinition{
_functionDefinition.debugData,
newFunctionName,
stackParameters,
{},
std::move(_functionDefinition.body)
});
// Generate new names for the arguments to maintain disambiguation.
std::map<YulName, YulName> newArgumentNames;
for (NameWithDebugData const& _var: stackParameters)
newArgumentNames[_var.name] = m_context.dispenser.newName(_var.name);
for (auto& parameter: _functionDefinition.parameters)
parameter.name = util::valueOrDefault(newArgumentNames, parameter.name, parameter.name);
// Replace original function by a call to the new function and an assignment to the return variable from memory.
_functionDefinition.body = Block{_functionDefinition.debugData, std::move(memoryVariableInits)};
_functionDefinition.body.statements.emplace_back(ExpressionStatement{
_functionDefinition.debugData,
FunctionCall{
_functionDefinition.debugData,
Identifier{_functionDefinition.debugData, newFunctionName},
stackParameters | ranges::views::transform([&](NameWithDebugData const& _arg) {
return Expression{Identifier{_arg.debugData, newArgumentNames.at(_arg.name)}};
}) | ranges::to<std::vector<Expression>>
}
});
_functionDefinition.body.statements.emplace_back(Assignment{
_functionDefinition.debugData,
{Identifier{_functionDefinition.debugData, _functionDefinition.returnVariables.front().name}},
std::make_unique<Expression>(generateMemoryLoad(
m_context.dialect,
_functionDefinition.debugData,
*m_memoryOffsetTracker(_functionDefinition.returnVariables.front().name)
))
});
return;
}
if (!memoryVariableInits.empty())
_functionDefinition.body.statements = std::move(memoryVariableInits) + std::move(_functionDefinition.body.statements);
_functionDefinition.returnVariables = _functionDefinition.returnVariables | ranges::views::filter(
std::not_fn(m_memoryOffsetTracker)
) | ranges::to<NameWithDebugDataList>;
}
void StackToMemoryMover::operator()(Block& _block)
{
using OptionalStatements = std::optional<std::vector<Statement>>;
auto rewriteAssignmentOrVariableDeclarationLeftHandSide = [this](
auto& _stmt,
auto& _lhsVars
) -> OptionalStatements {
using StatementType = std::decay_t<decltype(_stmt)>;
auto debugData = _stmt.debugData;
if (_lhsVars.size() == 1)
{
if (auto offset = m_memoryOffsetTracker(_lhsVars.front().name))
return generateMemoryStore(
m_context.dialect,
debugData,
*offset,
_stmt.value ? *std::move(_stmt.value) : Literal{debugData, LiteralKind::Number, LiteralValue(u256{0})}
);
else
return {};
}
std::vector<std::optional<LiteralValue>> rhsMemorySlots;
if (_stmt.value)
{
FunctionCall const* functionCall = std::get_if<FunctionCall>(_stmt.value.get());
yulAssert(functionCall, "");
if (m_context.dialect.findBuiltin(functionCall->functionName.name.str()))
rhsMemorySlots = std::vector<std::optional<LiteralValue>>(_lhsVars.size(), std::nullopt);
else
rhsMemorySlots =
m_functionReturnVariables.at(functionCall->functionName.name) |
ranges::views::transform(m_memoryOffsetTracker) |
ranges::to<std::vector<std::optional<LiteralValue>>>;
}
else
rhsMemorySlots = std::vector<std::optional<LiteralValue>>(_lhsVars.size(), std::nullopt);
// Nothing to do, if the right-hand-side remains entirely on the stack and
// none of the variables in the left-hand-side are moved.
if (
ranges::none_of(rhsMemorySlots, [](std::optional<LiteralValue> const& _slot) { return _slot.has_value(); }) &&
!util::contains_if(_lhsVars, m_memoryOffsetTracker)
)
return {};
std::vector<Statement> memoryAssignments;
std::vector<Statement> variableAssignments;
VariableDeclaration tempDecl{debugData, {}, std::move(_stmt.value)};
yulAssert(rhsMemorySlots.size() == _lhsVars.size(), "");
for (auto&& [lhsVar, rhsSlot]: ranges::views::zip(_lhsVars, rhsMemorySlots))
{
std::unique_ptr<Expression> rhs;
if (rhsSlot)
rhs = std::make_unique<Expression>(generateMemoryLoad(m_context.dialect, debugData, *rhsSlot));
else
{
YulName tempVarName = m_nameDispenser.newName(lhsVar.name);
tempDecl.variables.emplace_back(NameWithDebugData{lhsVar.debugData, tempVarName});
rhs = std::make_unique<Expression>(Identifier{debugData, tempVarName});
}
if (auto offset = m_memoryOffsetTracker(lhsVar.name))
memoryAssignments += generateMemoryStore(
m_context.dialect,
_stmt.debugData,
*offset,
std::move(*rhs)
);
else
variableAssignments.emplace_back(StatementType{
debugData,
{ std::move(lhsVar) },
std::move(rhs)
});
}
std::vector<Statement> result;
if (tempDecl.variables.empty())
result.emplace_back(ExpressionStatement{debugData, *std::move(tempDecl.value)});
else
result.emplace_back(std::move(tempDecl));
reverse(memoryAssignments.begin(), memoryAssignments.end());
result += std::move(memoryAssignments);
reverse(variableAssignments.begin(), variableAssignments.end());
result += std::move(variableAssignments);
return OptionalStatements{std::move(result)};
};
util::iterateReplacing(
_block.statements,
[&](Statement& _statement) -> OptionalStatements
{
visit(_statement);
if (auto* assignment = std::get_if<Assignment>(&_statement))
return rewriteAssignmentOrVariableDeclarationLeftHandSide(*assignment, assignment->variableNames);
else if (auto* varDecl = std::get_if<VariableDeclaration>(&_statement))
return rewriteAssignmentOrVariableDeclarationLeftHandSide(*varDecl, varDecl->variables);
return {};
}
);
}
void StackToMemoryMover::visit(Expression& _expression)
{
ASTModifier::visit(_expression);
if (Identifier* identifier = std::get_if<Identifier>(&_expression))
if (auto offset = m_memoryOffsetTracker(identifier->name))
_expression = generateMemoryLoad(m_context.dialect, identifier->debugData, *offset);
}
std::optional<LiteralValue> StackToMemoryMover::VariableMemoryOffsetTracker::operator()(YulName const& _variable) const
{
if (m_memorySlots.count(_variable))
{
uint64_t slot = m_memorySlots.at(_variable);
yulAssert(slot < m_numRequiredSlots, "");
auto const memoryOffset = m_reservedMemory + 32 * (m_numRequiredSlots - slot - 1);
return valueOfNumberLiteral(toCompactHexWithPrefix(memoryOffset));
}
else
return std::nullopt;
}
std::optional<LiteralValue> StackToMemoryMover::VariableMemoryOffsetTracker::operator()(NameWithDebugData const& _variable) const
{
return (*this)(_variable.name);
}
std::optional<LiteralValue> StackToMemoryMover::VariableMemoryOffsetTracker::operator()(Identifier const& _variable) const
{
return (*this)(_variable.name);
}
| 11,994
|
C++
|
.cpp
| 301
| 36.803987
| 132
| 0.769165
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,114
|
SSATransform.cpp
|
ethereum_solidity/libyul/optimiser/SSATransform.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that turns subsequent assignments to variable declarations
* and assignments.
*/
#include <libyul/optimiser/SSATransform.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::langutil;
namespace
{
/**
* First step of SSA transform: Introduces new SSA variables for each assignment or
* declaration of a variable to be replaced.
*/
class IntroduceSSA: public ASTModifier
{
public:
explicit IntroduceSSA(
NameDispenser& _nameDispenser,
std::set<YulName> const& _variablesToReplace
):
m_nameDispenser(_nameDispenser),
m_variablesToReplace(_variablesToReplace)
{ }
void operator()(Block& _block) override;
private:
NameDispenser& m_nameDispenser;
std::set<YulName> const& m_variablesToReplace;
};
void IntroduceSSA::operator()(Block& _block)
{
util::iterateReplacing(
_block.statements,
[&](Statement& _s) -> std::optional<std::vector<Statement>>
{
if (std::holds_alternative<VariableDeclaration>(_s))
{
VariableDeclaration& varDecl = std::get<VariableDeclaration>(_s);
if (varDecl.value)
visit(*varDecl.value);
bool needToReplaceSome = false;
for (auto const& var: varDecl.variables)
if (m_variablesToReplace.count(var.name))
needToReplaceSome = true;
if (!needToReplaceSome)
return {};
// Replace "let a := v" by "let a_1 := v let a := a_1"
// Replace "let a, b := v" by "let a_1, b_1 := v let a := a_1 let b := b_2"
langutil::DebugData::ConstPtr debugData = varDecl.debugData;
std::vector<Statement> statements;
statements.emplace_back(VariableDeclaration{debugData, {}, std::move(varDecl.value)});
NameWithDebugDataList newVariables;
for (auto const& var: varDecl.variables)
{
YulName oldName = var.name;
YulName newName = m_nameDispenser.newName(oldName);
newVariables.emplace_back(NameWithDebugData{debugData, newName});
statements.emplace_back(VariableDeclaration{
debugData,
{NameWithDebugData{debugData, oldName}},
std::make_unique<Expression>(Identifier{debugData, newName})
});
}
std::get<VariableDeclaration>(statements.front()).variables = std::move(newVariables);
return { std::move(statements) };
}
else if (std::holds_alternative<Assignment>(_s))
{
Assignment& assignment = std::get<Assignment>(_s);
visit(*assignment.value);
for (auto const& var: assignment.variableNames)
assertThrow(m_variablesToReplace.count(var.name), OptimizerException, "");
// Replace "a := v" by "let a_1 := v a := v"
// Replace "a, b := v" by "let a_1, b_1 := v a := a_1 b := b_2"
langutil::DebugData::ConstPtr debugData = assignment.debugData;
std::vector<Statement> statements;
statements.emplace_back(VariableDeclaration{debugData, {}, std::move(assignment.value)});
NameWithDebugDataList newVariables;
for (auto const& var: assignment.variableNames)
{
YulName oldName = var.name;
YulName newName = m_nameDispenser.newName(oldName);
newVariables.emplace_back(NameWithDebugData{debugData, newName});
statements.emplace_back(Assignment{
debugData,
{Identifier{debugData, oldName}},
std::make_unique<Expression>(Identifier{debugData, newName})
});
}
std::get<VariableDeclaration>(statements.front()).variables = std::move(newVariables);
return { std::move(statements) };
}
else
visit(_s);
return {};
}
);
}
/**
* Second step of SSA transform: Introduces new SSA variables at each control-flow join
* and at the beginning of functions.
*/
class IntroduceControlFlowSSA: public ASTModifier
{
public:
explicit IntroduceControlFlowSSA(
NameDispenser& _nameDispenser,
std::set<YulName> const& _variablesToReplace
):
m_nameDispenser(_nameDispenser),
m_variablesToReplace(_variablesToReplace)
{ }
void operator()(FunctionDefinition& _function) override;
void operator()(ForLoop& _forLoop) override;
void operator()(Switch& _switch) override;
void operator()(Block& _block) override;
private:
NameDispenser& m_nameDispenser;
std::set<YulName> const& m_variablesToReplace;
/// Variables (that are to be replaced) currently in scope.
std::set<YulName> m_variablesInScope;
/// Variables that do not have a specific value.
util::UniqueVector<YulName> m_variablesToReassign;
};
void IntroduceControlFlowSSA::operator()(FunctionDefinition& _function)
{
std::set<YulName> varsInScope;
std::swap(varsInScope, m_variablesInScope);
util::UniqueVector<YulName> toReassign;
std::swap(toReassign, m_variablesToReassign);
for (auto const& param: _function.parameters)
if (m_variablesToReplace.count(param.name))
{
m_variablesInScope.insert(param.name);
m_variablesToReassign.pushBack(param.name);
}
ASTModifier::operator()(_function);
m_variablesInScope = std::move(varsInScope);
m_variablesToReassign = std::move(toReassign);
}
void IntroduceControlFlowSSA::operator()(ForLoop& _for)
{
yulAssert(_for.pre.statements.empty(), "For loop init rewriter not run.");
for (auto const& var: assignedVariableNames(_for.body) + assignedVariableNames(_for.post))
if (util::contains(m_variablesInScope,var))
m_variablesToReassign.pushBack(var);
(*this)(_for.body);
(*this)(_for.post);
}
void IntroduceControlFlowSSA::operator()(Switch& _switch)
{
yulAssert(m_variablesToReassign.empty(), "");
util::UniqueVector<YulName> toReassign;
for (auto& c: _switch.cases)
{
(*this)(c.body);
toReassign.pushBack(m_variablesToReassign);
}
m_variablesToReassign.pushBack(toReassign);
}
void IntroduceControlFlowSSA::operator()(Block& _block)
{
util::UniqueVector<YulName> variablesDeclaredHere;
util::UniqueVector<YulName> assignedVariables;
util::iterateReplacing(
_block.statements,
[&](Statement& _s) -> std::optional<std::vector<Statement>>
{
std::vector<Statement> toPrepend;
for (YulName toReassign: m_variablesToReassign)
{
YulName newName = m_nameDispenser.newName(toReassign);
toPrepend.emplace_back(VariableDeclaration{
debugDataOf(_s),
{NameWithDebugData{debugDataOf(_s), newName}},
std::make_unique<Expression>(Identifier{debugDataOf(_s), toReassign})
});
assignedVariables.pushBack(toReassign);
}
m_variablesToReassign.clear();
if (std::holds_alternative<VariableDeclaration>(_s))
{
VariableDeclaration& varDecl = std::get<VariableDeclaration>(_s);
for (auto const& var: varDecl.variables)
if (m_variablesToReplace.count(var.name))
{
variablesDeclaredHere.pushBack(var.name);
m_variablesInScope.insert(var.name);
}
}
else if (std::holds_alternative<Assignment>(_s))
{
Assignment& assignment = std::get<Assignment>(_s);
for (auto const& var: assignment.variableNames)
if (m_variablesToReplace.count(var.name))
assignedVariables.pushBack(var.name);
}
else
visit(_s);
if (toPrepend.empty())
return {};
else
{
toPrepend.emplace_back(std::move(_s));
return {std::move(toPrepend)};
}
}
);
m_variablesToReassign.pushBack(assignedVariables);
m_variablesInScope -= variablesDeclaredHere.contents();
m_variablesToReassign.removeAll(variablesDeclaredHere.contents());
}
/**
* Third step of SSA transform: Replace the references to variables-to-be-replaced
* by their current values.
*/
class PropagateValues: public ASTModifier
{
public:
explicit PropagateValues(std::set<YulName> const& _variablesToReplace):
m_variablesToReplace(_variablesToReplace)
{ }
void operator()(Identifier& _identifier) override;
void operator()(VariableDeclaration& _varDecl) override;
void operator()(Assignment& _assignment) override;
void operator()(ForLoop& _for) override;
void operator()(Block& _block) override;
private:
/// This is a set of all variables that are assigned to anywhere in the code.
/// Variables that are only declared but never re-assigned are not touched.
std::set<YulName> const& m_variablesToReplace;
std::map<YulName, YulName> m_currentVariableValues;
std::set<YulName> m_clearAtEndOfBlock;
};
void PropagateValues::operator()(Identifier& _identifier)
{
if (m_currentVariableValues.count(_identifier.name))
_identifier.name = m_currentVariableValues[_identifier.name];
}
void PropagateValues::operator()(VariableDeclaration& _varDecl)
{
ASTModifier::operator()(_varDecl);
if (_varDecl.variables.size() != 1)
return;
YulName variable = _varDecl.variables.front().name;
if (m_variablesToReplace.count(variable))
{
// `let a := a_1` - regular declaration of non-SSA variable
yulAssert(std::holds_alternative<Identifier>(*_varDecl.value), "");
m_currentVariableValues[variable] = std::get<Identifier>(*_varDecl.value).name;
m_clearAtEndOfBlock.insert(variable);
}
else if (_varDecl.value && std::holds_alternative<Identifier>(*_varDecl.value))
{
// `let a_1 := a` - assignment to SSA variable after a branch.
YulName value = std::get<Identifier>(*_varDecl.value).name;
if (m_variablesToReplace.count(value))
{
// This is safe because `a_1` is not a "variable to replace" and thus
// will not be re-assigned.
m_currentVariableValues[value] = variable;
m_clearAtEndOfBlock.insert(value);
}
}
}
void PropagateValues::operator()(Assignment& _assignment)
{
visit(*_assignment.value);
if (_assignment.variableNames.size() != 1)
return;
YulName name = _assignment.variableNames.front().name;
if (!m_variablesToReplace.count(name))
return;
yulAssert(_assignment.value && std::holds_alternative<Identifier>(*_assignment.value), "");
m_currentVariableValues[name] = std::get<Identifier>(*_assignment.value).name;
m_clearAtEndOfBlock.insert(name);
}
void PropagateValues::operator()(ForLoop& _for)
{
yulAssert(_for.pre.statements.empty(), "For loop init rewriter not run.");
for (auto const& var: assignedVariableNames(_for.body) + assignedVariableNames(_for.post))
m_currentVariableValues.erase(var);
visit(*_for.condition);
(*this)(_for.body);
(*this)(_for.post);
}
void PropagateValues::operator()(Block& _block)
{
std::set<YulName> clearAtParentBlock = std::move(m_clearAtEndOfBlock);
m_clearAtEndOfBlock.clear();
ASTModifier::operator()(_block);
for (auto const& var: m_clearAtEndOfBlock)
m_currentVariableValues.erase(var);
m_clearAtEndOfBlock = std::move(clearAtParentBlock);
}
}
void SSATransform::run(OptimiserStepContext& _context, Block& _ast)
{
std::set<YulName> assignedVariables = assignedVariableNames(_ast);
IntroduceSSA{_context.dispenser, assignedVariables}(_ast);
IntroduceControlFlowSSA{_context.dispenser, assignedVariables}(_ast);
PropagateValues{assignedVariables}(_ast);
}
| 11,488
|
C++
|
.cpp
| 321
| 32.688474
| 93
| 0.744217
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,115
|
Suite.cpp
|
ethereum_solidity/libyul/optimiser/Suite.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser suite that combines all steps and also provides the settings for the heuristics.
*/
#include <libyul/optimiser/Suite.h>
#include <libyul/optimiser/Disambiguator.h>
#include <libyul/optimiser/VarDeclInitializer.h>
#include <libyul/optimiser/BlockFlattener.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/CircularReferencesPruner.h>
#include <libyul/optimiser/ControlFlowSimplifier.h>
#include <libyul/optimiser/ConditionalSimplifier.h>
#include <libyul/optimiser/ConditionalUnsimplifier.h>
#include <libyul/optimiser/DeadCodeEliminator.h>
#include <libyul/optimiser/FunctionGrouper.h>
#include <libyul/optimiser/FunctionHoister.h>
#include <libyul/optimiser/EqualStoreEliminator.h>
#include <libyul/optimiser/EquivalentFunctionCombiner.h>
#include <libyul/optimiser/ExpressionSplitter.h>
#include <libyul/optimiser/ExpressionJoiner.h>
#include <libyul/optimiser/ExpressionInliner.h>
#include <libyul/optimiser/FullInliner.h>
#include <libyul/optimiser/ForLoopConditionIntoBody.h>
#include <libyul/optimiser/ForLoopConditionOutOfBody.h>
#include <libyul/optimiser/ForLoopInitRewriter.h>
#include <libyul/optimiser/ForLoopConditionIntoBody.h>
#include <libyul/optimiser/FunctionSpecializer.h>
#include <libyul/optimiser/Rematerialiser.h>
#include <libyul/optimiser/UnusedFunctionParameterPruner.h>
#include <libyul/optimiser/UnusedPruner.h>
#include <libyul/optimiser/ExpressionSimplifier.h>
#include <libyul/optimiser/CommonSubexpressionEliminator.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/SSAReverser.h>
#include <libyul/optimiser/SSATransform.h>
#include <libyul/optimiser/StackCompressor.h>
#include <libyul/optimiser/StackLimitEvader.h>
#include <libyul/optimiser/StructuralSimplifier.h>
#include <libyul/optimiser/SyntacticalEquality.h>
#include <libyul/optimiser/UnusedAssignEliminator.h>
#include <libyul/optimiser/UnusedStoreEliminator.h>
#include <libyul/optimiser/VarNameCleaner.h>
#include <libyul/optimiser/LoadResolver.h>
#include <libyul/optimiser/LoopInvariantCodeMotion.h>
#include <libyul/optimiser/Metrics.h>
#include <libyul/optimiser/NameSimplifier.h>
#include <libyul/backends/evm/ConstantOptimiser.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <libyul/Object.h>
#include <libyul/backends/evm/NoOutputAssembly.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Profiler.h>
#include <libyul/CompilabilityChecker.h>
#include <range/v3/view/map.hpp>
#include <range/v3/action/remove.hpp>
#include <range/v3/algorithm/count.hpp>
#include <range/v3/algorithm/none_of.hpp>
#include <limits>
#include <tuple>
using namespace solidity;
using namespace solidity::yul;
using namespace std::string_literals;
void OptimiserSuite::run(
Dialect const& _dialect,
GasMeter const* _meter,
Object& _object,
bool _optimizeStackAllocation,
std::string_view _optimisationSequence,
std::string_view _optimisationCleanupSequence,
std::optional<size_t> _expectedExecutionsPerDeployment,
std::set<YulName> const& _externallyUsedIdentifiers
)
{
EVMDialect const* evmDialect = dynamic_cast<EVMDialect const*>(&_dialect);
bool usesOptimizedCodeGenerator =
_optimizeStackAllocation &&
evmDialect &&
evmDialect->evmVersion().canOverchargeGasForCall() &&
evmDialect->providesObjectAccess();
std::set<YulName> reservedIdentifiers = _externallyUsedIdentifiers;
Block astRoot;
{
PROFILER_PROBE("Disambiguator", probe);
astRoot = std::get<Block>(Disambiguator(
_dialect,
*_object.analysisInfo,
reservedIdentifiers
)(_object.code()->root()));
}
NameDispenser dispenser{_dialect, astRoot, reservedIdentifiers};
OptimiserStepContext context{_dialect, dispenser, reservedIdentifiers, _expectedExecutionsPerDeployment};
OptimiserSuite suite(context, Debug::None);
// Some steps depend on properties ensured by FunctionHoister, BlockFlattener, FunctionGrouper and
// ForLoopInitRewriter. Run them first to be able to run arbitrary sequences safely.
suite.runSequence("hgfo", astRoot);
// Now the user-supplied part
suite.runSequence(_optimisationSequence, astRoot);
// This is a tuning parameter, but actually just prevents infinite loops.
size_t stackCompressorMaxIterations = 16;
suite.runSequence("g", astRoot);
// We ignore the return value because we will get a much better error
// message once we perform code generation.
if (!usesOptimizedCodeGenerator)
{
PROFILER_PROBE("StackCompressor", probe);
_object.setCode(std::make_shared<AST>(std::move(astRoot)));
astRoot = std::get<1>(StackCompressor::run(
_dialect,
_object,
_optimizeStackAllocation,
stackCompressorMaxIterations
));
}
// Run the user-supplied clean up sequence
suite.runSequence(_optimisationCleanupSequence, astRoot);
// Hard-coded FunctionGrouper step is used to bring the AST into a canonical form required by the StackCompressor
// and StackLimitEvader. This is hard-coded as the last step, as some previously executed steps may break the
// aforementioned form, thus causing the StackCompressor/StackLimitEvader to throw.
suite.runSequence("g", astRoot);
if (evmDialect)
{
yulAssert(_meter, "");
{
PROFILER_PROBE("ConstantOptimiser", probe);
ConstantOptimiser{*evmDialect, *_meter}(astRoot);
}
if (usesOptimizedCodeGenerator)
{
{
PROFILER_PROBE("StackCompressor", probe);
_object.setCode(std::make_shared<AST>(std::move(astRoot)));
astRoot = std::get<1>(StackCompressor::run(
_dialect,
_object,
_optimizeStackAllocation,
stackCompressorMaxIterations
));
}
if (evmDialect->providesObjectAccess())
{
PROFILER_PROBE("StackLimitEvader", probe);
_object.setCode(std::make_shared<AST>(std::move(astRoot)));
astRoot = StackLimitEvader::run(suite.m_context, _object);
}
}
else if (evmDialect->providesObjectAccess() && _optimizeStackAllocation)
{
PROFILER_PROBE("StackLimitEvader", probe);
_object.setCode(std::make_shared<AST>(std::move(astRoot)));
astRoot = StackLimitEvader::run(suite.m_context, _object);
}
}
dispenser.reset(astRoot);
{
PROFILER_PROBE("NameSimplifier", probe);
NameSimplifier::run(suite.m_context, astRoot);
}
{
PROFILER_PROBE("VarNameCleaner", probe);
VarNameCleaner::run(suite.m_context, astRoot);
}
_object.setCode(std::make_shared<AST>(std::move(astRoot)));
_object.analysisInfo = std::make_shared<AsmAnalysisInfo>(AsmAnalyzer::analyzeStrictAssertCorrect(_dialect, _object));
}
namespace
{
template <class... Step>
std::map<std::string, std::unique_ptr<OptimiserStep>> optimiserStepCollection()
{
std::map<std::string, std::unique_ptr<OptimiserStep>> ret;
for (std::unique_ptr<OptimiserStep>& s: util::make_vector<std::unique_ptr<OptimiserStep>>(
(std::make_unique<OptimiserStepInstance<Step>>())...
))
{
yulAssert(!ret.count(s->name), "");
ret[s->name] = std::move(s);
}
return ret;
}
}
std::map<std::string, std::unique_ptr<OptimiserStep>> const& OptimiserSuite::allSteps()
{
static std::map<std::string, std::unique_ptr<OptimiserStep>> instance;
if (instance.empty())
instance = optimiserStepCollection<
BlockFlattener,
CircularReferencesPruner,
CommonSubexpressionEliminator,
ConditionalSimplifier,
ConditionalUnsimplifier,
ControlFlowSimplifier,
DeadCodeEliminator,
EqualStoreEliminator,
EquivalentFunctionCombiner,
ExpressionInliner,
ExpressionJoiner,
ExpressionSimplifier,
ExpressionSplitter,
ForLoopConditionIntoBody,
ForLoopConditionOutOfBody,
ForLoopInitRewriter,
FullInliner,
FunctionGrouper,
FunctionHoister,
FunctionSpecializer,
LiteralRematerialiser,
LoadResolver,
LoopInvariantCodeMotion,
UnusedAssignEliminator,
UnusedStoreEliminator,
Rematerialiser,
SSAReverser,
SSATransform,
StructuralSimplifier,
UnusedFunctionParameterPruner,
UnusedPruner,
VarDeclInitializer
>();
// Does not include VarNameCleaner because it destroys the property of unique names.
// Does not include NameSimplifier.
return instance;
}
std::map<std::string, char> const& OptimiserSuite::stepNameToAbbreviationMap()
{
static std::map<std::string, char> lookupTable{
{BlockFlattener::name, 'f'},
{CircularReferencesPruner::name, 'l'},
{CommonSubexpressionEliminator::name, 'c'},
{ConditionalSimplifier::name, 'C'},
{ConditionalUnsimplifier::name, 'U'},
{ControlFlowSimplifier::name, 'n'},
{DeadCodeEliminator::name, 'D'},
{EqualStoreEliminator::name, 'E'},
{EquivalentFunctionCombiner::name, 'v'},
{ExpressionInliner::name, 'e'},
{ExpressionJoiner::name, 'j'},
{ExpressionSimplifier::name, 's'},
{ExpressionSplitter::name, 'x'},
{ForLoopConditionIntoBody::name, 'I'},
{ForLoopConditionOutOfBody::name, 'O'},
{ForLoopInitRewriter::name, 'o'},
{FullInliner::name, 'i'},
{FunctionGrouper::name, 'g'},
{FunctionHoister::name, 'h'},
{FunctionSpecializer::name, 'F'},
{LiteralRematerialiser::name, 'T'},
{LoadResolver::name, 'L'},
{LoopInvariantCodeMotion::name, 'M'},
{UnusedAssignEliminator::name, 'r'},
{UnusedStoreEliminator::name, 'S'},
{Rematerialiser::name, 'm'},
{SSAReverser::name, 'V'},
{SSATransform::name, 'a'},
{StructuralSimplifier::name, 't'},
{UnusedFunctionParameterPruner::name, 'p'},
{UnusedPruner::name, 'u'},
{VarDeclInitializer::name, 'd'},
};
yulAssert(lookupTable.size() == allSteps().size(), "");
yulAssert((
util::convertContainer<std::set<char>>(std::string(NonStepAbbreviations)) -
util::convertContainer<std::set<char>>(lookupTable | ranges::views::values)
).size() == std::string(NonStepAbbreviations).size(),
"Step abbreviation conflicts with a character reserved for another syntactic element"
);
return lookupTable;
}
std::map<char, std::string> const& OptimiserSuite::stepAbbreviationToNameMap()
{
static std::map<char, std::string> lookupTable = util::invertMap(stepNameToAbbreviationMap());
return lookupTable;
}
void OptimiserSuite::validateSequence(std::string_view _stepAbbreviations)
{
int8_t nestingLevel = 0;
int8_t colonDelimiters = 0;
for (char abbreviation: _stepAbbreviations)
switch (abbreviation)
{
case ' ':
case '\n':
break;
case '[':
assertThrow(nestingLevel < std::numeric_limits<int8_t>::max(), OptimizerException, "Brackets nested too deep");
nestingLevel++;
break;
case ']':
nestingLevel--;
assertThrow(nestingLevel >= 0, OptimizerException, "Unbalanced brackets");
break;
case ':':
++colonDelimiters;
assertThrow(nestingLevel == 0, OptimizerException, "Cleanup sequence delimiter cannot be placed inside the brackets");
assertThrow(colonDelimiters <= 1, OptimizerException, "Too many cleanup sequence delimiters");
break;
default:
{
yulAssert(
std::string(NonStepAbbreviations).find(abbreviation) == std::string::npos,
"Unhandled syntactic element in the abbreviation sequence"
);
assertThrow(
stepAbbreviationToNameMap().find(abbreviation) != stepAbbreviationToNameMap().end(),
OptimizerException,
"'"s + abbreviation + "' is not a valid step abbreviation"
);
std::optional<std::string> invalid = allSteps().at(stepAbbreviationToNameMap().at(abbreviation))->invalidInCurrentEnvironment();
assertThrow(
!invalid.has_value(),
OptimizerException,
"'"s + abbreviation + "' is invalid in the current environment: " + *invalid
);
}
}
assertThrow(nestingLevel == 0, OptimizerException, "Unbalanced brackets");
}
bool OptimiserSuite::isEmptyOptimizerSequence(std::string const& _sequence)
{
return
ranges::count(_sequence, ':') == 1 &&
ranges::none_of(_sequence, [](auto _step) { return _step != ':' && _step != ' ' && _step != '\n'; });
}
void OptimiserSuite::runSequence(std::string_view _stepAbbreviations, Block& _ast, bool _repeatUntilStable)
{
validateSequence(_stepAbbreviations);
// This splits 'aaa[bbb]ccc...' into 'aaa' and '[bbb]ccc...'.
auto extractNonNestedPrefix = [](std::string_view _tail) -> std::tuple<std::string_view, std::string_view>
{
for (size_t i = 0; i < _tail.size(); ++i)
{
yulAssert(_tail[i] != ']');
if (_tail[i] == '[')
return {_tail.substr(0, i), _tail.substr(i)};
}
return {_tail, {}};
};
// This splits '[bbb]ccc...' into 'bbb' and 'ccc...'.
auto extractBracketContent = [](std::string_view _tail) -> std::tuple<std::string_view, std::string_view>
{
yulAssert(!_tail.empty() && _tail[0] == '[');
size_t contentLength = 0;
int8_t nestingLevel = 1;
for (char abbreviation: _tail.substr(1))
{
if (abbreviation == '[')
{
yulAssert(nestingLevel < std::numeric_limits<int8_t>::max());
++nestingLevel;
}
else if (abbreviation == ']')
{
--nestingLevel;
if (nestingLevel == 0)
break;
}
++contentLength;
}
yulAssert(nestingLevel == 0);
yulAssert(_tail[contentLength + 1] == ']');
return {_tail.substr(1, contentLength), _tail.substr(contentLength + 2)};
};
auto abbreviationsToSteps = [](std::string_view _sequence) -> std::vector<std::string>
{
std::vector<std::string> steps;
for (char abbreviation: _sequence)
if (abbreviation != ' ' && abbreviation != '\n')
steps.emplace_back(stepAbbreviationToNameMap().at(abbreviation));
return steps;
};
std::vector<std::tuple<std::string_view, bool>> subsequences;
std::string_view tail = _stepAbbreviations;
while (!tail.empty())
{
std::string_view subsequence;
tie(subsequence, tail) = extractNonNestedPrefix(tail);
if (subsequence.size() > 0)
subsequences.push_back({subsequence, false});
if (tail.empty())
break;
tie(subsequence, tail) = extractBracketContent(tail);
if (subsequence.size() > 0)
subsequences.push_back({subsequence, true});
}
// NOTE: If _repeatUntilStable is false, the value will not be used so do not calculate it.
size_t codeSize = (_repeatUntilStable ? CodeSize::codeSizeIncludingFunctions(_ast) : 0);
for (size_t round = 0; round < MaxRounds; ++round)
{
for (auto const& [subsequence, repeat]: subsequences)
{
if (repeat)
runSequence(subsequence, _ast, true);
else
runSequence(abbreviationsToSteps(subsequence), _ast);
}
if (!_repeatUntilStable)
break;
size_t newSize = CodeSize::codeSizeIncludingFunctions(_ast);
if (newSize == codeSize)
break;
codeSize = newSize;
}
}
void OptimiserSuite::runSequence(std::vector<std::string> const& _steps, Block& _ast)
{
std::unique_ptr<Block> copy;
if (m_debug == Debug::PrintChanges)
copy = std::make_unique<Block>(std::get<Block>(ASTCopier{}(_ast)));
for (std::string const& step: _steps)
{
if (m_debug == Debug::PrintStep)
std::cout << "Running " << step << std::endl;
{
PROFILER_PROBE(step, probe);
allSteps().at(step)->run(m_context, _ast);
}
if (m_debug == Debug::PrintChanges)
{
// TODO should add switch to also compare variable names!
if (SyntacticallyEqual{}.statementEqual(_ast, *copy))
std::cout << "== Running " << step << " did not cause changes." << std::endl;
else
{
std::cout << "== Running " << step << " changed the AST." << std::endl;
std::cout << AsmPrinter{m_context.dialect}(_ast) << std::endl;
copy = std::make_unique<Block>(std::get<Block>(ASTCopier{}(_ast)));
}
}
}
}
| 16,286
|
C++
|
.cpp
| 445
| 33.804494
| 131
| 0.730053
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,118
|
Rematerialiser.cpp
|
ethereum_solidity/libyul/optimiser/Rematerialiser.cpp
|
/*(
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Optimisation stage that replaces variables by their most recently assigned expressions.
*/
#include <libyul/optimiser/Rematerialiser.h>
#include <libyul/optimiser/Metrics.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/Exceptions.h>
#include <libyul/AST.h>
#include <range/v3/algorithm/all_of.hpp>
using namespace solidity;
using namespace solidity::yul;
void Rematerialiser::run(Dialect const& _dialect, Block& _ast, std::set<YulName> _varsToAlwaysRematerialize, bool _onlySelectedVariables)
{
Rematerialiser{_dialect, _ast, std::move(_varsToAlwaysRematerialize), _onlySelectedVariables}(_ast);
}
Rematerialiser::Rematerialiser(
Dialect const& _dialect,
Block& _ast,
std::set<YulName> _varsToAlwaysRematerialize,
bool _onlySelectedVariables
):
DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore),
m_referenceCounts(VariableReferencesCounter::countReferences(_ast)),
m_varsToAlwaysRematerialize(std::move(_varsToAlwaysRematerialize)),
m_onlySelectedVariables(_onlySelectedVariables)
{
}
void Rematerialiser::visit(Expression& _e)
{
if (std::holds_alternative<Identifier>(_e))
{
Identifier& identifier = std::get<Identifier>(_e);
YulName name = identifier.name;
if (AssignedValue const* value = variableValue(name))
{
assertThrow(value->value, OptimizerException, "");
size_t refs = m_referenceCounts[name];
size_t cost = CodeCost::codeCost(m_dialect, *value->value);
if (
(
!m_onlySelectedVariables && (
(refs <= 1 && value->loopDepth == m_loopDepth) ||
cost == 0 ||
(refs <= 5 && cost <= 1 && m_loopDepth == 0)
)
) || m_varsToAlwaysRematerialize.count(name)
)
{
assertThrow(m_referenceCounts[name] > 0, OptimizerException, "");
auto variableReferences = references(name);
if (!variableReferences || ranges::all_of(*variableReferences, [&](auto const& ref) { return inScope(ref); }))
{
// update reference counts
m_referenceCounts[name]--;
for (auto const& ref: VariableReferencesCounter::countReferences(
*value->value
))
m_referenceCounts[ref.first] += ref.second;
_e = (ASTCopier{}).translate(*value->value);
}
}
}
}
DataFlowAnalyzer::visit(_e);
}
void LiteralRematerialiser::visit(Expression& _e)
{
if (std::holds_alternative<Identifier>(_e))
{
Identifier& identifier = std::get<Identifier>(_e);
YulName name = identifier.name;
if (AssignedValue const* value = variableValue(name))
{
assertThrow(value->value, OptimizerException, "");
if (std::holds_alternative<Literal>(*value->value))
_e = *value->value;
}
}
DataFlowAnalyzer::visit(_e);
}
| 3,330
|
C++
|
.cpp
| 94
| 32.457447
| 137
| 0.737984
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,119
|
UnusedPruner.cpp
|
ethereum_solidity/libyul/optimiser/UnusedPruner.cpp
|
/*(
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Optimisation stage that removes unused variables and functions.
*/
#include <libyul/optimiser/UnusedPruner.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/FunctionGrouper.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/Exceptions.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libyul/SideEffects.h>
using namespace solidity;
using namespace solidity::yul;
void UnusedPruner::run(OptimiserStepContext& _context, Block& _ast)
{
UnusedPruner::runUntilStabilisedOnFullAST(_context.dialect, _ast, _context.reservedIdentifiers);
FunctionGrouper::run(_context, _ast);
}
UnusedPruner::UnusedPruner(
Dialect const& _dialect,
Block& _ast,
bool _allowMSizeOptimization,
std::map<YulName, SideEffects> const* _functionSideEffects,
std::set<YulName> const& _externallyUsedFunctions
):
m_dialect(_dialect),
m_allowMSizeOptimization(_allowMSizeOptimization),
m_functionSideEffects(_functionSideEffects)
{
m_references = ReferencesCounter::countReferences(_ast);
for (auto const& f: _externallyUsedFunctions)
++m_references[f];
}
void UnusedPruner::operator()(Block& _block)
{
for (auto&& statement: _block.statements)
if (std::holds_alternative<FunctionDefinition>(statement))
{
FunctionDefinition& funDef = std::get<FunctionDefinition>(statement);
if (!used(funDef.name))
{
subtractReferences(ReferencesCounter::countReferences(funDef.body));
statement = Block{std::move(funDef.debugData), {}};
}
}
else if (std::holds_alternative<VariableDeclaration>(statement))
{
VariableDeclaration& varDecl = std::get<VariableDeclaration>(statement);
// Multi-variable declarations are special. We can only remove it
// if all variables are unused and the right-hand-side is either
// movable or it returns a single value. In the latter case, we
// replace `let a := f()` by `pop(f())` (in pure Yul, this will be
// `drop(f())`).
if (std::none_of(
varDecl.variables.begin(),
varDecl.variables.end(),
[&](NameWithDebugData const& _typedName) { return used(_typedName.name); }
))
{
if (!varDecl.value)
statement = Block{std::move(varDecl.debugData), {}};
else if (
SideEffectsCollector(m_dialect, *varDecl.value, m_functionSideEffects).
canBeRemoved(m_allowMSizeOptimization)
)
{
subtractReferences(ReferencesCounter::countReferences(*varDecl.value));
statement = Block{std::move(varDecl.debugData), {}};
}
else if (varDecl.variables.size() == 1 && m_dialect.discardFunctionHandle())
statement = ExpressionStatement{varDecl.debugData, FunctionCall{
varDecl.debugData,
{varDecl.debugData, YulName{m_dialect.builtin(*m_dialect.discardFunctionHandle()).name}},
{*std::move(varDecl.value)}
}};
}
}
else if (std::holds_alternative<ExpressionStatement>(statement))
{
ExpressionStatement& exprStmt = std::get<ExpressionStatement>(statement);
if (
SideEffectsCollector(m_dialect, exprStmt.expression, m_functionSideEffects).
canBeRemoved(m_allowMSizeOptimization)
)
{
subtractReferences(ReferencesCounter::countReferences(exprStmt.expression));
statement = Block{std::move(exprStmt.debugData), {}};
}
}
removeEmptyBlocks(_block);
ASTModifier::operator()(_block);
}
void UnusedPruner::runUntilStabilised(
Dialect const& _dialect,
Block& _ast,
bool _allowMSizeOptimization,
std::map<YulName, SideEffects> const* _functionSideEffects,
std::set<YulName> const& _externallyUsedFunctions
)
{
while (true)
{
UnusedPruner pruner(
_dialect,
_ast,
_allowMSizeOptimization,
_functionSideEffects,
_externallyUsedFunctions
);
pruner(_ast);
if (!pruner.shouldRunAgain())
return;
}
}
void UnusedPruner::runUntilStabilisedOnFullAST(
Dialect const& _dialect,
Block& _ast,
std::set<YulName> const& _externallyUsedFunctions
)
{
std::map<YulName, SideEffects> functionSideEffects =
SideEffectsPropagator::sideEffects(_dialect, CallGraphGenerator::callGraph(_ast));
bool allowMSizeOptimization = !MSizeFinder::containsMSize(_dialect, _ast);
runUntilStabilised(_dialect, _ast, allowMSizeOptimization, &functionSideEffects, _externallyUsedFunctions);
}
bool UnusedPruner::used(YulName _name) const
{
return m_references.count(_name) && m_references.at(_name) > 0;
}
void UnusedPruner::subtractReferences(std::map<YulName, size_t> const& _subtrahend)
{
for (auto const& ref: _subtrahend)
{
assertThrow(m_references.count(ref.first), OptimizerException, "");
assertThrow(m_references.at(ref.first) >= ref.second, OptimizerException, "");
m_references[ref.first] -= ref.second;
m_shouldRunAgain = true;
}
}
| 5,428
|
C++
|
.cpp
| 154
| 32.383117
| 108
| 0.757749
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,120
|
BlockFlattener.cpp
|
ethereum_solidity/libyul/optimiser/BlockFlattener.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/BlockFlattener.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
#include <functional>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
void BlockFlattener::operator()(Block& _block)
{
ASTModifier::operator()(_block);
iterateReplacing(
_block.statements,
[](Statement& _s) -> std::optional<std::vector<Statement>>
{
if (std::holds_alternative<Block>(_s))
return std::move(std::get<Block>(_s).statements);
else
return {};
}
);
}
void BlockFlattener::run(OptimiserStepContext&, Block& _ast)
{
BlockFlattener flattener;
for (auto& statement: _ast.statements)
if (auto* block = std::get_if<Block>(&statement))
flattener(*block);
else if (auto* function = std::get_if<FunctionDefinition>(&statement))
flattener(function->body);
else
yulAssert(false, "BlockFlattener requires the FunctionGrouper.");
}
| 1,609
|
C++
|
.cpp
| 46
| 32.608696
| 72
| 0.760464
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,122
|
StackLimitEvader.cpp
|
ethereum_solidity/libyul/optimiser/StackLimitEvader.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/StackLimitEvader.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/FunctionCallFinder.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/StackToMemoryMover.h>
#include <libyul/backends/evm/ControlFlowGraphBuilder.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AST.h>
#include <libyul/CompilabilityChecker.h>
#include <libyul/Exceptions.h>
#include <libyul/Object.h>
#include <libyul/Utilities.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/CommonData.h>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/concat.hpp>
#include <range/v3/view/take.hpp>
using namespace solidity;
using namespace solidity::yul;
namespace
{
/**
* Walks the call graph using a Depth-First-Search assigning memory slots to variables.
* - The leaves of the call graph will get the lowest slot, increasing towards the root.
* - ``slotsRequiredForFunction`` maps a function to the number of slots it requires (which is also the
* next available slot that can be used by another function that calls this function).
* - For each function starting from the root of the call graph:
* - Visit all children that are not already visited.
* - Determine the maximum value ``n`` of the values of ``slotsRequiredForFunction`` among the children.
* - If the function itself contains variables that need memory slots, but is contained in a cycle,
* abort the process as failure.
* - If not, assign each variable its slot starting from ``n`` (incrementing it).
* - Assign ``n`` to ``slotsRequiredForFunction`` of the function.
*/
struct MemoryOffsetAllocator
{
uint64_t run(YulName _function = YulName{})
{
if (slotsRequiredForFunction.count(_function))
return slotsRequiredForFunction[_function];
// Assign to zero early to guard against recursive calls.
slotsRequiredForFunction[_function] = 0;
uint64_t requiredSlots = 0;
if (callGraph.count(_function))
for (YulName child: callGraph.at(_function))
requiredSlots = std::max(run(child), requiredSlots);
if (auto const* unreachables = util::valueOrNullptr(unreachableVariables, _function))
{
if (FunctionDefinition const* functionDefinition = util::valueOrDefault(functionDefinitions, _function, nullptr, util::allow_copy))
if (
size_t totalArgCount = functionDefinition->returnVariables.size() + functionDefinition->parameters.size();
totalArgCount > 16
)
for (NameWithDebugData const& var: ranges::concat_view(
functionDefinition->parameters,
functionDefinition->returnVariables
) | ranges::views::take(totalArgCount - 16))
slotAllocations[var.name] = requiredSlots++;
// Assign slots for all variables that become unreachable in the function body, if the above did not
// assign a slot for them already.
for (YulName variable: *unreachables)
// The empty case is a function with too many arguments or return values,
// which was already handled above.
if (!variable.empty() && !slotAllocations.count(variable))
slotAllocations[variable] = requiredSlots++;
}
return slotsRequiredForFunction[_function] = requiredSlots;
}
/// Maps function names to the set of unreachable variables in that function.
/// An empty variable name means that the function has too many arguments or return variables.
std::map<YulName, std::vector<YulName>> const& unreachableVariables;
/// The graph of immediate function calls of all functions.
std::map<YulName, std::vector<YulName>> const& callGraph;
/// Maps the name of each user-defined function to its definition.
std::map<YulName, FunctionDefinition const*> const& functionDefinitions;
/// Maps variable names to the memory slot the respective variable is assigned.
std::map<YulName, uint64_t> slotAllocations{};
/// Maps function names to the number of memory slots the respective function requires.
std::map<YulName, uint64_t> slotsRequiredForFunction{};
};
u256 literalArgumentValue(FunctionCall const& _call)
{
yulAssert(_call.arguments.size() == 1, "");
Literal const* literal = std::get_if<Literal>(&_call.arguments.front());
yulAssert(literal && literal->kind == LiteralKind::Number, "");
return literal->value.value();
}
}
Block StackLimitEvader::run(
OptimiserStepContext& _context,
Object const& _object
)
{
yulAssert(_object.hasCode());
auto const* evmDialect = dynamic_cast<EVMDialect const*>(&_context.dialect);
yulAssert(
evmDialect && evmDialect->providesObjectAccess(),
"StackLimitEvader can only be run on objects using the EVMDialect with object access."
);
auto astRoot = std::get<Block>(ASTCopier{}(_object.code()->root()));
if (evmDialect && evmDialect->evmVersion().canOverchargeGasForCall())
{
yul::AsmAnalysisInfo analysisInfo = yul::AsmAnalyzer::analyzeStrictAssertCorrect(
*evmDialect,
astRoot,
_object.summarizeStructure()
);
std::unique_ptr<CFG> cfg = ControlFlowGraphBuilder::build(analysisInfo, *evmDialect, astRoot);
run(_context, astRoot, StackLayoutGenerator::reportStackTooDeep(*cfg));
}
else
{
run(_context, astRoot, CompilabilityChecker{
_context.dialect,
_object,
true,
}.unreachableVariables);
}
return astRoot;
}
void StackLimitEvader::run(
OptimiserStepContext& _context,
Block& _astRoot,
std::map<YulName, std::vector<StackLayoutGenerator::StackTooDeep>> const& _stackTooDeepErrors
)
{
std::map<YulName, std::vector<YulName>> unreachableVariables;
for (auto&& [function, stackTooDeepErrors]: _stackTooDeepErrors)
{
auto& unreachables = unreachableVariables[function];
// TODO: choose wisely.
for (auto const& stackTooDeepError: stackTooDeepErrors)
for (auto variable: stackTooDeepError.variableChoices | ranges::views::take(stackTooDeepError.deficit))
if (!util::contains(unreachables, variable))
unreachables.emplace_back(variable);
}
run(_context, _astRoot, unreachableVariables);
}
void StackLimitEvader::run(
OptimiserStepContext& _context,
Block& _astRoot,
std::map<YulName, std::vector<YulName>> const& _unreachableVariables
)
{
auto const* evmDialect = dynamic_cast<EVMDialect const*>(&_context.dialect);
yulAssert(
evmDialect && evmDialect->providesObjectAccess(),
"StackLimitEvader can only be run on objects using the EVMDialect with object access."
);
std::vector<FunctionCall*> memoryGuardCalls = findFunctionCalls(_astRoot, "memoryguard"_yulname);
// Do not optimise, if no ``memoryguard`` call is found.
if (memoryGuardCalls.empty())
return;
// Make sure all calls to ``memoryguard`` we found have the same value as argument (otherwise, abort).
u256 reservedMemory = literalArgumentValue(*memoryGuardCalls.front());
yulAssert(reservedMemory < u256(1) << 32 - 1, "");
for (FunctionCall const* memoryGuardCall: memoryGuardCalls)
if (reservedMemory != literalArgumentValue(*memoryGuardCall))
return;
CallGraph callGraph = CallGraphGenerator::callGraph(_astRoot);
// We cannot move variables in recursive functions to fixed memory offsets.
for (YulName function: callGraph.recursiveFunctions())
if (_unreachableVariables.count(function))
return;
std::map<YulName, FunctionDefinition const*> functionDefinitions = allFunctionDefinitions(_astRoot);
MemoryOffsetAllocator memoryOffsetAllocator{_unreachableVariables, callGraph.functionCalls, functionDefinitions};
uint64_t requiredSlots = memoryOffsetAllocator.run();
yulAssert(requiredSlots < (uint64_t(1) << 32) - 1, "");
StackToMemoryMover::run(_context, reservedMemory, memoryOffsetAllocator.slotAllocations, requiredSlots, _astRoot);
reservedMemory += 32 * requiredSlots;
for (FunctionCall* memoryGuardCall: findFunctionCalls(_astRoot, "memoryguard"_yulname))
{
Literal* literal = std::get_if<Literal>(&memoryGuardCall->arguments.front());
yulAssert(literal && literal->kind == LiteralKind::Number, "");
literal->value = LiteralValue{reservedMemory, toCompactHexWithPrefix(reservedMemory)};
}
}
| 8,715
|
C++
|
.cpp
| 193
| 42.642487
| 134
| 0.773161
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,125
|
OptimizerUtilities.cpp
|
ethereum_solidity/libyul/optimiser/OptimizerUtilities.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Some useful snippets for the optimiser.
*/
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/Dialect.h>
#include <libyul/AST.h>
#include <liblangutil/Token.h>
#include <libsolutil/CommonData.h>
#include <range/v3/action/remove_if.hpp>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::yul;
namespace
{
bool hasLeadingOrTrailingDot(std::string_view const _s)
{
yulAssert(!_s.empty());
return _s.front() == '.' || _s.back() == '.';
}
}
void yul::removeEmptyBlocks(Block& _block)
{
auto isEmptyBlock = [](Statement const& _st) -> bool {
return std::holds_alternative<Block>(_st) && std::get<Block>(_st).statements.empty();
};
ranges::actions::remove_if(_block.statements, isEmptyBlock);
}
bool yul::isRestrictedIdentifier(Dialect const& _dialect, YulName const& _identifier)
{
return _identifier.empty() || hasLeadingOrTrailingDot(_identifier.str()) || TokenTraits::isYulKeyword(_identifier.str()) || _dialect.reservedIdentifier(_identifier.str());
}
std::optional<evmasm::Instruction> yul::toEVMInstruction(Dialect const& _dialect, YulName const& _name)
{
if (auto const* dialect = dynamic_cast<EVMDialect const*>(&_dialect))
if (std::optional<BuiltinHandle> const builtinHandle = dialect->findBuiltin(_name.str()))
return dialect->builtin(*builtinHandle).instruction;
return std::nullopt;
}
langutil::EVMVersion const yul::evmVersionFromDialect(Dialect const& _dialect)
{
if (auto const* dialect = dynamic_cast<EVMDialect const*>(&_dialect))
return dialect->evmVersion();
return langutil::EVMVersion();
}
void StatementRemover::operator()(Block& _block)
{
util::iterateReplacing(
_block.statements,
[&](Statement& _statement) -> std::optional<std::vector<Statement>>
{
if (m_toRemove.count(&_statement))
return {std::vector<Statement>{}};
else
return std::nullopt;
}
);
ASTModifier::operator()(_block);
}
| 2,685
|
C++
|
.cpp
| 74
| 34.283784
| 172
| 0.757517
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,126
|
DataFlowAnalyzer.cpp
|
ethereum_solidity/libyul/optimiser/DataFlowAnalyzer.cpp
|
/*(
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Base class to perform data flow analysis during AST walks.
* Tracks assignments and is used as base class for both Rematerialiser and
* Common Subexpression Eliminator.
*/
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/optimiser/KnowledgeBase.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libyul/Exceptions.h>
#include <libyul/Utilities.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/cxx20.h>
#include <variant>
#include <range/v3/view/reverse.hpp>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::yul;
DataFlowAnalyzer::DataFlowAnalyzer(
Dialect const& _dialect,
MemoryAndStorage _analyzeStores,
std::map<YulName, SideEffects> _functionSideEffects
):
m_dialect(_dialect),
m_functionSideEffects(std::move(_functionSideEffects)),
m_knowledgeBase([this](YulName _var) { return variableValue(_var); }),
m_analyzeStores(_analyzeStores == MemoryAndStorage::Analyze)
{
if (m_analyzeStores)
{
if (auto const& builtinHandle = _dialect.memoryStoreFunctionHandle())
m_storeFunctionName[static_cast<unsigned>(StoreLoadLocation::Memory)] = YulName{_dialect.builtin(*builtinHandle).name};
if (auto const& builtinHandle = _dialect.memoryLoadFunctionHandle())
m_loadFunctionName[static_cast<unsigned>(StoreLoadLocation::Memory)] = YulName{_dialect.builtin(*builtinHandle).name};
if (auto const& builtinHandle = _dialect.storageStoreFunctionHandle())
m_storeFunctionName[static_cast<unsigned>(StoreLoadLocation::Storage)] = YulName{_dialect.builtin(*builtinHandle).name};
if (auto const& builtinHandle = _dialect.storageLoadFunctionHandle())
m_loadFunctionName[static_cast<unsigned>(StoreLoadLocation::Storage)] = YulName{_dialect.builtin(*builtinHandle).name};
}
}
void DataFlowAnalyzer::operator()(ExpressionStatement& _statement)
{
if (m_analyzeStores)
{
if (auto vars = isSimpleStore(StoreLoadLocation::Storage, _statement))
{
ASTModifier::operator()(_statement);
cxx20::erase_if(m_state.environment.storage, mapTuple([&](auto&& key, auto&& value) {
return
!m_knowledgeBase.knownToBeDifferent(vars->first, key) &&
vars->second != value;
}));
m_state.environment.storage[vars->first] = vars->second;
return;
}
else if (auto vars = isSimpleStore(StoreLoadLocation::Memory, _statement))
{
ASTModifier::operator()(_statement);
cxx20::erase_if(m_state.environment.memory, mapTuple([&](auto&& key, auto&& /* value */) {
return !m_knowledgeBase.knownToBeDifferentByAtLeast32(vars->first, key);
}));
// TODO erase keccak knowledge, but in a more clever way
m_state.environment.keccak = {};
m_state.environment.memory[vars->first] = vars->second;
return;
}
}
clearKnowledgeIfInvalidated(_statement.expression);
ASTModifier::operator()(_statement);
}
void DataFlowAnalyzer::operator()(Assignment& _assignment)
{
std::set<YulName> names;
for (auto const& var: _assignment.variableNames)
names.emplace(var.name);
assertThrow(_assignment.value, OptimizerException, "");
clearKnowledgeIfInvalidated(*_assignment.value);
visit(*_assignment.value);
handleAssignment(names, _assignment.value.get(), false);
}
void DataFlowAnalyzer::operator()(VariableDeclaration& _varDecl)
{
std::set<YulName> names;
for (auto const& var: _varDecl.variables)
names.emplace(var.name);
m_variableScopes.back().variables += names;
if (_varDecl.value)
{
clearKnowledgeIfInvalidated(*_varDecl.value);
visit(*_varDecl.value);
}
handleAssignment(names, _varDecl.value.get(), true);
}
void DataFlowAnalyzer::operator()(If& _if)
{
clearKnowledgeIfInvalidated(*_if.condition);
Environment preEnvironment = m_state.environment;
ASTModifier::operator()(_if);
joinKnowledge(preEnvironment);
clearValues(assignedVariableNames(_if.body));
}
void DataFlowAnalyzer::operator()(Switch& _switch)
{
clearKnowledgeIfInvalidated(*_switch.expression);
visit(*_switch.expression);
std::set<YulName> assignedVariables;
for (auto& _case: _switch.cases)
{
Environment preEnvironment = m_state.environment;
(*this)(_case.body);
joinKnowledge(preEnvironment);
std::set<YulName> variables = assignedVariableNames(_case.body);
assignedVariables += variables;
// This is a little too destructive, we could retain the old values.
clearValues(variables);
clearKnowledgeIfInvalidated(_case.body);
}
for (auto& _case: _switch.cases)
clearKnowledgeIfInvalidated(_case.body);
clearValues(assignedVariables);
}
void DataFlowAnalyzer::operator()(FunctionDefinition& _fun)
{
// Save all information. We might rather reinstantiate this class,
// but this could be difficult if it is subclassed.
ScopedSaveAndRestore stateResetter(m_state, {});
ScopedSaveAndRestore loopDepthResetter(m_loopDepth, 0u);
pushScope(true);
for (auto const& parameter: _fun.parameters)
m_variableScopes.back().variables.emplace(parameter.name);
for (auto const& var: _fun.returnVariables)
{
m_variableScopes.back().variables.emplace(var.name);
handleAssignment({var.name}, nullptr, true);
}
ASTModifier::operator()(_fun);
// Note that the contents of return variables, storage and memory at this point
// might be incorrect due to the fact that the DataFlowAnalyzer ignores the ``leave``
// statement.
popScope();
}
void DataFlowAnalyzer::operator()(ForLoop& _for)
{
// If the pre block was not empty,
// we would have to deal with more complicated scoping rules.
assertThrow(_for.pre.statements.empty(), OptimizerException, "");
++m_loopDepth;
AssignmentsSinceContinue assignmentsSinceCont;
assignmentsSinceCont(_for.body);
std::set<YulName> assignedVariables =
assignedVariableNames(_for.body) + assignedVariableNames(_for.post);
clearValues(assignedVariables);
// break/continue are tricky for storage and thus we almost always clear here.
clearKnowledgeIfInvalidated(*_for.condition);
clearKnowledgeIfInvalidated(_for.post);
clearKnowledgeIfInvalidated(_for.body);
visit(*_for.condition);
(*this)(_for.body);
clearValues(assignmentsSinceCont.names());
clearKnowledgeIfInvalidated(_for.body);
(*this)(_for.post);
clearValues(assignedVariables);
clearKnowledgeIfInvalidated(*_for.condition);
clearKnowledgeIfInvalidated(_for.post);
clearKnowledgeIfInvalidated(_for.body);
--m_loopDepth;
}
void DataFlowAnalyzer::operator()(Block& _block)
{
size_t numScopes = m_variableScopes.size();
pushScope(false);
ASTModifier::operator()(_block);
popScope();
assertThrow(numScopes == m_variableScopes.size(), OptimizerException, "");
}
std::optional<YulName> DataFlowAnalyzer::storageValue(YulName _key) const
{
if (YulName const* value = valueOrNullptr(m_state.environment.storage, _key))
return *value;
else
return std::nullopt;
}
std::optional<YulName> DataFlowAnalyzer::memoryValue(YulName _key) const
{
if (YulName const* value = valueOrNullptr(m_state.environment.memory, _key))
return *value;
else
return std::nullopt;
}
std::optional<YulName> DataFlowAnalyzer::keccakValue(YulName _start, YulName _length) const
{
if (YulName const* value = valueOrNullptr(m_state.environment.keccak, std::make_pair(_start, _length)))
return *value;
else
return std::nullopt;
}
void DataFlowAnalyzer::handleAssignment(std::set<YulName> const& _variables, Expression* _value, bool _isDeclaration)
{
if (!_isDeclaration)
clearValues(_variables);
MovableChecker movableChecker{m_dialect, &m_functionSideEffects};
if (_value)
movableChecker.visit(*_value);
else
for (auto const& var: _variables)
assignValue(var, &m_zero);
if (_value && _variables.size() == 1)
{
YulName name = *_variables.begin();
// Expression has to be movable and cannot contain a reference
// to the variable that will be assigned to.
if (movableChecker.movable() && !movableChecker.referencedVariables().count(name))
assignValue(name, _value);
}
auto const& referencedVariables = movableChecker.referencedVariables();
for (auto const& name: _variables)
{
m_state.references[name] = referencedVariables;
if (!_isDeclaration)
{
// assignment to slot denoted by "name"
m_state.environment.storage.erase(name);
// assignment to slot contents denoted by "name"
cxx20::erase_if(m_state.environment.storage, mapTuple([&name](auto&& /* key */, auto&& value) { return value == name; }));
// assignment to slot denoted by "name"
m_state.environment.memory.erase(name);
// assignment to slot contents denoted by "name"
cxx20::erase_if(m_state.environment.keccak, [&name](auto&& _item) {
return _item.first.first == name || _item.first.second == name || _item.second == name;
});
cxx20::erase_if(m_state.environment.memory, mapTuple([&name](auto&& /* key */, auto&& value) { return value == name; }));
}
}
if (_value && _variables.size() == 1)
{
YulName variable = *_variables.begin();
if (!movableChecker.referencedVariables().count(variable))
{
// This might erase additional knowledge about the slot.
// On the other hand, if we knew the value in the slot
// already, then the sload() / mload() would have been replaced by a variable anyway.
if (auto key = isSimpleLoad(StoreLoadLocation::Memory, *_value))
m_state.environment.memory[*key] = variable;
else if (auto key = isSimpleLoad(StoreLoadLocation::Storage, *_value))
m_state.environment.storage[*key] = variable;
else if (auto arguments = isKeccak(*_value))
m_state.environment.keccak[*arguments] = variable;
}
}
}
void DataFlowAnalyzer::pushScope(bool _functionScope)
{
m_variableScopes.emplace_back(_functionScope);
}
void DataFlowAnalyzer::popScope()
{
for (auto const& name: m_variableScopes.back().variables)
{
m_state.value.erase(name);
m_state.references.erase(name);
}
m_variableScopes.pop_back();
}
void DataFlowAnalyzer::clearValues(std::set<YulName> _variables)
{
// All variables that reference variables to be cleared also have to be
// cleared, but not recursively, since only the value of the original
// variables changes. Example:
// let a := 1
// let b := a
// let c := b
// a := 2
// add(b, c)
// In the last line, we can replace c by b, but not b by a.
//
// This cannot be easily tested since the substitutions will be done
// one by one on the fly, and the last line will just be add(1, 1)
// First clear storage knowledge, because we do not have to clear
// storage knowledge of variables whose expression has changed,
// since the value is still unchanged.
auto eraseCondition = mapTuple([&_variables](auto&& key, auto&& value) {
return _variables.count(key) || _variables.count(value);
});
cxx20::erase_if(m_state.environment.storage, eraseCondition);
cxx20::erase_if(m_state.environment.memory, eraseCondition);
cxx20::erase_if(m_state.environment.keccak, [&_variables](auto&& _item) {
return
_variables.count(_item.first.first) ||
_variables.count(_item.first.second) ||
_variables.count(_item.second);
});
// Also clear variables that reference variables to be cleared.
std::set<YulName> referencingVariables;
for (auto const& variableToClear: _variables)
for (auto const& [ref, names]: m_state.references)
if (names.count(variableToClear))
referencingVariables.emplace(ref);
// Clear the value and update the reference relation.
for (auto const& name: _variables + referencingVariables)
{
m_state.value.erase(name);
m_state.references.erase(name);
}
}
void DataFlowAnalyzer::assignValue(YulName _variable, Expression const* _value)
{
m_state.value[_variable] = {_value, m_loopDepth};
}
void DataFlowAnalyzer::clearKnowledgeIfInvalidated(Block const& _block)
{
if (!m_analyzeStores)
return;
SideEffectsCollector sideEffects(m_dialect, _block, &m_functionSideEffects);
if (sideEffects.invalidatesStorage())
m_state.environment.storage.clear();
if (sideEffects.invalidatesMemory())
{
m_state.environment.memory.clear();
m_state.environment.keccak.clear();
}
}
void DataFlowAnalyzer::clearKnowledgeIfInvalidated(Expression const& _expr)
{
if (!m_analyzeStores)
return;
SideEffectsCollector sideEffects(m_dialect, _expr, &m_functionSideEffects);
if (sideEffects.invalidatesStorage())
m_state.environment.storage.clear();
if (sideEffects.invalidatesMemory())
{
m_state.environment.memory.clear();
m_state.environment.keccak.clear();
}
}
bool DataFlowAnalyzer::inScope(YulName _variableName) const
{
for (auto const& scope: m_variableScopes | ranges::views::reverse)
{
if (scope.variables.count(_variableName))
return true;
if (scope.isFunction)
return false;
}
return false;
}
std::optional<u256> DataFlowAnalyzer::valueOfIdentifier(YulName const& _name) const
{
if (AssignedValue const* value = variableValue(_name))
if (Literal const* literal = std::get_if<Literal>(value->value))
return literal->value.value();
return std::nullopt;
}
std::optional<std::pair<YulName, YulName>> DataFlowAnalyzer::isSimpleStore(
StoreLoadLocation _location,
ExpressionStatement const& _statement
) const
{
if (FunctionCall const* funCall = std::get_if<FunctionCall>(&_statement.expression))
if (funCall->functionName.name == m_storeFunctionName[static_cast<unsigned>(_location)])
if (Identifier const* key = std::get_if<Identifier>(&funCall->arguments.front()))
if (Identifier const* value = std::get_if<Identifier>(&funCall->arguments.back()))
return std::make_pair(key->name, value->name);
return {};
}
std::optional<YulName> DataFlowAnalyzer::isSimpleLoad(
StoreLoadLocation _location,
Expression const& _expression
) const
{
if (FunctionCall const* funCall = std::get_if<FunctionCall>(&_expression))
if (funCall->functionName.name == m_loadFunctionName[static_cast<unsigned>(_location)])
if (Identifier const* key = std::get_if<Identifier>(&funCall->arguments.front()))
return key->name;
return {};
}
std::optional<std::pair<YulName, YulName>> DataFlowAnalyzer::isKeccak(Expression const& _expression) const
{
if (FunctionCall const* funCall = std::get_if<FunctionCall>(&_expression))
if (funCall->functionName.name.str() == m_dialect.builtin(*m_dialect.hashFunctionHandle()).name)
if (Identifier const* start = std::get_if<Identifier>(&funCall->arguments.at(0)))
if (Identifier const* length = std::get_if<Identifier>(&funCall->arguments.at(1)))
return std::make_pair(start->name, length->name);
return std::nullopt;
}
void DataFlowAnalyzer::joinKnowledge(Environment const& _olderEnvironment)
{
if (!m_analyzeStores)
return;
joinKnowledgeHelper(m_state.environment.storage, _olderEnvironment.storage);
joinKnowledgeHelper(m_state.environment.memory, _olderEnvironment.memory);
cxx20::erase_if(m_state.environment.keccak, mapTuple([&_olderEnvironment](auto&& key, auto&& currentValue) {
YulName const* oldValue = valueOrNullptr(_olderEnvironment.keccak, key);
return !oldValue || *oldValue != currentValue;
}));
}
void DataFlowAnalyzer::joinKnowledgeHelper(
std::unordered_map<YulName, YulName>& _this,
std::unordered_map<YulName, YulName> const& _older
)
{
// We clear if the key does not exist in the older map or if the value is different.
// This also works for memory because _older is an "older version"
// of m_state.environment.memory and thus any overlapping write would have cleared the keys
// that are not known to be different inside m_state.environment.memory already.
cxx20::erase_if(_this, mapTuple([&_older](auto&& key, auto&& currentValue){
YulName const* oldValue = valueOrNullptr(_older, key);
return !oldValue || *oldValue != currentValue;
}));
}
| 16,313
|
C++
|
.cpp
| 425
| 36
| 125
| 0.757516
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,128
|
FunctionSpecializer.cpp
|
ethereum_solidity/libyul/optimiser/FunctionSpecializer.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/FunctionSpecializer.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/AST.h>
#include <libyul/YulName.h>
#include <libsolutil/CommonData.h>
#include <range/v3/algorithm/any_of.hpp>
#include <range/v3/view/enumerate.hpp>
#include <variant>
using namespace solidity::util;
using namespace solidity::yul;
FunctionSpecializer::LiteralArguments FunctionSpecializer::specializableArguments(
FunctionCall const& _f
)
{
auto heuristic = [&](Expression const& _e) -> std::optional<Expression>
{
if (std::holds_alternative<Literal>(_e))
return ASTCopier{}.translate(_e);
return std::nullopt;
};
return applyMap(_f.arguments, heuristic);
}
void FunctionSpecializer::operator()(FunctionCall& _f)
{
ASTModifier::operator()(_f);
// TODO When backtracking is implemented, the restriction of recursive functions can be lifted.
if (
m_dialect.findBuiltin(_f.functionName.name.str()) ||
m_recursiveFunctions.count(_f.functionName.name)
)
return;
LiteralArguments arguments = specializableArguments(_f);
if (ranges::any_of(arguments, [](auto& _a) { return _a.has_value(); }))
{
YulName oldName = std::move(_f.functionName.name);
auto newName = m_nameDispenser.newName(oldName);
m_oldToNewMap[oldName].emplace_back(std::make_pair(newName, arguments));
_f.functionName.name = newName;
_f.arguments = util::filter(
_f.arguments,
applyMap(arguments, [](auto& _a) { return !_a; })
);
}
}
FunctionDefinition FunctionSpecializer::specialize(
FunctionDefinition const& _f,
YulName _newName,
FunctionSpecializer::LiteralArguments _arguments
)
{
yulAssert(_arguments.size() == _f.parameters.size(), "");
std::map<YulName, YulName> translatedNames = applyMap(
NameCollector{_f, NameCollector::OnlyVariables}.names(),
[&](auto& _name) -> std::pair<YulName, YulName>
{
return std::make_pair(_name, m_nameDispenser.newName(_name));
},
std::map<YulName, YulName>{}
);
FunctionDefinition newFunction = std::get<FunctionDefinition>(FunctionCopier{translatedNames}(_f));
// Function parameters that will be specialized inside the body are converted into variable
// declarations.
std::vector<Statement> missingVariableDeclarations;
for (auto&& [index, argument]: _arguments | ranges::views::enumerate)
if (argument)
missingVariableDeclarations.emplace_back(
VariableDeclaration{
_f.debugData,
std::vector<NameWithDebugData>{newFunction.parameters[index]},
std::make_unique<Expression>(std::move(*argument))
}
);
newFunction.body.statements =
std::move(missingVariableDeclarations) + std::move(newFunction.body.statements);
// Only take those indices that cannot be specialized, i.e., whose value is `nullopt`.
newFunction.parameters =
util::filter(
newFunction.parameters,
applyMap(_arguments, [&](auto const& _v) { return !_v; })
);
newFunction.name = std::move(_newName);
return newFunction;
}
void FunctionSpecializer::run(OptimiserStepContext& _context, Block& _ast)
{
FunctionSpecializer f{
CallGraphGenerator::callGraph(_ast).recursiveFunctions(),
_context.dispenser,
_context.dialect
};
f(_ast);
iterateReplacing(_ast.statements, [&](Statement& _s) -> std::optional<std::vector<Statement>>
{
if (std::holds_alternative<FunctionDefinition>(_s))
{
auto& functionDefinition = std::get<FunctionDefinition>(_s);
if (f.m_oldToNewMap.count(functionDefinition.name))
{
std::vector<Statement> out = applyMap(
f.m_oldToNewMap.at(functionDefinition.name),
[&](auto& _p) -> Statement
{
return f.specialize(functionDefinition, std::move(_p.first), std::move(_p.second));
}
);
return std::move(out) + make_vector<Statement>(std::move(functionDefinition));
}
}
return std::nullopt;
});
}
| 4,614
|
C++
|
.cpp
| 128
| 33.28125
| 100
| 0.748486
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,129
|
UnusedStoreEliminator.cpp
|
ethereum_solidity/libyul/optimiser/UnusedStoreEliminator.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that removes stores to memory and storage slots that are not used
* or overwritten later on.
*/
#include <libyul/optimiser/UnusedStoreEliminator.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/SSAValueTracker.h>
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libyul/optimiser/KnowledgeBase.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libyul/AST.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libsolutil/CommonData.h>
#include <libevmasm/Instruction.h>
#include <libevmasm/SemanticInformation.h>
#include <range/v3/algorithm/all_of.hpp>
using namespace solidity;
using namespace solidity::yul;
void UnusedStoreEliminator::run(OptimiserStepContext& _context, Block& _ast)
{
std::map<YulName, SideEffects> functionSideEffects = SideEffectsPropagator::sideEffects(
_context.dialect,
CallGraphGenerator::callGraph(_ast)
);
SSAValueTracker ssaValues;
ssaValues(_ast);
std::map<YulName, AssignedValue> values;
for (auto const& [name, expression]: ssaValues.values())
values[name] = AssignedValue{expression, {}};
bool const ignoreMemory = MSizeFinder::containsMSize(_context.dialect, _ast);
UnusedStoreEliminator rse{
_context.dialect,
functionSideEffects,
ControlFlowSideEffectsCollector{_context.dialect, _ast}.functionSideEffectsNamed(),
values,
ignoreMemory
};
rse(_ast);
auto evmDialect = dynamic_cast<EVMDialect const*>(&_context.dialect);
if (evmDialect && evmDialect->providesObjectAccess())
rse.clearActive(Location::Memory);
else
rse.markActiveAsUsed(Location::Memory);
rse.markActiveAsUsed(Location::Storage);
rse.m_storesToRemove += rse.m_allStores - rse.m_usedStores;
std::set<Statement const*> toRemove{rse.m_storesToRemove.begin(), rse.m_storesToRemove.end()};
StatementRemover remover{toRemove};
remover(_ast);
}
UnusedStoreEliminator::UnusedStoreEliminator(
Dialect const& _dialect,
std::map<YulName, SideEffects> const& _functionSideEffects,
std::map<YulName, ControlFlowSideEffects> _controlFlowSideEffects,
std::map<YulName, AssignedValue> const& _ssaValues,
bool _ignoreMemory
):
UnusedStoreBase(_dialect),
m_ignoreMemory(_ignoreMemory),
m_functionSideEffects(_functionSideEffects),
m_controlFlowSideEffects(_controlFlowSideEffects),
m_ssaValues(_ssaValues),
m_knowledgeBase(_ssaValues)
{}
void UnusedStoreEliminator::operator()(FunctionCall const& _functionCall)
{
UnusedStoreBase::operator()(_functionCall);
for (Operation const& op: operationsFromFunctionCall(_functionCall))
applyOperation(op);
ControlFlowSideEffects sideEffects;
if (std::optional<BuiltinHandle> const builtinHandle = m_dialect.findBuiltin(_functionCall.functionName.name.str()))
sideEffects = m_dialect.builtin(*builtinHandle).controlFlowSideEffects;
else
sideEffects = m_controlFlowSideEffects.at(_functionCall.functionName.name);
if (sideEffects.canTerminate)
markActiveAsUsed(Location::Storage);
if (!sideEffects.canContinue)
{
clearActive(Location::Memory);
if (!sideEffects.canTerminate)
clearActive(Location::Storage);
}
}
void UnusedStoreEliminator::operator()(FunctionDefinition const& _functionDefinition)
{
ScopedSaveAndRestore storeOperations(m_storeOperations, {});
UnusedStoreBase::operator()(_functionDefinition);
}
void UnusedStoreEliminator::operator()(Leave const&)
{
markActiveAsUsed();
}
void UnusedStoreEliminator::visit(Statement const& _statement)
{
using evmasm::Instruction;
UnusedStoreBase::visit(_statement);
auto const* exprStatement = std::get_if<ExpressionStatement>(&_statement);
if (!exprStatement)
return;
FunctionCall const* funCall = std::get_if<FunctionCall>(&exprStatement->expression);
yulAssert(funCall);
std::optional<Instruction> instruction = toEVMInstruction(m_dialect, funCall->functionName.name);
if (!instruction)
return;
if (!ranges::all_of(funCall->arguments, [](Expression const& _expr) -> bool {
return std::get_if<Identifier>(&_expr) || std::get_if<Literal>(&_expr);
}))
return;
// We determine if this is a store instruction without additional side-effects
// both by querying a combination of semantic information and by listing the instructions.
// This way the assert below should be triggered on any change.
using evmasm::SemanticInformation;
bool isStorageWrite = (*instruction == Instruction::SSTORE);
bool isMemoryWrite =
*instruction == Instruction::EXTCODECOPY ||
*instruction == Instruction::CODECOPY ||
*instruction == Instruction::CALLDATACOPY ||
*instruction == Instruction::RETURNDATACOPY ||
// TODO: Removing MCOPY is complicated because it's not just a store but also a load.
//*instruction == Instruction::MCOPY ||
*instruction == Instruction::MSTORE ||
*instruction == Instruction::MSTORE8;
bool isCandidateForRemoval =
*instruction != Instruction::MCOPY &&
SemanticInformation::otherState(*instruction) != SemanticInformation::Write && (
SemanticInformation::storage(*instruction) == SemanticInformation::Write ||
(!m_ignoreMemory && SemanticInformation::memory(*instruction) == SemanticInformation::Write)
);
yulAssert(isCandidateForRemoval == (isStorageWrite || (!m_ignoreMemory && isMemoryWrite)));
if (isCandidateForRemoval)
{
if (*instruction == Instruction::RETURNDATACOPY)
{
// Out-of-bounds access to the returndata buffer results in a revert,
// so we are careful not to remove a potentially reverting call to a builtin.
// The only way the Solidity compiler uses `returndatacopy` is
// `returndatacopy(X, 0, returndatasize())`, so we only allow to remove this pattern
// (which is guaranteed to never cause an out-of-bounds revert).
bool allowReturndatacopyToBeRemoved = false;
auto startOffset = identifierNameIfSSA(funCall->arguments.at(1));
auto length = identifierNameIfSSA(funCall->arguments.at(2));
if (length && startOffset)
{
FunctionCall const* lengthCall = std::get_if<FunctionCall>(m_ssaValues.at(*length).value);
if (
m_knowledgeBase.knownToBeZero(*startOffset) &&
lengthCall &&
toEVMInstruction(m_dialect, lengthCall->functionName.name) == Instruction::RETURNDATASIZE
)
allowReturndatacopyToBeRemoved = true;
}
if (!allowReturndatacopyToBeRemoved)
return;
}
m_allStores.insert(&_statement);
std::vector<Operation> operations = operationsFromFunctionCall(*funCall);
yulAssert(operations.size() == 1, "");
if (operations.front().location == Location::Storage)
activeStorageStores().insert(&_statement);
else
{
yulAssert(operations.front().location == Location::Memory, "");
activeMemoryStores().insert(&_statement);
}
m_storeOperations[&_statement] = std::move(operations.front());
}
}
std::vector<UnusedStoreEliminator::Operation> UnusedStoreEliminator::operationsFromFunctionCall(
FunctionCall const& _functionCall
) const
{
using evmasm::Instruction;
YulName functionName = _functionCall.functionName.name;
SideEffects sideEffects;
if (std::optional<BuiltinHandle> const builtinHandle = m_dialect.findBuiltin(functionName.str()))
sideEffects = m_dialect.builtin(*builtinHandle).sideEffects;
else
sideEffects = m_functionSideEffects.at(functionName);
std::optional<Instruction> instruction = toEVMInstruction(m_dialect, functionName);
if (!instruction)
{
std::vector<Operation> result;
// Unknown read is worse than unknown write.
if (sideEffects.memory != SideEffects::Effect::None)
result.emplace_back(Operation{Location::Memory, Effect::Read, {}, {}});
if (sideEffects.storage != SideEffects::Effect::None)
result.emplace_back(Operation{Location::Storage, Effect::Read, {}, {}});
return result;
}
using evmasm::SemanticInformation;
return util::applyMap(
SemanticInformation::readWriteOperations(*instruction),
[&](SemanticInformation::Operation const& _op) -> Operation
{
yulAssert(!(_op.lengthParameter && _op.lengthConstant));
yulAssert(_op.effect != Effect::None);
Operation ourOp{_op.location, _op.effect, {}, {}};
if (_op.startParameter)
ourOp.start = identifierNameIfSSA(_functionCall.arguments.at(*_op.startParameter));
if (_op.lengthParameter)
ourOp.length = identifierNameIfSSA(_functionCall.arguments.at(*_op.lengthParameter));
if (_op.lengthConstant)
switch (*_op.lengthConstant)
{
case 1: ourOp.length = u256(1); break;
case 32: ourOp.length = u256(32); break;
default: yulAssert(false);
}
return ourOp;
}
);
}
void UnusedStoreEliminator::applyOperation(UnusedStoreEliminator::Operation const& _operation)
{
std::set<Statement const*>& active =
_operation.location == Location::Storage ?
activeStorageStores() :
activeMemoryStores();
for (auto it = active.begin(); it != active.end();)
{
Statement const* statement = *it;
Operation const& storeOperation = m_storeOperations.at(statement);
if (_operation.effect == Effect::Read && !knownUnrelated(storeOperation, _operation))
{
// This store is read from, mark it as used and remove it from the active set.
m_usedStores.insert(statement);
it = active.erase(it);
}
else if (_operation.effect == Effect::Write && knownCovered(storeOperation, _operation))
// This store is overwritten before being read, remove it from the active set.
it = active.erase(it);
else
++it;
}
}
bool UnusedStoreEliminator::knownUnrelated(
UnusedStoreEliminator::Operation const& _op1,
UnusedStoreEliminator::Operation const& _op2
) const
{
if (_op1.location != _op2.location)
return true;
if (_op1.location == Location::Storage)
{
if (_op1.start && _op2.start)
{
yulAssert(
_op1.length &&
_op2.length &&
lengthValue(*_op1.length) == 1 &&
lengthValue(*_op2.length) == 1
);
return m_knowledgeBase.knownToBeDifferent(*_op1.start, *_op2.start);
}
}
else
{
yulAssert(_op1.location == Location::Memory, "");
if (
(_op1.length && lengthValue(*_op1.length) == 0) ||
(_op2.length && lengthValue(*_op2.length) == 0)
)
return true;
if (_op1.start && _op1.length && _op2.start)
{
std::optional<u256> length1 = lengthValue(*_op1.length);
std::optional<u256> start1 = m_knowledgeBase.valueIfKnownConstant(*_op1.start);
std::optional<u256> start2 = m_knowledgeBase.valueIfKnownConstant(*_op2.start);
if (
(length1 && start1 && start2) &&
*start1 + *length1 >= *start1 && // no overflow
*start1 + *length1 <= *start2
)
return true;
}
if (_op2.start && _op2.length && _op1.start)
{
std::optional<u256> length2 = lengthValue(*_op2.length);
std::optional<u256> start2 = m_knowledgeBase.valueIfKnownConstant(*_op2.start);
std::optional<u256> start1 = m_knowledgeBase.valueIfKnownConstant(*_op1.start);
if (
(length2 && start2 && start1) &&
*start2 + *length2 >= *start2 && // no overflow
*start2 + *length2 <= *start1
)
return true;
}
if (_op1.start && _op1.length && _op2.start && _op2.length)
{
std::optional<u256> length1 = lengthValue(*_op1.length);
std::optional<u256> length2 = lengthValue(*_op2.length);
if (
(length1 && *length1 <= 32) &&
(length2 && *length2 <= 32) &&
m_knowledgeBase.knownToBeDifferentByAtLeast32(*_op1.start, *_op2.start)
)
return true;
}
}
return false;
}
bool UnusedStoreEliminator::knownCovered(
UnusedStoreEliminator::Operation const& _covered,
UnusedStoreEliminator::Operation const& _covering
) const
{
if (_covered.location != _covering.location)
return false;
if (
(_covered.start && _covered.start == _covering.start) &&
(_covered.length && _covered.length == _covering.length)
)
return true;
if (_covered.location == Location::Memory)
{
if (_covered.length && lengthValue(*_covered.length) == 0)
return true;
// Condition (i = cover_i_ng, e = cover_e_d):
// i.start <= e.start && e.start + e.length <= i.start + i.length
if (!_covered.start || !_covering.start || !_covered.length || !_covering.length)
return false;
std::optional<u256> coveredLength = lengthValue(*_covered.length);
std::optional<u256> coveringLength = lengthValue(*_covering.length);
if (*_covered.start == *_covering.start)
if (coveredLength && coveringLength && *coveredLength <= *coveringLength)
return true;
std::optional<u256> coveredStart = m_knowledgeBase.valueIfKnownConstant(*_covered.start);
std::optional<u256> coveringStart = m_knowledgeBase.valueIfKnownConstant(*_covering.start);
if (coveredStart && coveringStart && coveredLength && coveringLength)
if (
*coveringStart <= *coveredStart &&
*coveringStart + *coveringLength >= *coveringStart && // no overflow
*coveredStart + *coveredLength >= *coveredStart && // no overflow
*coveredStart + *coveredLength <= *coveringStart + *coveringLength
)
return true;
// TODO for this we probably need a non-overflow assumption as above.
// Condition (i = cover_i_ng, e = cover_e_d):
// i.start <= e.start && e.start + e.length <= i.start + i.length
}
return false;
}
void UnusedStoreEliminator::markActiveAsUsed(
std::optional<UnusedStoreEliminator::Location> _onlyLocation
)
{
if (_onlyLocation == std::nullopt || _onlyLocation == Location::Memory)
for (Statement const* statement: activeMemoryStores())
m_usedStores.insert(statement);
if (_onlyLocation == std::nullopt || _onlyLocation == Location::Storage)
for (Statement const* statement: activeStorageStores())
m_usedStores.insert(statement);
clearActive(_onlyLocation);
}
void UnusedStoreEliminator::clearActive(
std::optional<UnusedStoreEliminator::Location> _onlyLocation
)
{
if (_onlyLocation == std::nullopt || _onlyLocation == Location::Memory)
activeMemoryStores() = {};
if (_onlyLocation == std::nullopt || _onlyLocation == Location::Storage)
activeStorageStores() = {};
}
std::optional<YulName> UnusedStoreEliminator::identifierNameIfSSA(Expression const& _expression) const
{
if (Identifier const* identifier = std::get_if<Identifier>(&_expression))
if (m_ssaValues.count(identifier->name))
return {identifier->name};
return std::nullopt;
}
| 14,825
|
C++
|
.cpp
| 385
| 35.664935
| 117
| 0.745432
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,130
|
SimplificationRules.cpp
|
ethereum_solidity/libyul/optimiser/SimplificationRules.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Module for applying replacement rules against Expressions.
*/
#include <libyul/optimiser/SimplificationRules.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/DataFlowAnalyzer.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/SyntacticalEquality.h>
#include <libevmasm/RuleList.h>
#include <libsolutil/StringUtils.h>
using namespace solidity;
using namespace solidity::evmasm;
using namespace solidity::langutil;
using namespace solidity::yul;
SimplificationRules::Rule const* SimplificationRules::findFirstMatch(
Expression const& _expr,
Dialect const& _dialect,
std::function<AssignedValue const*(YulName)> const& _ssaValues
)
{
auto instruction = instructionAndArguments(_dialect, _expr);
if (!instruction)
return nullptr;
static std::map<std::optional<EVMVersion>, std::unique_ptr<SimplificationRules>> evmRules;
std::optional<EVMVersion> version;
if (yul::EVMDialect const* evmDialect = dynamic_cast<yul::EVMDialect const*>(&_dialect))
version = evmDialect->evmVersion();
if (!evmRules[version])
evmRules[version] = std::make_unique<SimplificationRules>(version);
SimplificationRules& rules = *evmRules[version];
assertThrow(rules.isInitialized(), OptimizerException, "Rule list not properly initialized.");
for (auto const& rule: rules.m_rules[uint8_t(instruction->first)])
{
rules.resetMatchGroups();
if (rule.pattern.matches(_expr, _dialect, _ssaValues))
if (!rule.feasible || rule.feasible())
return &rule;
}
return nullptr;
}
bool SimplificationRules::isInitialized() const
{
return !m_rules[uint8_t(evmasm::Instruction::ADD)].empty();
}
std::optional<std::pair<evmasm::Instruction, std::vector<Expression> const*>>
SimplificationRules::instructionAndArguments(Dialect const& _dialect, Expression const& _expr)
{
if (std::holds_alternative<FunctionCall>(_expr))
if (auto const* dialect = dynamic_cast<EVMDialect const*>(&_dialect))
if (std::optional<BuiltinHandle> const builtinHandle = dialect->findBuiltin(std::get<FunctionCall>(_expr).functionName.name.str()))
if (auto const& instruction = dialect->builtin(*builtinHandle).instruction)
return std::make_pair(*instruction, &std::get<FunctionCall>(_expr).arguments);
return {};
}
void SimplificationRules::addRules(std::vector<Rule> const& _rules)
{
for (auto const& r: _rules)
addRule(r);
}
void SimplificationRules::addRule(Rule const& _rule)
{
m_rules[uint8_t(_rule.pattern.instruction())].push_back(_rule);
}
SimplificationRules::SimplificationRules(std::optional<langutil::EVMVersion> _evmVersion)
{
// Multiple occurrences of one of these inside one rule must match the same equivalence class.
// Constants.
Pattern A(PatternKind::Constant);
Pattern B(PatternKind::Constant);
Pattern C(PatternKind::Constant);
// Anything.
Pattern W;
Pattern X;
Pattern Y;
Pattern Z;
A.setMatchGroup(1, m_matchGroups);
B.setMatchGroup(2, m_matchGroups);
C.setMatchGroup(3, m_matchGroups);
W.setMatchGroup(4, m_matchGroups);
X.setMatchGroup(5, m_matchGroups);
Y.setMatchGroup(6, m_matchGroups);
Z.setMatchGroup(7, m_matchGroups);
addRules(simplificationRuleList(_evmVersion, A, B, C, W, X, Y, Z));
assertThrow(isInitialized(), OptimizerException, "Rule list not properly initialized.");
}
yul::Pattern::Pattern(evmasm::Instruction _instruction, std::initializer_list<Pattern> _arguments):
m_kind(PatternKind::Operation),
m_instruction(_instruction),
m_arguments(_arguments)
{
}
void Pattern::setMatchGroup(unsigned _group, std::map<unsigned, Expression const*>& _matchGroups)
{
m_matchGroup = _group;
m_matchGroups = &_matchGroups;
}
bool Pattern::matches(
Expression const& _expr,
Dialect const& _dialect,
std::function<AssignedValue const*(YulName)> const& _ssaValues
) const
{
Expression const* expr = &_expr;
// Resolve the variable if possible.
// Do not do it for "Any" because we can check identity better for variables.
if (m_kind != PatternKind::Any && std::holds_alternative<Identifier>(_expr))
{
YulName varName = std::get<Identifier>(_expr).name;
if (AssignedValue const* value = _ssaValues(varName))
if (Expression const* new_expr = value->value)
expr = new_expr;
}
assertThrow(expr, OptimizerException, "");
if (m_kind == PatternKind::Constant)
{
if (!std::holds_alternative<Literal>(*expr))
return false;
Literal const& literal = std::get<Literal>(*expr);
if (literal.kind != LiteralKind::Number)
return false;
if (m_data && *m_data != literal.value.value())
return false;
assertThrow(m_arguments.empty(), OptimizerException, "");
}
else if (m_kind == PatternKind::Operation)
{
auto instrAndArgs = SimplificationRules::instructionAndArguments(_dialect, *expr);
if (!instrAndArgs || m_instruction != instrAndArgs->first)
return false;
assertThrow(m_arguments.size() == instrAndArgs->second->size(), OptimizerException, "");
for (size_t i = 0; i < m_arguments.size(); ++i)
{
Expression const& arg = instrAndArgs->second->at(i);
// If this is a direct function call instead of a variable or literal,
// we reject the match because side-effects could prevent us from
// arbitrarily modifying the code.
if (
std::holds_alternative<FunctionCall>(arg) ||
!m_arguments[i].matches(arg, _dialect, _ssaValues)
)
return false;
}
}
else
{
assertThrow(m_arguments.empty(), OptimizerException, "\"Any\" should not have arguments.");
assertThrow(!std::holds_alternative<FunctionCall>(*expr), OptimizerException, "\"Any\" at top-level.");
}
if (m_matchGroup)
{
// We support matching multiple expressions that require the same value
// based on identical ASTs, which have to be movable.
// TODO: add tests:
// - { let x := mload(0) let y := and(x, x) }
// - { let x := 4 let y := and(x, y) }
// This code uses `_expr` again for "Any", because we want the comparison to be done
// on the variables and not their values.
// The assumption is that CSE or local value numbering has been done prior to this step.
if (m_matchGroups->count(m_matchGroup))
{
assertThrow(m_kind == PatternKind::Any, OptimizerException, "Match group repetition for non-any.");
Expression const* firstMatch = (*m_matchGroups)[m_matchGroup];
assertThrow(firstMatch, OptimizerException, "Match set but to null.");
assertThrow(
!std::holds_alternative<FunctionCall>(_expr) &&
!std::holds_alternative<FunctionCall>(*firstMatch),
OptimizerException,
"Group matches have to be literals or variables."
);
return SyntacticallyEqual{}(*firstMatch, _expr);
}
else if (m_kind == PatternKind::Any)
(*m_matchGroups)[m_matchGroup] = &_expr;
else
{
assertThrow(m_kind == PatternKind::Constant, OptimizerException, "Match group set for operation.");
// We do not use _expr here, because we want the actual number.
(*m_matchGroups)[m_matchGroup] = expr;
}
}
return true;
}
evmasm::Instruction Pattern::instruction() const
{
assertThrow(m_kind == PatternKind::Operation, OptimizerException, "");
return m_instruction;
}
Expression Pattern::toExpression(langutil::DebugData::ConstPtr const& _debugData, langutil::EVMVersion _evmVersion) const
{
if (matchGroup())
return ASTCopier().translate(matchGroupValue());
if (m_kind == PatternKind::Constant)
{
assertThrow(m_data, OptimizerException, "No match group and no constant value given.");
return Literal{_debugData, LiteralKind::Number, LiteralValue{*m_data, formatNumber(*m_data)}};
}
else if (m_kind == PatternKind::Operation)
{
std::vector<Expression> arguments;
for (auto const& arg: m_arguments)
arguments.emplace_back(arg.toExpression(_debugData, _evmVersion));
std::string name = util::toLower(instructionInfo(m_instruction, _evmVersion).name);
return FunctionCall{_debugData,
Identifier{_debugData, YulName{name}},
std::move(arguments)
};
}
assertThrow(false, OptimizerException, "Pattern of kind 'any', but no match group.");
}
u256 Pattern::d() const
{
return std::get<Literal>(matchGroupValue()).value.value();
}
Expression const& Pattern::matchGroupValue() const
{
assertThrow(m_matchGroup > 0, OptimizerException, "");
assertThrow(!!m_matchGroups, OptimizerException, "");
assertThrow((*m_matchGroups)[m_matchGroup], OptimizerException, "");
return *(*m_matchGroups)[m_matchGroup];
}
| 9,108
|
C++
|
.cpp
| 237
| 35.974684
| 134
| 0.747255
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,132
|
StackCompressor.cpp
|
ethereum_solidity/libyul/optimiser/StackCompressor.cpp
|
/*(
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Optimisation stage that aggressively rematerializes certain variables ina a function to free
* space on the stack until it is compilable.
*/
#include <libyul/optimiser/StackCompressor.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/Rematerialiser.h>
#include <libyul/optimiser/UnusedPruner.h>
#include <libyul/optimiser/Metrics.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/backends/evm/ControlFlowGraphBuilder.h>
#include <libyul/backends/evm/StackHelpers.h>
#include <libyul/backends/evm/StackLayoutGenerator.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/CompilabilityChecker.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
namespace
{
/**
* Class that discovers all variables that can be fully eliminated by rematerialization,
* and the corresponding approximate costs.
*
* Prerequisite: Disambiguator, Function Grouper
*/
class RematCandidateSelector: public DataFlowAnalyzer
{
public:
explicit RematCandidateSelector(Dialect const& _dialect): DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore) {}
/// @returns a map from function name to rematerialisation costs to a vector of variables to rematerialise
/// and variables that occur in their expression.
/// While the map is sorted by cost, the contained vectors are sorted by the order of occurrence.
std::map<YulName, std::map<size_t, std::vector<YulName>>> candidates()
{
std::map<YulName, std::map<size_t, std::vector<YulName>>> cand;
for (auto const& [functionName, candidate]: m_candidates)
{
if (size_t const* cost = util::valueOrNullptr(m_expressionCodeCost, candidate))
{
size_t numRef = m_numReferences[candidate];
cand[functionName][*cost * numRef].emplace_back(candidate);
}
}
return cand;
}
using DataFlowAnalyzer::operator();
void operator()(FunctionDefinition& _function) override
{
yulAssert(m_currentFunctionName.empty());
m_currentFunctionName = _function.name;
DataFlowAnalyzer::operator()(_function);
m_currentFunctionName = {};
}
void operator()(VariableDeclaration& _varDecl) override
{
DataFlowAnalyzer::operator()(_varDecl);
if (_varDecl.variables.size() == 1)
{
YulName varName = _varDecl.variables.front().name;
if (AssignedValue const* value = variableValue(varName))
{
yulAssert(!m_expressionCodeCost.count(varName), "");
m_candidates.emplace_back(m_currentFunctionName, varName);
m_expressionCodeCost[varName] = CodeCost::codeCost(m_dialect, *value->value);
}
}
}
void operator()(Assignment& _assignment) override
{
for (auto const& var: _assignment.variableNames)
rematImpossible(var.name);
DataFlowAnalyzer::operator()(_assignment);
}
// We use visit(Expression) because operator()(Identifier) would also
// get called on left-hand-sides of assignments.
void visit(Expression& _e) override
{
if (std::holds_alternative<Identifier>(_e))
{
YulName name = std::get<Identifier>(_e).name;
if (m_expressionCodeCost.count(name))
{
if (!variableValue(name))
rematImpossible(name);
else
++m_numReferences[name];
}
}
DataFlowAnalyzer::visit(_e);
}
/// Remove the variable from the candidate set.
void rematImpossible(YulName _variable)
{
m_numReferences.erase(_variable);
m_expressionCodeCost.erase(_variable);
}
YulName m_currentFunctionName = {};
/// All candidate variables by function name, in order of occurrence.
std::vector<std::pair<YulName, YulName>> m_candidates;
/// Candidate variables and the code cost of their value.
std::map<YulName, size_t> m_expressionCodeCost;
/// Number of references to each candidate variable.
std::map<YulName, size_t> m_numReferences;
};
/// Selects at most @a _numVariables among @a _candidates.
std::set<YulName> chooseVarsToEliminate(
std::map<size_t, std::vector<YulName>> const& _candidates,
size_t _numVariables
)
{
std::set<YulName> varsToEliminate;
for (auto&& [cost, candidates]: _candidates)
for (auto&& candidate: candidates)
{
if (varsToEliminate.size() >= _numVariables)
return varsToEliminate;
varsToEliminate.insert(candidate);
}
return varsToEliminate;
}
void eliminateVariables(
Dialect const& _dialect,
Block& _ast,
std::map<YulName, int> const& _numVariables,
bool _allowMSizeOptimization
)
{
RematCandidateSelector selector{_dialect};
selector(_ast);
std::map<YulName, std::map<size_t, std::vector<YulName>>> candidates = selector.candidates();
std::set<YulName> varsToEliminate;
for (auto const& [functionName, numVariables]: _numVariables)
{
yulAssert(numVariables > 0);
varsToEliminate += chooseVarsToEliminate(candidates[functionName], static_cast<size_t>(numVariables));
}
Rematerialiser::run(_dialect, _ast, std::move(varsToEliminate));
// Do not remove functions.
std::set<YulName> allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names();
UnusedPruner::runUntilStabilised(_dialect, _ast, _allowMSizeOptimization, nullptr, allFunctions);
}
void eliminateVariablesOptimizedCodegen(
Dialect const& _dialect,
Block& _ast,
std::map<YulName, std::vector<StackLayoutGenerator::StackTooDeep>> const& _unreachables,
bool _allowMSizeOptimization
)
{
if (std::all_of(_unreachables.begin(), _unreachables.end(), [](auto const& _item) { return _item.second.empty(); }))
return;
RematCandidateSelector selector{_dialect};
selector(_ast);
std::map<YulName, size_t> candidates;
for (auto const& [functionName, candidatesInFunction]: selector.candidates())
for (auto [cost, candidatesWithCost]: candidatesInFunction)
for (auto candidate: candidatesWithCost)
candidates[candidate] = cost;
std::set<YulName> varsToEliminate;
// TODO: this currently ignores the fact that variables may reference other variables we want to eliminate.
for (auto const& [functionName, unreachables]: _unreachables)
for (auto const& unreachable: unreachables)
{
std::map<size_t, std::vector<YulName>> suitableCandidates;
size_t neededSlots = unreachable.deficit;
for (auto varName: unreachable.variableChoices)
{
if (varsToEliminate.count(varName))
--neededSlots;
else if (size_t* cost = util::valueOrNullptr(candidates, varName))
if (!util::contains(suitableCandidates[*cost], varName))
suitableCandidates[*cost].emplace_back(varName);
}
for (auto candidatesByCost: suitableCandidates)
{
for (auto candidate: candidatesByCost.second)
if (neededSlots--)
varsToEliminate.emplace(candidate);
else
break;
if (!neededSlots)
break;
}
}
Rematerialiser::run(_dialect, _ast, std::move(varsToEliminate), true);
// Do not remove functions.
std::set<YulName> allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names();
UnusedPruner::runUntilStabilised(_dialect, _ast, _allowMSizeOptimization, nullptr, allFunctions);
}
}
std::tuple<bool, Block> StackCompressor::run(
Dialect const& _dialect,
Object const& _object,
bool _optimizeStackAllocation,
size_t _maxIterations)
{
yulAssert(_object.hasCode());
yulAssert(
!_object.code()->root().statements.empty() && std::holds_alternative<Block>(_object.code()->root().statements.at(0)),
"Need to run the function grouper before the stack compressor."
);
bool usesOptimizedCodeGenerator = false;
if (auto evmDialect = dynamic_cast<EVMDialect const*>(&_dialect))
usesOptimizedCodeGenerator =
_optimizeStackAllocation &&
evmDialect->evmVersion().canOverchargeGasForCall() &&
evmDialect->providesObjectAccess();
bool allowMSizeOptimization = !MSizeFinder::containsMSize(_dialect, _object.code()->root());
Block astRoot = std::get<Block>(ASTCopier{}(_object.code()->root()));
if (usesOptimizedCodeGenerator)
{
yul::AsmAnalysisInfo analysisInfo = yul::AsmAnalyzer::analyzeStrictAssertCorrect(
_dialect,
astRoot,
_object.summarizeStructure()
);
std::unique_ptr<CFG> cfg = ControlFlowGraphBuilder::build(analysisInfo, _dialect, astRoot);
eliminateVariablesOptimizedCodegen(
_dialect,
astRoot,
StackLayoutGenerator::reportStackTooDeep(*cfg),
allowMSizeOptimization
);
}
else
{
for (size_t iterations = 0; iterations < _maxIterations; iterations++)
{
Object object(_object);
object.setCode(std::make_shared<AST>(std::get<Block>(ASTCopier{}(astRoot))));
std::map<YulName, int> stackSurplus = CompilabilityChecker(_dialect, object, _optimizeStackAllocation).stackDeficit;
if (stackSurplus.empty())
return std::make_tuple(true, std::move(astRoot));
eliminateVariables(
_dialect,
astRoot,
stackSurplus,
allowMSizeOptimization
);
}
}
return std::make_tuple(false, std::move(astRoot));
}
| 9,441
|
C++
|
.cpp
| 259
| 33.656371
| 119
| 0.757788
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,134
|
FunctionCallFinder.cpp
|
ethereum_solidity/libyul/optimiser/FunctionCallFinder.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libyul/optimiser/FunctionCallFinder.h>
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/AST.h>
using namespace solidity;
using namespace solidity::yul;
namespace
{
template<typename Base, typename ResultType>
class MaybeConstFunctionCallFinder: Base
{
public:
using MaybeConstBlock = std::conditional_t<std::is_const_v<ResultType>, Block const, Block>;
static std::vector<ResultType*> run(MaybeConstBlock& _block, YulName const _functionName)
{
MaybeConstFunctionCallFinder functionCallFinder(_functionName);
functionCallFinder(_block);
return functionCallFinder.m_calls;
}
private:
explicit MaybeConstFunctionCallFinder(YulName const _functionName): m_functionName(_functionName), m_calls() {}
using Base::operator();
void operator()(ResultType& _functionCall) override
{
Base::operator()(_functionCall);
if (_functionCall.functionName.name == m_functionName)
m_calls.emplace_back(&_functionCall);
}
YulName m_functionName;
std::vector<ResultType*> m_calls;
};
}
std::vector<FunctionCall*> solidity::yul::findFunctionCalls(Block& _block, YulName _functionName)
{
return MaybeConstFunctionCallFinder<ASTModifier, FunctionCall>::run(_block, _functionName);
}
std::vector<FunctionCall const*> solidity::yul::findFunctionCalls(Block const& _block, YulName _functionName)
{
return MaybeConstFunctionCallFinder<ASTWalker, FunctionCall const>::run(_block, _functionName);
}
| 2,067
|
C++
|
.cpp
| 52
| 37.865385
| 112
| 0.799103
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,135
|
UnusedFunctionsCommon.cpp
|
ethereum_solidity/libyul/optimiser/UnusedFunctionsCommon.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/UnusedFunctionsCommon.h>
#include <libyul/Dialect.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::yul;
using namespace solidity::yul::unusedFunctionsCommon;
FunctionDefinition unusedFunctionsCommon::createLinkingFunction(
FunctionDefinition const& _original,
std::pair<std::vector<bool>, std::vector<bool>> const& _usedParametersAndReturns,
YulName const& _originalFunctionName,
YulName const& _linkingFunctionName,
NameDispenser& _nameDispenser
)
{
auto generateTypedName = [&](NameWithDebugData t)
{
return NameWithDebugData{
t.debugData,
_nameDispenser.newName(t.name)
};
};
FunctionDefinition linkingFunction{
_original.debugData,
_linkingFunctionName,
util::applyMap(_original.parameters, generateTypedName),
util::applyMap(_original.returnVariables, generateTypedName),
{_original.debugData, {}} // body
};
FunctionCall call{_original.debugData, Identifier{_original.debugData, _originalFunctionName}, {}};
for (auto const& p: filter(linkingFunction.parameters, _usedParametersAndReturns.first))
call.arguments.emplace_back(Identifier{_original.debugData, p.name});
Assignment assignment{_original.debugData, {}, nullptr};
for (auto const& r: filter(linkingFunction.returnVariables, _usedParametersAndReturns.second))
assignment.variableNames.emplace_back(Identifier{_original.debugData, r.name});
if (assignment.variableNames.empty())
linkingFunction.body.statements.emplace_back(ExpressionStatement{_original.debugData, std::move(call)});
else
{
assignment.value = std::make_unique<Expression>(std::move(call));
linkingFunction.body.statements.emplace_back(std::move(assignment));
}
return linkingFunction;
}
| 2,463
|
C++
|
.cpp
| 58
| 40.189655
| 106
| 0.800084
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,137
|
ForLoopConditionIntoBody.cpp
|
ethereum_solidity/libyul/optimiser/ForLoopConditionIntoBody.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libyul/optimiser/ForLoopConditionIntoBody.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/AST.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
void ForLoopConditionIntoBody::run(OptimiserStepContext& _context, Block& _ast)
{
ForLoopConditionIntoBody{_context.dialect}(_ast);
}
void ForLoopConditionIntoBody::operator()(ForLoop& _forLoop)
{
if (
m_dialect.booleanNegationFunctionHandle() &&
!std::holds_alternative<Literal>(*_forLoop.condition) &&
!std::holds_alternative<Identifier>(*_forLoop.condition)
)
{
langutil::DebugData::ConstPtr debugData = debugDataOf(*_forLoop.condition);
_forLoop.body.statements.emplace(
begin(_forLoop.body.statements),
If {
debugData,
std::make_unique<Expression>(
FunctionCall {
debugData,
{debugData, YulName{m_dialect.builtin(*m_dialect.booleanNegationFunctionHandle()).name}},
util::make_vector<Expression>(std::move(*_forLoop.condition))
}
),
Block {debugData, util::make_vector<Statement>(Break{{}})}
}
);
_forLoop.condition = std::make_unique<Expression>(
Literal {
debugData,
LiteralKind::Boolean,
LiteralValue{true}
}
);
}
ASTModifier::operator()(_forLoop);
}
| 1,958
|
C++
|
.cpp
| 57
| 31.350877
| 95
| 0.756742
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,142
|
UnusedAssignEliminator.cpp
|
ethereum_solidity/libyul/optimiser/UnusedAssignEliminator.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that removes assignments to variables that are not used
* until they go out of scope or are re-assigned.
*/
#include <libyul/optimiser/UnusedAssignEliminator.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libyul/AST.h>
#include <libyul/AsmPrinter.h>
#include <libsolutil/CommonData.h>
#include <range/v3/action/remove_if.hpp>
#include <iostream>
using namespace solidity;
using namespace solidity::yul;
void UnusedAssignEliminator::run(OptimiserStepContext& _context, Block& _ast)
{
UnusedAssignEliminator uae{
_context.dialect,
ControlFlowSideEffectsCollector{_context.dialect, _ast}.functionSideEffectsNamed()
};
uae(_ast);
uae.m_storesToRemove += uae.m_allStores - uae.m_usedStores;
std::set<Statement const*> toRemove{uae.m_storesToRemove.begin(), uae.m_storesToRemove.end()};
StatementRemover remover{toRemove};
remover(_ast);
}
void UnusedAssignEliminator::operator()(Identifier const& _identifier)
{
markUsed(_identifier.name);
}
void UnusedAssignEliminator::operator()(Assignment const& _assignment)
{
visit(*_assignment.value);
// Do not visit the variables because they are Identifiers
}
void UnusedAssignEliminator::operator()(FunctionDefinition const& _functionDefinition)
{
ScopedSaveAndRestore outerReturnVariables(m_returnVariables, {});
for (auto const& retParam: _functionDefinition.returnVariables)
m_returnVariables.insert(retParam.name);
UnusedStoreBase::operator()(_functionDefinition);
}
void UnusedAssignEliminator::operator()(FunctionCall const& _functionCall)
{
UnusedStoreBase::operator()(_functionCall);
ControlFlowSideEffects sideEffects;
if (std::optional<BuiltinHandle> const builtinHandle = m_dialect.findBuiltin(_functionCall.functionName.name.str()))
sideEffects = m_dialect.builtin(*builtinHandle).controlFlowSideEffects;
else
sideEffects = m_controlFlowSideEffects.at(_functionCall.functionName.name);
if (!sideEffects.canContinue)
// We do not return from the current function, so it is OK to also
// clear the return variables.
m_activeStores.clear();
}
void UnusedAssignEliminator::operator()(Leave const&)
{
for (YulName name: m_returnVariables)
markUsed(name);
m_activeStores.clear();
}
void UnusedAssignEliminator::operator()(Block const& _block)
{
UnusedStoreBase::operator()(_block);
for (auto const& statement: _block.statements)
if (auto const* varDecl = std::get_if<VariableDeclaration>(&statement))
for (auto const& var: varDecl->variables)
m_activeStores.erase(var.name);
}
void UnusedAssignEliminator::visit(Statement const& _statement)
{
UnusedStoreBase::visit(_statement);
if (auto const* assignment = std::get_if<Assignment>(&_statement))
{
// We do not remove assignments whose values might have side-effects,
// but clear the active stores to the assigned variables in any case.
if (SideEffectsCollector{m_dialect, *assignment->value}.movable())
{
m_allStores.insert(&_statement);
for (auto const& var: assignment->variableNames)
m_activeStores[var.name] = {&_statement};
}
else
for (auto const& var: assignment->variableNames)
m_activeStores[var.name].clear();
}
}
void UnusedAssignEliminator::shortcutNestedLoop(ActiveStores const& _zeroRuns)
{
// Shortcut to avoid horrible runtime:
// Change all assignments that were newly introduced in the for loop to "used".
// We do not have to do that with the "break" or "continue" paths, because
// they will be joined later anyway.
for (auto& [variable, stores]: m_activeStores)
{
auto zeroIt = _zeroRuns.find(variable);
for (auto& assignment: stores)
{
if (zeroIt != _zeroRuns.end() && zeroIt->second.count(assignment))
continue;
m_usedStores.insert(assignment);
}
}
}
void UnusedAssignEliminator::finalizeFunctionDefinition(FunctionDefinition const& _functionDefinition)
{
for (auto const& retParam: _functionDefinition.returnVariables)
markUsed(retParam.name);
}
void UnusedAssignEliminator::markUsed(YulName _variable)
{
for (auto& assignment: m_activeStores[_variable])
m_usedStores.insert(assignment);
m_activeStores.erase(_variable);
}
| 4,905
|
C++
|
.cpp
| 130
| 35.515385
| 117
| 0.783562
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,144
|
NameDispenser.cpp
|
ethereum_solidity/libyul/optimiser/NameDispenser.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* Optimiser component that can create new unique names.
*/
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/optimiser/NameCollector.h>
#include <libyul/optimiser/OptimizerUtilities.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libsolutil/CommonData.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::util;
NameDispenser::NameDispenser(Dialect const& _dialect, Block const& _ast, std::set<YulName> _reservedNames):
NameDispenser(_dialect, NameCollector(_ast).names() + _reservedNames)
{
m_reservedNames = std::move(_reservedNames);
}
NameDispenser::NameDispenser(Dialect const& _dialect, std::set<YulName> _usedNames):
m_dialect(_dialect),
m_usedNames(std::move(_usedNames))
{
}
YulName NameDispenser::newName(YulName _nameHint)
{
YulName name = _nameHint;
while (illegalName(name))
{
m_counter++;
name = YulName(_nameHint.str() + "_" + std::to_string(m_counter));
}
m_usedNames.emplace(name);
return name;
}
bool NameDispenser::illegalName(YulName _name)
{
return isRestrictedIdentifier(m_dialect, _name) || m_usedNames.count(_name);
}
void NameDispenser::reset(Block const& _ast)
{
m_usedNames = NameCollector(_ast).names() + m_reservedNames;
m_counter = 0;
}
| 1,944
|
C++
|
.cpp
| 56
| 32.964286
| 107
| 0.773987
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
3,146
|
Transport.cpp
|
ethereum_solidity/libsolidity/lsp/Transport.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/lsp/Transport.h>
#include <libsolidity/lsp/Utils.h>
#include <libsolutil/JSON.h>
#include <libsolutil/Visitor.h>
#include <libsolutil/CommonIO.h>
#include <liblangutil/Exceptions.h>
#include <fmt/format.h>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <sstream>
#include <string>
#if defined(_WIN32)
#include <io.h>
#include <fcntl.h>
#endif
using namespace solidity::lsp;
using namespace solidity;
// {{{ Transport
std::optional<Json> Transport::receive()
{
auto const headers = parseHeaders();
if (!headers)
{
error({}, ErrorCode::ParseError, "Could not parse RPC headers.");
return std::nullopt;
}
if (!headers->count("content-length"))
{
error({}, ErrorCode::ParseError, "No content-length header found.");
return std::nullopt;
}
std::string const data = readBytes(stoul(headers->at("content-length")));
Json jsonMessage;
std::string jsonParsingErrors;
solidity::util::jsonParseStrict(data, jsonMessage, &jsonParsingErrors);
if (!jsonParsingErrors.empty() || jsonMessage.empty() || !jsonMessage.is_object())
{
error({}, ErrorCode::ParseError, "Could not parse RPC JSON payload. " + jsonParsingErrors);
return std::nullopt;
}
return {std::move(jsonMessage)};
}
void Transport::trace(std::string _message, Json _extra)
{
if (m_logTrace != TraceValue::Off)
{
Json params;
if (_extra.is_object())
params = std::move(_extra);
params["message"] = std::move(_message);
notify("$/logTrace", std::move(params));
}
}
std::optional<std::map<std::string, std::string>> Transport::parseHeaders()
{
std::map<std::string, std::string> headers;
while (true)
{
auto line = getline();
if (boost::trim_copy(line).empty())
break;
auto const delimiterPos = line.find(':');
if (delimiterPos == std::string::npos)
return std::nullopt;
auto const name = boost::to_lower_copy(line.substr(0, delimiterPos));
auto const value = line.substr(delimiterPos + 1);
if (!headers.emplace(boost::trim_copy(name), boost::trim_copy(value)).second)
return std::nullopt;
}
return {std::move(headers)};
}
void Transport::notify(std::string _method, Json _message)
{
Json json;
json["method"] = std::move(_method);
json["params"] = std::move(_message);
send(std::move(json));
}
void Transport::reply(MessageID _id, Json _message)
{
Json json;
json["result"] = std::move(_message);
send(std::move(json), _id);
}
void Transport::error(MessageID _id, ErrorCode _code, std::string _message)
{
Json json;
json["error"]["code"] = static_cast<int>(_code);
json["error"]["message"] = std::move(_message);
send(std::move(json), _id);
}
void Transport::send(Json _json, MessageID _id)
{
solAssert(_json.is_object());
_json["jsonrpc"] = "2.0";
if (_id != Json())
_json["id"] = _id;
// Trailing CRLF only for easier readability.
std::string const jsonString = solidity::util::jsonCompactPrint(_json);
writeBytes(fmt::format("Content-Length: {}\r\n\r\n", jsonString.size()));
writeBytes(jsonString);
flushOutput();
}
// }}}
// {{{ IOStreamTransport
IOStreamTransport::IOStreamTransport(std::istream& _in, std::ostream& _out):
m_input{_in},
m_output{_out}
{
}
bool IOStreamTransport::closed() const noexcept
{
return m_input.eof();
}
std::string IOStreamTransport::readBytes(size_t _length)
{
return util::readBytes(m_input, _length);
}
std::string IOStreamTransport::getline()
{
std::string line;
std::getline(m_input, line);
return line;
}
void IOStreamTransport::writeBytes(std::string_view _data)
{
m_output.write(_data.data(), static_cast<std::streamsize>(_data.size()));
}
void IOStreamTransport::flushOutput()
{
m_output.flush();
}
// }}}
// {{{ StdioTransport
StdioTransport::StdioTransport()
{
#if defined(_WIN32)
// Attempt to change the modes of stdout from text to binary.
setmode(fileno(stdout), O_BINARY);
#endif
}
bool StdioTransport::closed() const noexcept
{
return feof(stdin);
}
std::string StdioTransport::readBytes(size_t _byteCount)
{
std::string buffer;
buffer.resize(_byteCount);
auto const n = fread(buffer.data(), 1, _byteCount, stdin);
if (n < _byteCount)
buffer.resize(n);
return buffer;
}
std::string StdioTransport::getline()
{
std::string line;
std::getline(std::cin, line);
lspDebug(fmt::format("Received: {}", line));
return line;
}
void StdioTransport::writeBytes(std::string_view _data)
{
lspDebug(fmt::format("Sending: {}", _data));
auto const bytesWritten = fwrite(_data.data(), 1, _data.size(), stdout);
solAssert(bytesWritten == _data.size());
}
void StdioTransport::flushOutput()
{
fflush(stdout);
}
// }}}
| 5,277
|
C++
|
.cpp
| 186
| 26.467742
| 93
| 0.725905
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,147
|
HandlerBase.cpp
|
ethereum_solidity/libsolidity/lsp/HandlerBase.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolutil/Exceptions.h>
#include <libsolidity/lsp/HandlerBase.h>
#include <libsolidity/lsp/LanguageServer.h>
#include <libsolidity/lsp/Utils.h>
#include <libsolidity/ast/AST.h>
#include <liblangutil/Exceptions.h>
#include <fmt/format.h>
using namespace solidity::langutil;
using namespace solidity::lsp;
using namespace solidity::util;
using namespace solidity;
Json HandlerBase::toRange(SourceLocation const& _location) const
{
if (!_location.hasText())
return toJsonRange({}, {});
solAssert(_location.sourceName, "");
langutil::CharStream const& stream = charStreamProvider().charStream(*_location.sourceName);
LineColumn start = stream.translatePositionToLineColumn(_location.start);
LineColumn end = stream.translatePositionToLineColumn(_location.end);
return toJsonRange(start, end);
}
Json HandlerBase::toJson(SourceLocation const& _location) const
{
solAssert(_location.sourceName);
Json item;
item["uri"] = fileRepository().sourceUnitNameToUri(*_location.sourceName);
item["range"] = toRange(_location);
return item;
}
std::pair<std::string, LineColumn> HandlerBase::extractSourceUnitNameAndLineColumn(Json const& _args) const
{
std::string const uri = _args["textDocument"]["uri"].get<std::string>();
std::string const sourceUnitName = fileRepository().uriToSourceUnitName(uri);
if (!fileRepository().sourceUnits().count(sourceUnitName))
BOOST_THROW_EXCEPTION(
RequestError(ErrorCode::RequestFailed) <<
errinfo_comment("Unknown file: " + uri)
);
auto const lineColumn = parseLineColumn(_args["position"]);
if (!lineColumn)
BOOST_THROW_EXCEPTION(
RequestError(ErrorCode::RequestFailed) <<
errinfo_comment(fmt::format(
"Unknown position {line}:{column} in file: {file}",
fmt::arg("line", lineColumn.value().line),
fmt::arg("column", lineColumn.value().column),
fmt::arg("file", sourceUnitName)
))
);
return {sourceUnitName, *lineColumn};
}
| 2,611
|
C++
|
.cpp
| 65
| 37.907692
| 107
| 0.771812
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,148
|
RenameSymbol.cpp
|
ethereum_solidity/libsolidity/lsp/RenameSymbol.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/lsp/RenameSymbol.h>
#include <libsolidity/lsp/Utils.h>
#include <libyul/AST.h>
#include <fmt/format.h>
#include <memory>
#include <string>
#include <vector>
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::lsp;
namespace
{
CallableDeclaration const* extractCallableDeclaration(FunctionCall const& _functionCall)
{
if (
auto const* functionType = dynamic_cast<FunctionType const*>(_functionCall.expression().annotation().type);
functionType && functionType->hasDeclaration()
)
if (auto const* functionDefinition = dynamic_cast<FunctionDefinition const*>(&functionType->declaration()))
return functionDefinition;
return nullptr;
}
}
void RenameSymbol::operator()(MessageID _id, Json const& _args)
{
auto const&& [sourceUnitName, lineColumn] = extractSourceUnitNameAndLineColumn(_args);
std::string const newName = _args["newName"].get<std::string>();
std::string const uri = _args["textDocument"]["uri"].get<std::string>();
ASTNode const* sourceNode = m_server.astNodeAtSourceLocation(sourceUnitName, lineColumn);
m_symbolName = {};
m_declarationToRename = nullptr;
m_sourceUnits = { &m_server.compilerStack().ast(sourceUnitName) };
m_locations.clear();
std::optional<int> cursorBytePosition = charStreamProvider()
.charStream(sourceUnitName)
.translateLineColumnToPosition(lineColumn);
solAssert(cursorBytePosition.has_value(), "Expected source pos");
extractNameAndDeclaration(*sourceNode, *cursorBytePosition);
// Find all source units using this symbol
for (auto const& [name, content]: fileRepository().sourceUnits())
{
auto const& sourceUnit = m_server.compilerStack().ast(name);
for (auto const* referencedSourceUnit: sourceUnit.referencedSourceUnits(true, util::convertContainer<std::set<SourceUnit const*>>(m_sourceUnits)))
if (*referencedSourceUnit->location().sourceName == sourceUnitName)
{
m_sourceUnits.insert(&sourceUnit);
break;
}
}
// Origin source unit should always be checked
m_sourceUnits.insert(&m_declarationToRename->sourceUnit());
Visitor visitor(*this);
for (auto const* sourceUnit: m_sourceUnits)
sourceUnit->accept(visitor);
// Apply changes in reverse order (will iterate in reverse)
sort(m_locations.begin(), m_locations.end());
Json reply;
reply["changes"] = Json::object();
Json edits = Json::array();
for (auto i = m_locations.rbegin(); i != m_locations.rend(); i++)
{
solAssert(i->isValid());
// Replace in our file repository
std::string const uri = fileRepository().sourceUnitNameToUri(*i->sourceName);
std::string buffer = fileRepository().sourceUnits().at(*i->sourceName);
buffer.replace((size_t)i->start, (size_t)(i->end - i->start), newName);
fileRepository().setSourceByUri(uri, std::move(buffer));
Json edit;
edit["range"] = toRange(*i);
edit["newText"] = newName;
// Record changes for the client
edits.emplace_back(edit);
if (i + 1 == m_locations.rend() || (i + 1)->sourceName != i->sourceName)
{
reply["changes"][uri] = edits;
edits = Json::array(); // Reset.
}
}
client().reply(_id, reply);
}
void RenameSymbol::extractNameAndDeclaration(ASTNode const& _node, int _cursorBytePosition)
{
// Identify symbol name and node
if (auto const* declaration = dynamic_cast<Declaration const*>(&_node))
{
if (declaration->nameLocation().containsOffset(_cursorBytePosition))
{
m_symbolName = declaration->name();
m_declarationToRename = declaration;
}
else if (auto const* importDirective = dynamic_cast<ImportDirective const*>(declaration))
extractNameAndDeclaration(*importDirective, _cursorBytePosition);
}
else if (auto const* identifier = dynamic_cast<Identifier const*>(&_node))
{
if (auto const* declReference = dynamic_cast<Declaration const*>(identifier->annotation().referencedDeclaration))
{
m_symbolName = identifier->name();
m_declarationToRename = declReference;
}
}
else if (auto const* identifierPath = dynamic_cast<IdentifierPath const*>(&_node))
extractNameAndDeclaration(*identifierPath, _cursorBytePosition);
else if (auto const* memberAccess = dynamic_cast<MemberAccess const*>(&_node))
{
m_symbolName = memberAccess->memberName();
m_declarationToRename = memberAccess->annotation().referencedDeclaration;
}
else if (auto const* functionCall = dynamic_cast<FunctionCall const*>(&_node))
extractNameAndDeclaration(*functionCall, _cursorBytePosition);
else if (auto const* inlineAssembly = dynamic_cast<InlineAssembly const*>(&_node))
extractNameAndDeclaration(*inlineAssembly, _cursorBytePosition);
else
solAssert(false, "Unexpected ASTNODE id: " + std::to_string(_node.id()));
lspDebug(fmt::format("Goal: rename '{}', loc: {}-{}", m_symbolName, m_declarationToRename->nameLocation().start, m_declarationToRename->nameLocation().end));
}
void RenameSymbol::extractNameAndDeclaration(ImportDirective const& _importDirective, int _cursorBytePosition)
{
for (ImportDirective::SymbolAlias const& symbolAlias: _importDirective.symbolAliases())
if (symbolAlias.location.containsOffset(_cursorBytePosition))
{
solAssert(symbolAlias.alias);
m_symbolName = *symbolAlias.alias;
m_declarationToRename = symbolAlias.symbol->annotation().referencedDeclaration;
break;
}
}
void RenameSymbol::Visitor::endVisit(ImportDirective const& _node)
{
// Handles SourceUnit aliases
if (handleGenericDeclaration(_node))
return;
for (ImportDirective::SymbolAlias const& symbolAlias: _node.symbolAliases())
if (
symbolAlias.alias != nullptr &&
*symbolAlias.alias == m_outer.m_symbolName &&
symbolAlias.symbol->annotation().referencedDeclaration == m_outer.m_declarationToRename
)
m_outer.m_locations.emplace_back(symbolAlias.location);
}
void RenameSymbol::extractNameAndDeclaration(FunctionCall const& _functionCall, int _cursorBytePosition)
{
if (auto const* functionDefinition = extractCallableDeclaration(_functionCall))
for (size_t i = 0; i < _functionCall.names().size(); i++)
if (_functionCall.nameLocations()[i].containsOffset(_cursorBytePosition))
{
m_symbolName = *_functionCall.names()[i];
for (size_t j = 0; j < functionDefinition->parameters().size(); j++)
if (
functionDefinition->parameters()[j] &&
functionDefinition->parameters()[j]->name() == m_symbolName
)
m_declarationToRename = functionDefinition->parameters()[j].get();
return;
}
}
void RenameSymbol::Visitor::endVisit(FunctionCall const& _node)
{
SourceLocation nameLocationInFunctionCall;
for (size_t i = 0; i < _node.names().size(); i++)
if (_node.names()[i] && *_node.names()[i] == m_outer.m_symbolName)
nameLocationInFunctionCall = _node.nameLocations()[i];
if (!nameLocationInFunctionCall.isValid())
return;
if (auto const* functionDefinition = extractCallableDeclaration(_node))
for (size_t j = 0; j < functionDefinition->parameters().size(); j++)
if (
functionDefinition->parameters()[j] &&
*functionDefinition->parameters()[j] == *m_outer.m_declarationToRename
)
m_outer.m_locations.emplace_back(nameLocationInFunctionCall);
}
void RenameSymbol::Visitor::endVisit(MemberAccess const& _node)
{
if (
m_outer.m_symbolName == _node.memberName() &&
*m_outer.m_declarationToRename == *_node.annotation().referencedDeclaration
)
m_outer.m_locations.emplace_back(_node.memberLocation());
}
void RenameSymbol::Visitor::endVisit(Identifier const& _node)
{
if (
m_outer.m_symbolName == _node.name() &&
*m_outer.m_declarationToRename == *_node.annotation().referencedDeclaration
)
m_outer.m_locations.emplace_back(_node.location());
}
void RenameSymbol::extractNameAndDeclaration(IdentifierPath const& _identifierPath, int _cursorBytePosition)
{
// iterate through the elements of the path to find the one the cursor is on
size_t numIdentifiers = _identifierPath.pathLocations().size();
for (size_t i = 0; i < numIdentifiers; i++)
{
auto& location = _identifierPath.pathLocations()[i];
if (location.containsOffset(_cursorBytePosition))
{
solAssert(_identifierPath.annotation().pathDeclarations.size() == numIdentifiers);
solAssert(_identifierPath.path().size() == numIdentifiers);
m_declarationToRename = _identifierPath.annotation().pathDeclarations[i];
m_symbolName = _identifierPath.path()[i];
}
}
}
void RenameSymbol::Visitor::endVisit(IdentifierPath const& _node)
{
std::vector<Declaration const*>& declarations = _node.annotation().pathDeclarations;
solAssert(declarations.size() == _node.path().size());
for (size_t i = 0; i < _node.path().size(); i++)
if (
_node.path()[i] == m_outer.m_symbolName &&
declarations[i] == m_outer.m_declarationToRename
)
m_outer.m_locations.emplace_back(_node.pathLocations()[i]);
}
void RenameSymbol::extractNameAndDeclaration(InlineAssembly const& _inlineAssembly, int _cursorBytePosition)
{
for (auto&& [identifier, externalReference]: _inlineAssembly.annotation().externalReferences)
{
SourceLocation location = yul::nativeLocationOf(*identifier);
location.end -= static_cast<int>(externalReference.suffix.size() + 1);
if (location.containsOffset(_cursorBytePosition))
{
m_declarationToRename = externalReference.declaration;
m_symbolName = identifier->name.str();
if (!externalReference.suffix.empty())
m_symbolName = m_symbolName.substr(0, m_symbolName.length() - externalReference.suffix.size() - 1);
break;
}
}
}
void RenameSymbol::Visitor::endVisit(InlineAssembly const& _node)
{
for (auto&& [identifier, externalReference]: _node.annotation().externalReferences)
{
std::string identifierName = identifier->name.str();
if (!externalReference.suffix.empty())
identifierName = identifierName.substr(0, identifierName.length() - externalReference.suffix.size() - 1);
if (
externalReference.declaration == m_outer.m_declarationToRename &&
identifierName == m_outer.m_symbolName
)
{
SourceLocation location = yul::nativeLocationOf(*identifier);
location.end -= static_cast<int>(externalReference.suffix.size() + 1);
m_outer.m_locations.emplace_back(location);
}
}
}
| 10,808
|
C++
|
.cpp
| 263
| 38.338403
| 158
| 0.751263
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,149
|
LanguageServer.cpp
|
ethereum_solidity/libsolidity/lsp/LanguageServer.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/ASTUtils.h>
#include <libsolidity/ast/ASTVisitor.h>
#include <libsolidity/interface/ReadFile.h>
#include <libsolidity/interface/StandardCompiler.h>
#include <libsolidity/lsp/LanguageServer.h>
#include <libsolidity/lsp/HandlerBase.h>
#include <libsolidity/lsp/Utils.h>
// LSP feature implementations
#include <libsolidity/lsp/DocumentHoverHandler.h>
#include <libsolidity/lsp/GotoDefinition.h>
#include <libsolidity/lsp/RenameSymbol.h>
#include <libsolidity/lsp/SemanticTokensBuilder.h>
#include <liblangutil/SourceReferenceExtractor.h>
#include <liblangutil/CharStream.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/Visitor.h>
#include <libsolutil/JSON.h>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <ostream>
#include <string>
#include <fmt/format.h>
using namespace std::string_literals;
using namespace std::placeholders;
using namespace solidity::lsp;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity;
namespace fs = boost::filesystem;
namespace
{
bool resolvesToRegularFile(boost::filesystem::path _path, int maxRecursionDepth = 10)
{
fs::file_status fileStatus = fs::status(_path);
while (fileStatus.type() == fs::file_type::symlink_file && maxRecursionDepth > 0)
{
_path = boost::filesystem::read_symlink(_path);
fileStatus = fs::status(_path);
maxRecursionDepth--;
}
return fileStatus.type() == fs::file_type::regular_file;
}
int toDiagnosticSeverity(Error::Type _errorType)
{
// 1=Error, 2=Warning, 3=Info, 4=Hint
switch (Error::errorSeverity(_errorType))
{
case Error::Severity::Error: return 1;
case Error::Severity::Warning: return 2;
case Error::Severity::Info: return 3;
}
solAssert(false);
return -1;
}
Json semanticTokensLegend()
{
Json legend;
// NOTE! The (alphabetical) order and items must match exactly the items of
// their respective enum class members.
Json tokenTypes = Json::array();
tokenTypes.emplace_back("class");
tokenTypes.emplace_back("comment");
tokenTypes.emplace_back("enum");
tokenTypes.emplace_back("enumMember");
tokenTypes.emplace_back("event");
tokenTypes.emplace_back("function");
tokenTypes.emplace_back("interface");
tokenTypes.emplace_back("keyword");
tokenTypes.emplace_back("macro");
tokenTypes.emplace_back("method");
tokenTypes.emplace_back("modifier");
tokenTypes.emplace_back("number");
tokenTypes.emplace_back("operator");
tokenTypes.emplace_back("parameter");
tokenTypes.emplace_back("property");
tokenTypes.emplace_back("std::string");
tokenTypes.emplace_back("struct");
tokenTypes.emplace_back("type");
tokenTypes.emplace_back("typeParameter");
tokenTypes.emplace_back("variable");
legend["tokenTypes"] = tokenTypes;
Json tokenModifiers = Json::array();
tokenModifiers.emplace_back("abstract");
tokenModifiers.emplace_back("declaration");
tokenModifiers.emplace_back("definition");
tokenModifiers.emplace_back("deprecated");
tokenModifiers.emplace_back("documentation");
tokenModifiers.emplace_back("modification");
tokenModifiers.emplace_back("readonly");
legend["tokenModifiers"] = tokenModifiers;
return legend;
}
}
LanguageServer::LanguageServer(Transport& _transport):
m_client{_transport},
m_handlers{
{"$/cancelRequest", [](auto, auto) {/*nothing for now as we are synchronous */}},
{"cancelRequest", [](auto, auto) {/*nothing for now as we are synchronous */}},
{"exit", [this](auto, auto) { m_state = (m_state == State::ShutdownRequested ? State::ExitRequested : State::ExitWithoutShutdown); }},
{"initialize", std::bind(&LanguageServer::handleInitialize, this, _1, _2)},
{"initialized", std::bind(&LanguageServer::handleInitialized, this, _1, _2)},
{"$/setTrace", [this](auto, Json const& args) { setTrace(args["value"]); }},
{"shutdown", [this](auto, auto) { m_state = State::ShutdownRequested; }},
{"textDocument/definition", GotoDefinition(*this) },
{"textDocument/didOpen", std::bind(&LanguageServer::handleTextDocumentDidOpen, this, _2)},
{"textDocument/didChange", std::bind(&LanguageServer::handleTextDocumentDidChange, this, _2)},
{"textDocument/didClose", std::bind(&LanguageServer::handleTextDocumentDidClose, this, _2)},
{"textDocument/hover", DocumentHoverHandler(*this) },
{"textDocument/rename", RenameSymbol(*this) },
{"textDocument/implementation", GotoDefinition(*this) },
{"textDocument/semanticTokens/full", std::bind(&LanguageServer::semanticTokensFull, this, _1, _2)},
{"workspace/didChangeConfiguration", std::bind(&LanguageServer::handleWorkspaceDidChangeConfiguration, this, _2)},
},
m_fileRepository("/" /* basePath */, {} /* no search paths */),
m_compilerStack{m_fileRepository.reader()}
{
}
Json LanguageServer::toRange(SourceLocation const& _location)
{
return HandlerBase(*this).toRange(_location);
}
Json LanguageServer::toJson(SourceLocation const& _location)
{
return HandlerBase(*this).toJson(_location);
}
void LanguageServer::changeConfiguration(Json const& _settings)
{
// The settings item: "file-load-strategy" (enum) defaults to "project-directory" if not (or not correctly) set.
// It can be overridden during client's handshake or at runtime, as usual.
//
// If this value is set to "project-directory" (default), all .sol files located inside the project directory or reachable through symbolic links will be subject to operations.
//
// Operations include compiler analysis, but also finding all symbolic references or symbolic renaming.
//
// If this value is set to "directly-opened-and-on-import", then only currently directly opened files and
// those files being imported directly or indirectly will be included in operations.
if (_settings.contains("file-load-strategy"))
{
auto const text = _settings["file-load-strategy"].get<std::string>();
if (text == "project-directory")
m_fileLoadStrategy = FileLoadStrategy::ProjectDirectory;
else if (text == "directly-opened-and-on-import")
m_fileLoadStrategy = FileLoadStrategy::DirectlyOpenedAndOnImported;
else
lspRequire(false, ErrorCode::InvalidParams, "Invalid file load strategy: " + text);
}
m_settingsObject = _settings;
Json jsonIncludePaths = _settings.contains("include-paths") ? _settings["include-paths"] : Json::object();
if (!jsonIncludePaths.empty())
{
int typeFailureCount = 0;
if (jsonIncludePaths.is_array())
{
std::vector<boost::filesystem::path> includePaths;
for (Json const& jsonPath: jsonIncludePaths)
{
if (jsonPath.is_string())
includePaths.emplace_back(jsonPath.get<std::string>());
else
typeFailureCount++;
}
m_fileRepository.setIncludePaths(std::move(includePaths));
}
else
++typeFailureCount;
if (typeFailureCount)
m_client.trace("Invalid JSON configuration passed. \"include-paths\" must be an array of strings.");
}
}
std::vector<boost::filesystem::path> LanguageServer::allSolidityFilesFromProject() const
{
std::vector<fs::path> collectedPaths{};
// We explicitly decided against including all files from include paths but leave the possibility
// open for a future PR to enable such a feature to be optionally enabled (default disabled).
// Note: Newer versions of boost have deprecated symlink_option::recurse
#if (BOOST_VERSION < 107200)
auto directoryIterator = fs::recursive_directory_iterator(m_fileRepository.basePath(), fs::symlink_option::recurse);
#else
auto directoryIterator = fs::recursive_directory_iterator(m_fileRepository.basePath(), fs::directory_options::follow_directory_symlink);
#endif
for (fs::directory_entry const& dirEntry: directoryIterator)
if (
dirEntry.path().extension() == ".sol" &&
(dirEntry.status().type() == fs::file_type::regular_file || resolvesToRegularFile(dirEntry.path()))
)
collectedPaths.push_back(dirEntry.path());
return collectedPaths;
}
void LanguageServer::compile()
{
// For files that are not open, we have to take changes on disk into account,
// so we just remove all non-open files.
FileRepository oldRepository(m_fileRepository.basePath(), m_fileRepository.includePaths());
std::swap(oldRepository, m_fileRepository);
// Load all solidity files from project.
if (m_fileLoadStrategy == FileLoadStrategy::ProjectDirectory)
for (auto const& projectFile: allSolidityFilesFromProject())
{
lspDebug(fmt::format("adding project file: {}", projectFile.generic_string()));
m_fileRepository.setSourceByUri(
m_fileRepository.sourceUnitNameToUri(projectFile.generic_string()),
util::readFileAsString(projectFile)
);
}
// Overwrite all files as opened by the client, including the ones which might potentially have changes.
for (std::string const& fileName: m_openFiles)
m_fileRepository.setSourceByUri(
fileName,
oldRepository.sourceUnits().at(oldRepository.uriToSourceUnitName(fileName))
);
// TODO: optimize! do not recompile if nothing has changed (file(s) not flagged dirty).
m_compilerStack.reset(false);
m_compilerStack.setSources(m_fileRepository.sourceUnits());
m_compilerStack.compile(CompilerStack::State::AnalysisSuccessful);
}
void LanguageServer::compileAndUpdateDiagnostics()
{
compile();
// These are the source units we will sent diagnostics to the client for sure,
// even if it is just to clear previous diagnostics.
std::map<std::string, Json> diagnosticsBySourceUnit;
for (std::string const& sourceUnitName: m_fileRepository.sourceUnits() | ranges::views::keys)
diagnosticsBySourceUnit[sourceUnitName] = Json::array();
for (std::string const& sourceUnitName: m_nonemptyDiagnostics)
diagnosticsBySourceUnit[sourceUnitName] = Json::array();
for (std::shared_ptr<Error const> const& error: m_compilerStack.errors())
{
SourceLocation const* location = error->sourceLocation();
if (!location || !location->sourceName)
// LSP only has diagnostics applied to individual files.
continue;
Json jsonDiag;
jsonDiag["source"] = "solc";
jsonDiag["severity"] = toDiagnosticSeverity(error->type());
jsonDiag["code"] = Json(error->errorId().error);
std::string message = Error::formatErrorType(error->type()) + ":";
if (std::string const* comment = error->comment())
message += " " + *comment;
jsonDiag["message"] = std::move(message);
jsonDiag["range"] = toRange(*location);
if (auto const* secondary = error->secondarySourceLocation())
for (auto&& [secondaryMessage, secondaryLocation]: secondary->infos)
{
Json jsonRelated;
jsonRelated["message"] = secondaryMessage;
jsonRelated["location"] = toJson(secondaryLocation);
jsonDiag["relatedInformation"].emplace_back(jsonRelated);
}
diagnosticsBySourceUnit[*location->sourceName].emplace_back(jsonDiag);
}
if (m_client.traceValue() != TraceValue::Off)
{
Json extra;
extra["openFileCount"] = Json(diagnosticsBySourceUnit.size());
m_client.trace("Number of currently open files: " + std::to_string(diagnosticsBySourceUnit.size()), extra);
}
m_nonemptyDiagnostics.clear();
for (auto&& [sourceUnitName, diagnostics]: diagnosticsBySourceUnit)
{
Json params;
params["uri"] = m_fileRepository.sourceUnitNameToUri(sourceUnitName);
if (!diagnostics.empty())
m_nonemptyDiagnostics.insert(sourceUnitName);
params["diagnostics"] = std::move(diagnostics);
m_client.notify("textDocument/publishDiagnostics", std::move(params));
}
}
bool LanguageServer::run()
{
while (m_state != State::ExitRequested && m_state != State::ExitWithoutShutdown && !m_client.closed())
{
MessageID id;
try
{
std::optional<Json> const jsonMessage = m_client.receive();
if (!jsonMessage)
continue;
if ((*jsonMessage).contains("method") && (*jsonMessage)["method"].is_string())
{
std::string const methodName = (*jsonMessage)["method"].get<std::string>();
if ((*jsonMessage).contains("id"))
id = (*jsonMessage)["id"];
lspDebug(fmt::format("received method call: {}", methodName));
if (auto handler = util::valueOrDefault(m_handlers, methodName))
handler(id, (*jsonMessage)["params"]);
else
m_client.error(id, ErrorCode::MethodNotFound, "Unknown method " + methodName);
}
else
m_client.error({}, ErrorCode::ParseError, "\"method\" has to be a string.");
}
catch (Json::exception const&)
{
m_client.error(id, ErrorCode::InvalidParams, "JSON object access error. Most likely due to a badly formatted JSON request message."s);
}
catch (RequestError const& error)
{
m_client.error(id, error.code(), error.comment() ? *error.comment() : ""s);
}
catch (...)
{
m_client.error(id, ErrorCode::InternalError, "Unhandled exception: "s + boost::current_exception_diagnostic_information());
}
}
return m_state == State::ExitRequested;
}
void LanguageServer::requireServerInitialized()
{
lspRequire(
m_state == State::Initialized,
ErrorCode::ServerNotInitialized,
"Server is not properly initialized."
);
}
void LanguageServer::handleInitialize(MessageID _id, Json const& _args)
{
lspRequire(
m_state == State::Started,
ErrorCode::RequestFailed,
"Initialize called at the wrong time."
);
m_state = State::Initialized;
// The default of FileReader is to use `.`, but the path from where the LSP was started
// should not matter.
std::string rootPath("/");
if (_args.contains("rootUri") && _args["rootUri"].is_string())
{
rootPath = _args["rootUri"].get<std::string>();
lspRequire(
boost::starts_with(rootPath, "file://"),
ErrorCode::InvalidParams,
"rootUri only supports file URI scheme."
);
rootPath = stripFileUriSchemePrefix(rootPath);
}
else if (_args.contains("rootPath"))
rootPath = _args["rootPath"].get<std::string>();
if (_args.contains("trace"))
setTrace(_args["trace"]);
m_fileRepository = FileRepository(rootPath, {});
if (_args.contains("initializationOptions") && _args["initializationOptions"].is_object())
changeConfiguration(_args["initializationOptions"]);
Json replyArgs;
replyArgs["serverInfo"]["name"] = "solc";
replyArgs["serverInfo"]["version"] = std::string(VersionNumber);
replyArgs["capabilities"]["definitionProvider"] = true;
replyArgs["capabilities"]["implementationProvider"] = true;
replyArgs["capabilities"]["textDocumentSync"]["change"] = 2; // 0=none, 1=full, 2=incremental
replyArgs["capabilities"]["textDocumentSync"]["openClose"] = true;
replyArgs["capabilities"]["semanticTokensProvider"]["legend"] = semanticTokensLegend();
replyArgs["capabilities"]["semanticTokensProvider"]["range"] = false;
replyArgs["capabilities"]["semanticTokensProvider"]["full"] = true; // XOR requests.full.delta = true
replyArgs["capabilities"]["renameProvider"] = true;
replyArgs["capabilities"]["hoverProvider"] = true;
m_client.reply(_id, std::move(replyArgs));
}
void LanguageServer::handleInitialized(MessageID, Json const&)
{
if (m_fileLoadStrategy == FileLoadStrategy::ProjectDirectory)
compileAndUpdateDiagnostics();
}
void LanguageServer::semanticTokensFull(MessageID _id, Json const& _args)
{
if (_args.contains("textDocument") && _args["textDocument"].contains("uri"))
{
auto uri = _args["textDocument"]["uri"];
compile();
auto const sourceName = m_fileRepository.uriToSourceUnitName(uri.get<std::string>());
SourceUnit const& ast = m_compilerStack.ast(sourceName);
m_compilerStack.charStream(sourceName);
Json data = SemanticTokensBuilder().build(ast, m_compilerStack.charStream(sourceName));
Json reply;
reply["data"] = data;
m_client.reply(_id, std::move(reply));
}
else
m_client.error(_id, ErrorCode::InvalidParams, "Invalid parameter: textDocument.uri expected.");
}
void LanguageServer::handleWorkspaceDidChangeConfiguration(Json const& _args)
{
requireServerInitialized();
if (_args.contains("settings") && _args["settings"].is_object())
changeConfiguration(_args["settings"]);
}
void LanguageServer::setTrace(Json const& _args)
{
if (!_args.is_string())
// Simply ignore invalid parameter.
return;
std::string const stringValue = _args.get<std::string>();
if (stringValue == "off")
m_client.setTrace(TraceValue::Off);
else if (stringValue == "messages")
m_client.setTrace(TraceValue::Messages);
else if (stringValue == "verbose")
m_client.setTrace(TraceValue::Verbose);
}
void LanguageServer::handleTextDocumentDidOpen(Json const& _args)
{
requireServerInitialized();
lspRequire(
_args.contains("textDocument"),
ErrorCode::RequestFailed,
"Text document parameter missing."
);
if (_args["textDocument"].contains("text") && _args["textDocument"].contains("uri"))
{
std::string text = _args["textDocument"]["text"].get<std::string>();
std::string uri = _args["textDocument"]["uri"].get<std::string>();
m_openFiles.insert(uri);
m_fileRepository.setSourceByUri(uri, std::move(text));
compileAndUpdateDiagnostics();
}
}
void LanguageServer::handleTextDocumentDidChange(Json const& _args)
{
requireServerInitialized();
if (_args.contains("textDocument") && _args["textDocument"].contains("uri"))
{
std::string const uri = _args["textDocument"]["uri"].get<std::string>();
if (_args.contains("contentChanges"))
for (auto const& [_, jsonContentChange]: _args["contentChanges"].items())
{
lspRequire(jsonContentChange.is_object(), ErrorCode::RequestFailed, "Invalid content reference.");
std::string const sourceUnitName = m_fileRepository.uriToSourceUnitName(uri);
lspRequire(
m_fileRepository.sourceUnits().count(sourceUnitName),
ErrorCode::RequestFailed,
"Unknown file: " + uri);
if (jsonContentChange.contains("text"))
{
std::string text = jsonContentChange["text"].get<std::string>();
if (jsonContentChange.contains("range")
&& jsonContentChange["range"].is_object()) // otherwise full content update
{
std::optional<SourceLocation> change
= parseRange(m_fileRepository, sourceUnitName, jsonContentChange["range"]);
lspRequire(
change && change->hasText(),
ErrorCode::RequestFailed,
"Invalid source range: " + util::jsonCompactPrint(jsonContentChange["range"]));
std::string buffer = m_fileRepository.sourceUnits().at(sourceUnitName);
buffer.replace(
static_cast<size_t>(change->start),
static_cast<size_t>(change->end - change->start),
std::move(text));
text = std::move(buffer);
}
m_fileRepository.setSourceByUri(uri, std::move(text));
}
}
compileAndUpdateDiagnostics();
}
}
void LanguageServer::handleTextDocumentDidClose(Json const& _args)
{
requireServerInitialized();
lspRequire(
_args.contains("textDocument"),
ErrorCode::RequestFailed,
"Text document parameter missing."
);
if (_args["textDocument"].contains("uri"))
{
std::string uri = _args["textDocument"]["uri"].get<std::string>();
m_openFiles.erase(uri);
compileAndUpdateDiagnostics();
}
}
ASTNode const* LanguageServer::astNodeAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos)
{
return std::get<ASTNode const*>(astNodeAndOffsetAtSourceLocation(_sourceUnitName, _filePos));
}
std::tuple<ASTNode const*, int> LanguageServer::astNodeAndOffsetAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos)
{
if (m_compilerStack.state() < CompilerStack::AnalysisSuccessful)
return {nullptr, -1};
if (!m_fileRepository.sourceUnits().count(_sourceUnitName))
return {nullptr, -1};
std::optional<int> sourcePos = m_compilerStack.charStream(_sourceUnitName).translateLineColumnToPosition(_filePos);
if (!sourcePos)
return {nullptr, -1};
return {locateInnermostASTNode(*sourcePos, m_compilerStack.ast(_sourceUnitName)), *sourcePos};
}
| 20,362
|
C++
|
.cpp
| 500
| 37.988
| 177
| 0.746258
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,150
|
GotoDefinition.cpp
|
ethereum_solidity/libsolidity/lsp/GotoDefinition.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/lsp/GotoDefinition.h>
#include <libsolidity/lsp/Transport.h> // for RequestError
#include <libsolidity/lsp/Utils.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/ASTUtils.h>
#include <fmt/format.h>
#include <memory>
#include <string>
#include <vector>
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::lsp;
void GotoDefinition::operator()(MessageID _id, Json const& _args)
{
auto const [sourceUnitName, lineColumn] = extractSourceUnitNameAndLineColumn(_args);
ASTNode const* sourceNode = m_server.astNodeAtSourceLocation(sourceUnitName, lineColumn);
std::vector<SourceLocation> locations;
if (auto const* expression = dynamic_cast<Expression const*>(sourceNode))
{
// Handles all expressions that can have one or more declaration annotation.
if (auto const* declaration = referencedDeclaration(expression))
if (auto location = declarationLocation(declaration))
locations.emplace_back(std::move(location.value()));
}
else if (auto const* identifierPath = dynamic_cast<IdentifierPath const*>(sourceNode))
{
if (auto const* declaration = identifierPath->annotation().referencedDeclaration)
if (auto location = declarationLocation(declaration))
locations.emplace_back(std::move(location.value()));
}
else if (auto const* importDirective = dynamic_cast<ImportDirective const*>(sourceNode))
{
auto const& path = *importDirective->annotation().absolutePath;
if (fileRepository().sourceUnits().count(path))
locations.emplace_back(SourceLocation{0, 0, std::make_shared<std::string const>(path)});
}
Json reply = Json::array();
for (SourceLocation const& location: locations)
reply.emplace_back(toJson(location));
client().reply(_id, reply);
}
| 2,453
|
C++
|
.cpp
| 55
| 42.418182
| 91
| 0.781407
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,151
|
DocumentHoverHandler.cpp
|
ethereum_solidity/libsolidity/lsp/DocumentHoverHandler.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/lsp/DocumentHoverHandler.h>
#include <libsolidity/lsp/Utils.h>
#include <fmt/format.h>
namespace solidity::lsp
{
using namespace solidity::lsp;
using namespace solidity::langutil;
using namespace solidity::frontend;
namespace
{
struct MarkdownBuilder
{
std::stringstream result;
MarkdownBuilder& solidityCode(std::string const& _code)
{
auto constexpr SolidityLanguageId = "solidity";
result << "```" << SolidityLanguageId << '\n' << _code << "\n```\n\n";
return *this;
}
MarkdownBuilder& paragraph(std::string const& _text)
{
if (!_text.empty())
{
result << _text << '\n';
if (_text.back() != '\n') // We want double-LF to ensure constructing a paragraph.
result << '\n';
}
return *this;
}
};
}
void DocumentHoverHandler::operator()(MessageID _id, Json const& _args)
{
auto const [sourceUnitName, lineColumn] = HandlerBase(*this).extractSourceUnitNameAndLineColumn(_args);
auto const [sourceNode, sourceOffset] = m_server.astNodeAndOffsetAtSourceLocation(sourceUnitName, lineColumn);
MarkdownBuilder markdown;
auto rangeToHighlight = toRange(sourceNode->location());
// Try getting the type definition of the underlying AST node, if available.
if (auto const* expression = dynamic_cast<Expression const*>(sourceNode))
{
if (auto const* declaration = ASTNode::referencedDeclaration(*expression))
if (declaration->type())
markdown.solidityCode(declaration->type()->toString(false));
}
else if (auto const* declaration = dynamic_cast<Declaration const*>(sourceNode))
{
if (declaration->type())
markdown.solidityCode(declaration->type()->toString(false));
}
else if (auto const* identifierPath = dynamic_cast<IdentifierPath const*>(sourceNode))
{
for (size_t i = 0; i < identifierPath->path().size(); ++i)
{
if (identifierPath->pathLocations()[i].containsOffset(sourceOffset))
{
rangeToHighlight = toRange(identifierPath->pathLocations()[i]);
if (i < identifierPath->annotation().pathDeclarations.size())
{
Declaration const* declaration = identifierPath->annotation().pathDeclarations[i];
if (declaration && declaration->type())
markdown.solidityCode(declaration->type()->toString(false));
if (auto const* structurallyDocumented = dynamic_cast<StructurallyDocumented const*>(declaration))
if (structurallyDocumented->documentation()->text())
markdown.paragraph(*structurallyDocumented->documentation()->text());
}
break;
}
}
}
// If this AST node contains documentation itself, append it.
if (auto const* documented = dynamic_cast<StructurallyDocumented const*>(sourceNode))
{
if (documented->documentation())
markdown.paragraph(*documented->documentation()->text());
}
auto tooltipText = markdown.result.str();
if (tooltipText.empty())
{
client().reply(_id, Json());
return;
}
Json reply;
reply["range"] = rangeToHighlight;
reply["contents"]["kind"] = "markdown";
reply["contents"]["value"] = std::move(tooltipText);
client().reply(_id, reply);
}
}
| 3,723
|
C++
|
.cpp
| 102
| 33.715686
| 111
| 0.739722
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,152
|
SemanticTokensBuilder.cpp
|
ethereum_solidity/libsolidity/lsp/SemanticTokensBuilder.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/lsp/SemanticTokensBuilder.h>
#include <libsolidity/lsp/Utils.h>
#include <liblangutil/CharStream.h>
#include <liblangutil/SourceLocation.h>
#include <fmt/format.h>
using namespace solidity::langutil;
using namespace solidity::frontend;
namespace solidity::lsp
{
namespace
{
std::optional<SemanticTokenType> semanticTokenTypeForType(frontend::Type const* _type)
{
if (!_type)
return std::nullopt;
switch (_type->category())
{
case frontend::Type::Category::Address: return SemanticTokenType::Class;
case frontend::Type::Category::Bool: return SemanticTokenType::Number;
case frontend::Type::Category::Enum: return SemanticTokenType::Enum;
case frontend::Type::Category::Function: return SemanticTokenType::Function;
case frontend::Type::Category::Integer: return SemanticTokenType::Number;
case frontend::Type::Category::RationalNumber: return SemanticTokenType::Number;
case frontend::Type::Category::StringLiteral: return SemanticTokenType::String;
case frontend::Type::Category::Struct: return SemanticTokenType::Struct;
case frontend::Type::Category::Contract: return SemanticTokenType::Class;
default:
lspDebug(fmt::format("semanticTokenTypeForType: unknown category: {}", static_cast<unsigned>(_type->category())));
return SemanticTokenType::Type;
}
}
SemanticTokenType semanticTokenTypeForExpression(frontend::Type const* _type)
{
if (!_type)
return SemanticTokenType::Variable;
switch (_type->category())
{
case frontend::Type::Category::Enum:
return SemanticTokenType::Enum;
default:
return SemanticTokenType::Variable;
}
}
} // end namespace
Json SemanticTokensBuilder::build(SourceUnit const& _sourceUnit, CharStream const& _charStream)
{
reset(&_charStream);
_sourceUnit.accept(*this);
return m_encodedTokens;
}
void SemanticTokensBuilder::reset(CharStream const* _charStream)
{
m_encodedTokens = Json::array();
m_charStream = _charStream;
m_lastLine = 0;
m_lastStartChar = 0;
}
void SemanticTokensBuilder::encode(
SourceLocation const& _sourceLocation,
SemanticTokenType _tokenType,
SemanticTokenModifiers _modifiers
)
{
/*
https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocument_semanticTokens
// Step-1: Absolute positions
{ line: 2, startChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 },
{ line: 2, startChar: 10, length: 4, tokenType: 1, tokenModifiers: 0 },
{ line: 5, startChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 }
// Step-2: Relative positions as intermediate step
{ deltaLine: 2, deltaStartChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 },
{ deltaLine: 0, deltaStartChar: 5, length: 4, tokenType: 1, tokenModifiers: 0 },
{ deltaLine: 3, deltaStartChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 }
// Step-3: final array result
// 1st token, 2nd token, 3rd token
[ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ]
So traverse through the AST and assign each leaf a token 5-tuple.
*/
// solAssert(_sourceLocation.isValid());
if (!_sourceLocation.isValid())
return;
auto const [line, startChar] = m_charStream->translatePositionToLineColumn(_sourceLocation.start);
auto const length = _sourceLocation.end - _sourceLocation.start;
lspDebug(fmt::format("encode [{}:{}..{}] {}", line, startChar, length, static_cast<int>(_tokenType)));
m_encodedTokens.emplace_back(line - m_lastLine);
if (line == m_lastLine)
m_encodedTokens.emplace_back(startChar - m_lastStartChar);
else
m_encodedTokens.emplace_back(startChar);
m_encodedTokens.emplace_back(length);
m_encodedTokens.emplace_back(static_cast<int>(_tokenType));
m_encodedTokens.emplace_back(static_cast<int>(_modifiers));
m_lastLine = line;
m_lastStartChar = startChar;
}
bool SemanticTokensBuilder::visit(frontend::ContractDefinition const& _node)
{
encode(_node.nameLocation(), SemanticTokenType::Class);
return true;
}
bool SemanticTokensBuilder::visit(frontend::ElementaryTypeName const& _node)
{
encode(_node.location(), SemanticTokenType::Type);
return true;
}
bool SemanticTokensBuilder::visit(frontend::ElementaryTypeNameExpression const& _node)
{
if (auto const tokenType = semanticTokenTypeForType(_node.annotation().type); tokenType.has_value())
encode(_node.location(), tokenType.value());
return true;
}
bool SemanticTokensBuilder::visit(frontend::EnumDefinition const& _node)
{
encode(_node.nameLocation(), SemanticTokenType::Enum);
return true;
}
bool SemanticTokensBuilder::visit(frontend::EnumValue const& _node)
{
encode(_node.nameLocation(), SemanticTokenType::EnumMember);
return true;
}
bool SemanticTokensBuilder::visit(frontend::ErrorDefinition const& _node)
{
encode(_node.nameLocation(), SemanticTokenType::Event);
return true;
}
bool SemanticTokensBuilder::visit(frontend::FunctionDefinition const& _node)
{
encode(_node.nameLocation(), SemanticTokenType::Function);
return true;
}
bool SemanticTokensBuilder::visit(frontend::ModifierDefinition const& _node)
{
encode(_node.nameLocation(), SemanticTokenType::Modifier);
return true;
}
void SemanticTokensBuilder::endVisit(frontend::Literal const& _literal)
{
encode(_literal.location(), SemanticTokenType::Number);
}
void SemanticTokensBuilder::endVisit(frontend::StructuredDocumentation const& _documentation)
{
encode(_documentation.location(), SemanticTokenType::Comment);
}
void SemanticTokensBuilder::endVisit(frontend::Identifier const& _identifier)
{
//lspDebug(fmt::format("Identifier: {}, {}..{} cat={}", _identifier.name(), _identifier.location().start, _identifier.location().end, _identifier.annotation().type->category()));
SemanticTokenModifiers modifiers = SemanticTokenModifiers::None;
if (_identifier.annotation().isConstant.set() && *_identifier.annotation().isConstant)
{
lspDebug("OMG We've found a const!");
modifiers = modifiers | SemanticTokenModifiers::Readonly;
}
encode(_identifier.location(), semanticTokenTypeForExpression(_identifier.annotation().type), modifiers);
}
void SemanticTokensBuilder::endVisit(frontend::IdentifierPath const& _node)
{
lspDebug(fmt::format("IdentifierPath: identifier path [{}..{}]", _node.location().start, _node.location().end));
for (size_t i = 0; i < _node.path().size(); ++i)
lspDebug(fmt::format(" [{}]: {}", i, _node.path().at(i)));
if (dynamic_cast<EnumDefinition const*>(_node.annotation().referencedDeclaration))
encode(_node.location(), SemanticTokenType::EnumMember);
else
encode(_node.location(), SemanticTokenType::Variable);
}
bool SemanticTokensBuilder::visit(frontend::MemberAccess const& _node)
{
lspDebug(fmt::format("[{}..{}] MemberAccess({}): {}", _node.location().start, _node.location().end, _node.annotation().referencedDeclaration ? _node.annotation().referencedDeclaration->name() : "?", _node.memberName()));
auto const memberNameLength = static_cast<int>(_node.memberName().size());
auto const memberTokenType = semanticTokenTypeForExpression(_node.annotation().type);
auto lhsLocation = _node.location();
lhsLocation.end -= (memberNameLength + 1 /*exclude the dot*/);
auto rhsLocation = _node.location();
rhsLocation.start = rhsLocation.end - static_cast<int>(memberNameLength);
if (memberTokenType == SemanticTokenType::Enum)
{
// Special handling for enumeration symbols.
encode(lhsLocation, SemanticTokenType::Enum);
encode(rhsLocation, SemanticTokenType::EnumMember);
}
else if (memberTokenType == SemanticTokenType::Function)
{
// Special handling for function symbols.
encode(lhsLocation, SemanticTokenType::Variable);
encode(rhsLocation, memberTokenType);
}
else
{
encode(rhsLocation, memberTokenType);
}
return false; // we handle LHS and RHS explicitly above.
}
void SemanticTokensBuilder::endVisit(PragmaDirective const& _pragma)
{
encode(_pragma.location(), SemanticTokenType::Macro);
// NOTE: It would be nice if we could highlight based on the symbols,
// such as (version) numerics be different than identifiers.
}
bool SemanticTokensBuilder::visit(frontend::UserDefinedTypeName const& _node)
{
if (auto const token = semanticTokenTypeForType(_node.annotation().type); token.has_value())
encode(_node.location(), *token);
return false;
}
bool SemanticTokensBuilder::visit(frontend::VariableDeclaration const& _node)
{
lspDebug(fmt::format("VariableDeclaration: {}", _node.name()));
if (auto const token = semanticTokenTypeForType(_node.typeName().annotation().type); token.has_value())
encode(_node.typeName().location(), *token);
encode(_node.nameLocation(), SemanticTokenType::Variable);
if (_node.overrides())
_node.overrides()->accept(*this);
if (_node.value())
_node.value()->accept(*this);
return false;
}
} // end namespace
| 9,375
|
C++
|
.cpp
| 231
| 38.541126
| 222
| 0.767733
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,153
|
Utils.cpp
|
ethereum_solidity/libsolidity/lsp/Utils.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <liblangutil/CharStreamProvider.h>
#include <liblangutil/Exceptions.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/lsp/FileRepository.h>
#include <libsolidity/lsp/Utils.h>
#include <regex>
#include <fstream>
namespace solidity::lsp
{
using namespace frontend;
using namespace langutil;
std::optional<LineColumn> parseLineColumn(Json const& _lineColumn)
{
if (_lineColumn.is_object() && _lineColumn["line"].is_number_integer() && _lineColumn["character"].is_number_integer())
return LineColumn{_lineColumn["line"].get<int>(), _lineColumn["character"].get<int>()};
else
return std::nullopt;
}
Json toJson(LineColumn const& _pos)
{
Json json;
json["line"] = std::max(_pos.line, 0);
json["character"] = std::max(_pos.column, 0);
return json;
}
Json toJsonRange(LineColumn const& _start, LineColumn const& _end)
{
Json json;
json["start"] = toJson(_start);
json["end"] = toJson(_end);
return json;
}
Declaration const* referencedDeclaration(Expression const* _expression)
{
if (auto const* identifier = dynamic_cast<Identifier const*>(_expression))
if (Declaration const* referencedDeclaration = identifier->annotation().referencedDeclaration)
return referencedDeclaration;
if (auto const* memberAccess = dynamic_cast<MemberAccess const*>(_expression))
if (memberAccess->annotation().referencedDeclaration)
return memberAccess->annotation().referencedDeclaration;
return nullptr;
}
std::optional<SourceLocation> declarationLocation(Declaration const* _declaration)
{
if (!_declaration)
return std::nullopt;
if (_declaration->nameLocation().isValid())
return _declaration->nameLocation();
if (_declaration->location().isValid())
return _declaration->location();
return std::nullopt;
}
std::optional<SourceLocation> parsePosition(
FileRepository const& _fileRepository,
std::string const& _sourceUnitName,
Json const& _position
)
{
if (!_fileRepository.sourceUnits().count(_sourceUnitName))
return std::nullopt;
if (std::optional<LineColumn> lineColumn = parseLineColumn(_position))
if (std::optional<int> const offset = CharStream::translateLineColumnToPosition(
_fileRepository.sourceUnits().at(_sourceUnitName),
*lineColumn
))
return SourceLocation{*offset, *offset, std::make_shared<std::string>(_sourceUnitName)};
return std::nullopt;
}
std::optional<SourceLocation> parseRange(FileRepository const& _fileRepository, std::string const& _sourceUnitName, Json const& _range)
{
if (!_range.is_object())
return std::nullopt;
std::optional<SourceLocation> start = parsePosition(_fileRepository, _sourceUnitName, _range["start"]);
std::optional<SourceLocation> end = parsePosition(_fileRepository, _sourceUnitName, _range["end"]);
if (!start || !end)
return std::nullopt;
solAssert(*start->sourceName == *end->sourceName);
start->end = end->end;
return start;
}
std::string stripFileUriSchemePrefix(std::string const& _path)
{
std::regex const windowsDriveLetterPath("^file:///[a-zA-Z]:/");
if (regex_search(_path, windowsDriveLetterPath))
return _path.substr(8);
if (_path.find("file://") == 0)
return _path.substr(7);
else
return _path;
}
}
| 3,839
|
C++
|
.cpp
| 105
| 34.485714
| 135
| 0.764214
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
3,154
|
FileRepository.cpp
|
ethereum_solidity/libsolidity/lsp/FileRepository.cpp
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolidity/lsp/FileRepository.h>
#include <libsolidity/lsp/Transport.h>
#include <libsolidity/lsp/Utils.h>
#include <libsolutil/StringUtils.h>
#include <libsolutil/CommonIO.h>
#include <range/v3/algorithm/none_of.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/transform.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <regex>
#include <boost/algorithm/string/predicate.hpp>
#include <fmt/format.h>
using namespace solidity;
using namespace solidity::lsp;
using namespace solidity::frontend;
using solidity::util::readFileAsString;
using solidity::util::joinHumanReadable;
using solidity::util::Result;
FileRepository::FileRepository(boost::filesystem::path _basePath, std::vector<boost::filesystem::path> _includePaths):
m_basePath(std::move(_basePath)),
m_includePaths(std::move(_includePaths))
{
}
void FileRepository::setIncludePaths(std::vector<boost::filesystem::path> _paths)
{
m_includePaths = std::move(_paths);
}
std::string FileRepository::sourceUnitNameToUri(std::string const& _sourceUnitName) const
{
std::regex const windowsDriveLetterPath("^[a-zA-Z]:/");
auto const ensurePathIsUnixLike = [&](std::string inputPath) -> std::string {
if (!regex_search(inputPath, windowsDriveLetterPath))
return inputPath;
else
return "/" + std::move(inputPath);
};
if (m_sourceUnitNamesToUri.count(_sourceUnitName))
{
solAssert(boost::starts_with(m_sourceUnitNamesToUri.at(_sourceUnitName), "file://"), "");
return m_sourceUnitNamesToUri.at(_sourceUnitName);
}
else if (_sourceUnitName.find("file://") == 0)
return _sourceUnitName;
else if (regex_search(_sourceUnitName, windowsDriveLetterPath))
return "file:///" + _sourceUnitName;
else if (
auto const resolvedPath = tryResolvePath(_sourceUnitName);
resolvedPath.message().empty()
)
return "file://" + ensurePathIsUnixLike(resolvedPath.get().generic_string());
else if (m_basePath.generic_string() != "/")
return "file://" + m_basePath.generic_string() + "/" + _sourceUnitName;
else
// Avoid double-/ in case base-path itself is simply a UNIX root filesystem root.
return "file:///" + _sourceUnitName;
}
std::string FileRepository::uriToSourceUnitName(std::string const& _path) const
{
lspRequire(boost::algorithm::starts_with(_path, "file://"), ErrorCode::InternalError, "URI must start with file://");
return stripFileUriSchemePrefix(_path);
}
void FileRepository::setSourceByUri(std::string const& _uri, std::string _source)
{
// This is needed for uris outside the base path. It can lead to collisions,
// but we need to mostly rewrite this in a future version anyway.
auto sourceUnitName = uriToSourceUnitName(_uri);
lspDebug(fmt::format("FileRepository.setSourceByUri({}): {}", _uri, _source));
m_sourceUnitNamesToUri.emplace(sourceUnitName, _uri);
m_sourceCodes[sourceUnitName] = std::move(_source);
}
Result<boost::filesystem::path> FileRepository::tryResolvePath(std::string const& _strippedSourceUnitName) const
{
if (
boost::filesystem::path(_strippedSourceUnitName).has_root_path() &&
boost::filesystem::exists(_strippedSourceUnitName)
)
return boost::filesystem::path(_strippedSourceUnitName);
std::vector<boost::filesystem::path> candidates;
std::vector<std::reference_wrapper<boost::filesystem::path const>> prefixes = {m_basePath};
prefixes += (m_includePaths | ranges::to<std::vector<std::reference_wrapper<boost::filesystem::path const>>>);
auto const defaultInclude = m_basePath / "node_modules";
if (m_includePaths.empty())
prefixes.emplace_back(defaultInclude);
auto const pathToQuotedString = [](boost::filesystem::path const& _path) { return "\"" + _path.string() + "\""; };
for (auto const& prefix: prefixes)
{
boost::filesystem::path canonicalPath = boost::filesystem::path(prefix) / boost::filesystem::path(_strippedSourceUnitName);
if (boost::filesystem::exists(canonicalPath))
candidates.push_back(std::move(canonicalPath));
}
if (candidates.empty())
return Result<boost::filesystem::path>::err(
"File not found. Searched the following locations: " +
joinHumanReadable(prefixes | ranges::views::transform(pathToQuotedString), ", ") +
"."
);
if (candidates.size() >= 2)
return Result<boost::filesystem::path>::err(
"Ambiguous import. "
"Multiple matching files found inside base path and/or include paths: " +
joinHumanReadable(candidates | ranges::views::transform(pathToQuotedString), ", ") +
"."
);
if (!boost::filesystem::is_regular_file(candidates[0]))
return Result<boost::filesystem::path>::err("Not a valid file.");
return candidates[0];
}
frontend::ReadCallback::Result FileRepository::readFile(std::string const& _kind, std::string const& _sourceUnitName)
{
solAssert(
_kind == ReadCallback::kindString(ReadCallback::Kind::ReadFile),
"ReadFile callback used as callback kind " + _kind
);
try
{
// File was read already. Use local store.
if (m_sourceCodes.count(_sourceUnitName))
return ReadCallback::Result{true, m_sourceCodes.at(_sourceUnitName)};
std::string const strippedSourceUnitName = stripFileUriSchemePrefix(_sourceUnitName);
Result<boost::filesystem::path> const resolvedPath = tryResolvePath(strippedSourceUnitName);
if (!resolvedPath.message().empty())
return ReadCallback::Result{false, resolvedPath.message()};
auto contents = readFileAsString(resolvedPath.get());
solAssert(m_sourceCodes.count(_sourceUnitName) == 0, "");
m_sourceCodes[_sourceUnitName] = contents;
return ReadCallback::Result{true, std::move(contents)};
}
catch (...)
{
return ReadCallback::Result{false, "Exception in read callback: " + boost::current_exception_diagnostic_information()};
}
}
| 6,377
|
C++
|
.cpp
| 146
| 41.342466
| 125
| 0.756574
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.