Merge remote-tracking branch 'origin/develop' into breaking

This commit is contained in:
chriseth 2020-12-08 21:00:09 +01:00
commit 806453aca9
60 changed files with 245 additions and 179 deletions

View File

@ -50,6 +50,7 @@ Compiler Features:
* SMTChecker: Support struct constructor.
* SMTChecker: Support getters.
* SMTChecker: Support early returns in the CHC engine.
* SMTChecker: Report struct values in counterexamples from CHC engine.
* Standard-Json: Properly filter the requested output artifacts.
Bugfixes:

View File

@ -51,6 +51,7 @@ if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MA
add_compile_options(-Wno-unknown-pragmas)
add_compile_options(-Wimplicit-fallthrough)
add_compile_options(-Wsign-conversion)
add_compile_options(-Wconversion)
eth_add_cxx_compiler_flag_if_supported(
$<$<COMPILE_LANGUAGE:CXX>:-Wextra-semi>

View File

@ -56,14 +56,14 @@ unsigned Assembly::bytesRequired(unsigned subTagSize) const
{
for (unsigned tagSize = subTagSize; true; ++tagSize)
{
unsigned ret = 1;
size_t ret = 1;
for (auto const& i: m_data)
ret += i.second.size();
for (AssemblyItem const& i: m_items)
ret += i.bytesRequired(tagSize);
if (util::bytesRequired(ret) <= tagSize)
return ret;
return static_cast<unsigned>(ret);
}
}
@ -257,7 +257,7 @@ Json::Value Assembly::assemblyJSON(map<string, unsigned> const& _sourceIndices)
break;
case PushString:
collection.append(
createJsonValue("PUSH tag", sourceIndex, i.location().start, i.location().end, m_strings.at((h256)i.data())));
createJsonValue("PUSH tag", sourceIndex, i.location().start, i.location().end, m_strings.at(h256(i.data()))));
break;
case PushTag:
if (i.data() == 0)
@ -573,21 +573,21 @@ LinkerObject const& Assembly::assemble() const
"Cannot push and assign immutables in the same assembly subroutine."
);
size_t bytesRequiredForCode = bytesRequired(subTagSize);
unsigned bytesRequiredForCode = bytesRequired(static_cast<unsigned>(subTagSize));
m_tagPositionsInBytecode = vector<size_t>(m_usedTags, numeric_limits<size_t>::max());
map<size_t, pair<size_t, size_t>> tagRef;
multimap<h256, unsigned> dataRef;
multimap<size_t, size_t> subRef;
vector<unsigned> sizeRef; ///< Pointers to code locations where the size of the program is inserted
unsigned bytesPerTag = util::bytesRequired(bytesRequiredForCode);
uint8_t tagPush = (uint8_t)pushInstruction(bytesPerTag);
uint8_t tagPush = static_cast<uint8_t>(pushInstruction(bytesPerTag));
unsigned bytesRequiredIncludingData = bytesRequiredForCode + 1 + m_auxiliaryData.size();
unsigned bytesRequiredIncludingData = bytesRequiredForCode + 1 + static_cast<unsigned>(m_auxiliaryData.size());
for (auto const& sub: m_subs)
bytesRequiredIncludingData += sub->assemble().bytecode.size();
bytesRequiredIncludingData += static_cast<unsigned>(sub->assemble().bytecode.size());
unsigned bytesPerDataRef = util::bytesRequired(bytesRequiredIncludingData);
uint8_t dataRefPush = (uint8_t)pushInstruction(bytesPerDataRef);
uint8_t dataRefPush = static_cast<uint8_t>(pushInstruction(bytesPerDataRef));
ret.bytecode.reserve(bytesRequiredIncludingData);
for (AssemblyItem const& i: m_items)
@ -599,25 +599,25 @@ LinkerObject const& Assembly::assemble() const
switch (i.type())
{
case Operation:
ret.bytecode.push_back((uint8_t)i.instruction());
ret.bytecode.push_back(static_cast<uint8_t>(i.instruction()));
break;
case PushString:
{
ret.bytecode.push_back((uint8_t)Instruction::PUSH32);
ret.bytecode.push_back(static_cast<uint8_t>(Instruction::PUSH32));
unsigned ii = 0;
for (auto j: m_strings.at((h256)i.data()))
for (auto j: m_strings.at(h256(i.data())))
if (++ii > 32)
break;
else
ret.bytecode.push_back((uint8_t)j);
ret.bytecode.push_back(uint8_t(j));
while (ii++ < 32)
ret.bytecode.push_back(0);
break;
}
case Push:
{
uint8_t b = max<unsigned>(1, util::bytesRequired(i.data()));
ret.bytecode.push_back((uint8_t)pushInstruction(b));
unsigned b = max<unsigned>(1, util::bytesRequired(i.data()));
ret.bytecode.push_back(static_cast<uint8_t>(pushInstruction(b)));
ret.bytecode.resize(ret.bytecode.size() + b);
bytesRef byr(&ret.bytecode.back() + 1 - b, b);
toBigEndian(i.data(), byr);
@ -632,7 +632,7 @@ LinkerObject const& Assembly::assemble() const
}
case PushData:
ret.bytecode.push_back(dataRefPush);
dataRef.insert(make_pair((h256)i.data(), ret.bytecode.size()));
dataRef.insert(make_pair(h256(i.data()), ret.bytecode.size()));
ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef);
break;
case PushSub:
@ -646,8 +646,8 @@ LinkerObject const& Assembly::assemble() const
assertThrow(i.data() <= numeric_limits<size_t>::max(), AssemblyException, "");
auto s = subAssemblyById(static_cast<size_t>(i.data()))->assemble().bytecode.size();
i.setPushedValue(u256(s));
uint8_t b = max<unsigned>(1, util::bytesRequired(s));
ret.bytecode.push_back((uint8_t)pushInstruction(b));
unsigned b = max<unsigned>(1, util::bytesRequired(s));
ret.bytecode.push_back(static_cast<uint8_t>(pushInstruction(b)));
ret.bytecode.resize(ret.bytecode.size() + b);
bytesRef byr(&ret.bytecode.back() + 1 - b, b);
toBigEndian(s, byr);
@ -656,17 +656,17 @@ LinkerObject const& Assembly::assemble() const
case PushProgramSize:
{
ret.bytecode.push_back(dataRefPush);
sizeRef.push_back(ret.bytecode.size());
sizeRef.push_back(static_cast<unsigned>(ret.bytecode.size()));
ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef);
break;
}
case PushLibraryAddress:
ret.bytecode.push_back(uint8_t(Instruction::PUSH20));
ret.bytecode.push_back(static_cast<uint8_t>(Instruction::PUSH20));
ret.linkReferences[ret.bytecode.size()] = m_libraries.at(i.data());
ret.bytecode.resize(ret.bytecode.size() + 20);
break;
case PushImmutable:
ret.bytecode.push_back(uint8_t(Instruction::PUSH32));
ret.bytecode.push_back(static_cast<uint8_t>(Instruction::PUSH32));
ret.immutableReferences[i.data()].first = m_immutables.at(i.data());
ret.immutableReferences[i.data()].second.emplace_back(ret.bytecode.size());
ret.bytecode.resize(ret.bytecode.size() + 32);
@ -683,7 +683,7 @@ LinkerObject const& Assembly::assemble() const
}
// TODO: should we make use of the constant optimizer methods for pushing the offsets?
bytes offsetBytes = toCompactBigEndian(u256(offsets[i]));
ret.bytecode.push_back(uint8_t(pushInstruction(offsetBytes.size())));
ret.bytecode.push_back(static_cast<uint8_t>(pushInstruction(static_cast<unsigned>(offsetBytes.size()))));
ret.bytecode += offsetBytes;
ret.bytecode.push_back(uint8_t(Instruction::ADD));
ret.bytecode.push_back(uint8_t(Instruction::MSTORE));
@ -697,7 +697,7 @@ LinkerObject const& Assembly::assemble() const
break;
}
case PushDeployTimeAddress:
ret.bytecode.push_back(uint8_t(Instruction::PUSH20));
ret.bytecode.push_back(static_cast<uint8_t>(Instruction::PUSH20));
ret.bytecode.resize(ret.bytecode.size() + 20);
break;
case Tag:
@ -706,7 +706,7 @@ LinkerObject const& Assembly::assemble() const
assertThrow(ret.bytecode.size() < 0xffffffffL, AssemblyException, "Tag too large.");
assertThrow(m_tagPositionsInBytecode[static_cast<size_t>(i.data())] == numeric_limits<size_t>::max(), AssemblyException, "Duplicate tag position.");
m_tagPositionsInBytecode[static_cast<size_t>(i.data())] = ret.bytecode.size();
ret.bytecode.push_back((uint8_t)Instruction::JUMPDEST);
ret.bytecode.push_back(static_cast<uint8_t>(Instruction::JUMPDEST));
break;
default:
assertThrow(false, InvalidOpcode, "Unexpected opcode while assembling.");
@ -720,7 +720,7 @@ LinkerObject const& Assembly::assemble() const
if (!m_subs.empty() || !m_data.empty() || !m_auxiliaryData.empty())
// Append an INVALID here to help tests find miscompilation.
ret.bytecode.push_back(uint8_t(Instruction::INVALID));
ret.bytecode.push_back(static_cast<uint8_t>(Instruction::INVALID));
for (auto const& [subIdPath, bytecodeOffset]: subRef)
{

View File

@ -23,7 +23,6 @@
#include <libevmasm/ConstantOptimiser.h>
#include <libevmasm/Assembly.h>
#include <libevmasm/GasMeter.h>
#include <libsolutil/CommonData.h>
using namespace std;
using namespace solidity;

View File

@ -27,8 +27,6 @@
#include <liblangutil/EVMVersion.h>
#include <libsolutil/Assertions.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/CommonIO.h>
#include <vector>

View File

@ -79,19 +79,19 @@ void ControlFlowGraph::splitBlocks()
if (item.type() == Tag)
{
if (id)
m_blocks[id].end = index;
m_blocks[id].end = static_cast<unsigned>(index);
id = BlockId::invalid();
}
if (!id)
{
id = item.type() == Tag ? BlockId(item.data()) : generateNewId();
m_blocks[id].begin = index;
m_blocks[id].begin = static_cast<unsigned>(index);
}
if (item.type() == PushTag)
m_blocks[id].pushedTags.emplace_back(item.data());
if (SemanticInformation::altersControlFlow(item))
{
m_blocks[id].end = index + 1;
m_blocks[id].end = static_cast<unsigned>(index + 1);
if (item == Instruction::JUMP)
m_blocks[id].endType = BasicBlock::EndType::JUMP;
else if (item == Instruction::JUMPI)
@ -103,7 +103,7 @@ void ControlFlowGraph::splitBlocks()
}
if (id)
{
m_blocks[id].end = m_items.size();
m_blocks[id].end = static_cast<unsigned>(m_items.size());
if (m_blocks[id].endType == BasicBlock::EndType::HANDOVER)
m_blocks[id].endType = BasicBlock::EndType::STOP;
}

View File

@ -86,7 +86,7 @@ ExpressionClasses::Id ExpressionClasses::find(
exp.id = id;
else
{
exp.id = m_representatives.size();
exp.id = static_cast<Id>(m_representatives.size());
m_representatives.push_back(exp);
}
m_expressions.insert(exp);
@ -117,7 +117,7 @@ void ExpressionClasses::forceEqual(
ExpressionClasses::Id ExpressionClasses::newClass(SourceLocation const& _location)
{
Expression exp;
exp.id = m_representatives.size();
exp.id = static_cast<Id>(m_representatives.size());
exp.item = storeItem(AssemblyItem(UndefinedItem, (u256(1) << 255) + exp.id, _location));
m_representatives.push_back(exp);
m_expressions.insert(exp);

View File

@ -78,7 +78,7 @@ public:
/// @returns the canonical representative of an expression class.
Expression const& representative(Id _id) const { return m_representatives.at(_id); }
/// @returns the number of classes.
Id size() const { return m_representatives.size(); }
size_t size() const { return m_representatives.size(); }
/// Forces the given @a _item with @a _arguments to the class @a _id. This can be used to
/// add prior knowledge e.g. about CALLDATA, but has to be used with caution. Will not work as

View File

@ -209,7 +209,7 @@ CVC4::Expr CVC4Interface::toCVC4Expr(Expression const& _expr)
else if (n == "int2bv")
{
size_t size = std::stoul(_expr.arguments[1].name);
auto i2bvOp = m_context.mkConst(CVC4::IntToBitVector(size));
auto i2bvOp = m_context.mkConst(CVC4::IntToBitVector(static_cast<unsigned>(size)));
// CVC4 treats all BVs as unsigned, so we need to manually apply 2's complement if needed.
return m_context.mkExpr(
CVC4::kind::ITE,

View File

@ -146,4 +146,3 @@ set(sources
add_library(solidity ${sources})
target_link_libraries(solidity PUBLIC yul evmasm langutil smtutil solutil Boost::boost)

View File

@ -71,8 +71,7 @@ public:
using KindCompareType = std::underlying_type<VariableOccurrence::Kind>::type;
return
std::make_pair(m_declaration.id(), static_cast<KindCompareType>(m_occurrenceKind)) <
std::make_pair(_rhs.m_declaration.id(), static_cast<KindCompareType>(_rhs.m_occurrenceKind))
;
std::make_pair(_rhs.m_declaration.id(), static_cast<KindCompareType>(_rhs.m_occurrenceKind));
}
VariableDeclaration const& declaration() const { return m_declaration; }

View File

@ -155,14 +155,14 @@ private:
static std::string literalTokenKind(Token _token);
static std::string type(Expression const& _expression);
static std::string type(VariableDeclaration const& _varDecl);
static int nodeId(ASTNode const& _node)
static int64_t nodeId(ASTNode const& _node)
{
return _node.id();
}
template<class Container>
static Json::Value getContainerIds(Container const& _container, bool _order = false)
{
std::vector<int> tmp;
std::vector<int64_t> tmp;
for (auto const& element: _container)
{
@ -173,7 +173,7 @@ private:
std::sort(tmp.begin(), tmp.end());
Json::Value json(Json::arrayValue);
for (int val: tmp)
for (int64_t val: tmp)
json.append(val);
return json;

View File

@ -368,7 +368,7 @@ RationalNumberType const* TypeProvider::rationalNumber(Literal const& _literal)
{
size_t const digitCount = _literal.valueWithoutUnderscores().length() - 2;
if (digitCount % 2 == 0 && (digitCount / 2) <= 32)
compatibleBytesType = fixedBytes(digitCount / 2);
compatibleBytesType = fixedBytes(static_cast<unsigned>(digitCount / 2));
}
return rationalNumber(std::get<1>(validLiteral), compatibleBytesType);

View File

@ -781,7 +781,7 @@ tuple<bool, rational> RationalNumberType::parseRational(string const& _value)
denominator = bigint(string(fractionalBegin, _value.end()));
denominator /= boost::multiprecision::pow(
bigint(10),
static_cast<size_t>(distance(radixPoint + 1, _value.end()))
static_cast<unsigned>(distance(radixPoint + 1, _value.end()))
);
numerator = bigint(string(_value.begin(), radixPoint));
value = numerator + denominator;

View File

@ -294,6 +294,7 @@ public:
return *m_stackItems;
}
/// Total number of stack slots occupied by this type. This is the sum of ``sizeOnStack`` of all ``stackItems()``.
// TODO: consider changing the return type to be size_t
unsigned sizeOnStack() const
{
if (!m_stackSize)
@ -306,7 +307,7 @@ public:
++sizeOnStack;
m_stackSize = sizeOnStack;
}
return *m_stackSize;
return static_cast<unsigned>(*m_stackSize);
}
/// If it is possible to initialize such a value in memory by just writing zeros
/// of the size memoryHeadSize().

View File

@ -249,7 +249,7 @@ void CompilerContext::removeVariablesAboveStackHeight(unsigned _stackHeight)
unsigned CompilerContext::numberOfLocalVariables() const
{
return m_localVariables.size();
return static_cast<unsigned>(m_localVariables.size());
}
shared_ptr<evmasm::Assembly> CompilerContext::compiledContract(ContractDefinition const& _contract) const
@ -430,10 +430,10 @@ void CompilerContext::appendInlineAssembly(
util::errinfo_comment("Stack too deep (" + to_string(stackDiff) + "), try removing local variables.")
);
if (_context == yul::IdentifierContext::RValue)
_assembly.appendInstruction(dupInstruction(stackDiff));
_assembly.appendInstruction(dupInstruction(static_cast<unsigned>(stackDiff)));
else
{
_assembly.appendInstruction(swapInstruction(stackDiff));
_assembly.appendInstruction(swapInstruction(static_cast<unsigned>(stackDiff)));
_assembly.appendInstruction(Instruction::POP);
}
};

View File

@ -928,7 +928,7 @@ void CompilerUtils::convertType(
{
auto const& arrayType = dynamic_cast<ArrayType const&>(_targetType);
solAssert(arrayType.isByteArray(), "");
unsigned storageSize = 32 + ((data.size() + 31) / 32) * 32;
size_t storageSize = 32 + ((data.size() + 31) / 32) * 32;
allocateMemory(storageSize);
// stack: mempos
m_context << Instruction::DUP1 << u256(data.size());

View File

@ -193,7 +193,7 @@ size_t ContractCompiler::packIntoContractCreator(ContractDefinition const& _cont
auto const& immutables = contractType.immutableVariables();
// Push all immutable values on the stack.
for (auto const& immutable: immutables)
CompilerUtils(m_context).loadFromMemory(m_context.immutableMemoryOffset(*immutable), *immutable->annotation().type);
CompilerUtils(m_context).loadFromMemory(static_cast<unsigned>(m_context.immutableMemoryOffset(*immutable)), *immutable->annotation().type);
m_context.pushSubroutineSize(m_context.runtimeSub());
if (immutables.empty())
m_context << Instruction::DUP1;
@ -673,7 +673,7 @@ bool ContractCompiler::visit(FunctionDefinition const& _function)
}
else
{
m_context << swapInstruction(stackLayout.size() - static_cast<unsigned>(stackLayout.back()) - 1u);
m_context << swapInstruction(static_cast<unsigned>(stackLayout.size()) - static_cast<unsigned>(stackLayout.back()) - 1u);
swap(stackLayout[static_cast<size_t>(stackLayout.back())], stackLayout.back());
}
for (size_t i = 0; i < stackLayout.size(); ++i)

View File

@ -131,7 +131,7 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
// stack: <keys..> <slot position>
// copy key[i] to top.
utils().copyToStackTop(paramTypes.size() - i + 1, 1);
utils().copyToStackTop(static_cast<unsigned>(paramTypes.size() - i + 1), 1);
m_context.appendInlineAssembly(R"({
let key_len := mload(key_ptr)
@ -155,7 +155,7 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
utils().storeInMemory(32);
// move key to memory.
utils().copyToStackTop(paramTypes.size() - i, 1);
utils().copyToStackTop(static_cast<unsigned>(paramTypes.size() - i), 1);
utils().storeInMemory(0);
m_context << u256(64) << u256(0);
m_context << Instruction::KECCAK256;
@ -169,7 +169,7 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
{
// pop offset
m_context << Instruction::POP;
utils().copyToStackTop(paramTypes.size() - i + 1, 1);
utils().copyToStackTop(static_cast<unsigned>(paramTypes.size() - i + 1), 1);
ArrayUtils(m_context).retrieveLength(*arrayType, 1);
// Stack: ref [length] index length
@ -190,9 +190,9 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
m_context << Instruction::SWAP2 << Instruction::POP << Instruction::SWAP1;
else if (paramTypes.size() >= 2)
{
m_context << swapInstruction(paramTypes.size());
m_context << swapInstruction(static_cast<unsigned>(paramTypes.size()));
m_context << Instruction::POP;
m_context << swapInstruction(paramTypes.size());
m_context << swapInstruction(static_cast<unsigned>(paramTypes.size()));
utils().popStackSlots(paramTypes.size() - 1);
}
unsigned retSizeOnStack = 0;
@ -840,7 +840,7 @@ bool ExpressionCompiler::visit(FunctionCall const& _functionCall)
unsigned numIndexed = 0;
TypePointers paramTypes = function.parameterTypes();
// All indexed arguments go to the stack
for (unsigned arg = arguments.size(); arg > 0; --arg)
for (size_t arg = arguments.size(); arg > 0; --arg)
if (event.parameters()[arg - 1]->isIndexed())
{
++numIndexed;
@ -1292,7 +1292,7 @@ bool ExpressionCompiler::visit(FunctionCallOptions const& _functionCallOptions)
solAssert(!contains(presentOptions, newOption), "");
ptrdiff_t insertPos = presentOptions.end() - lower_bound(presentOptions.begin(), presentOptions.end(), newOption);
utils().moveIntoStack(static_cast<size_t>(insertPos), 1);
utils().moveIntoStack(static_cast<unsigned>(insertPos), 1);
presentOptions.insert(presentOptions.end() - insertPos, newOption);
}

View File

@ -437,17 +437,32 @@ pair<string, map<ContractDefinition const*, vector<string>>> IRGenerator::evalua
ContractDefinition const& _contract
)
{
struct InheritanceOrder
{
bool operator()(ContractDefinition const* _c1, ContractDefinition const* _c2) const
{
solAssert(contains(linearizedBaseContracts, _c1) && contains(linearizedBaseContracts, _c2), "");
auto it1 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c1);
auto it2 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c2);
return it1 < it2;
}
vector<ContractDefinition const*> const& linearizedBaseContracts;
} inheritanceOrder{_contract.annotation().linearizedBaseContracts};
map<ContractDefinition const*, vector<string>> constructorParams;
vector<pair<ContractDefinition const*, std::vector<ASTPointer<Expression>>const *>> baseConstructorArguments;
map<ContractDefinition const*, std::vector<ASTPointer<Expression>>const *, InheritanceOrder>
baseConstructorArguments(inheritanceOrder);
;
for (ASTPointer<InheritanceSpecifier> const& base: _contract.baseContracts())
if (FunctionDefinition const* baseConstructor = dynamic_cast<ContractDefinition const*>(
base->name().annotation().referencedDeclaration
)->constructor(); baseConstructor && base->arguments())
baseConstructorArguments.emplace_back(
solAssert(baseConstructorArguments.emplace(
dynamic_cast<ContractDefinition const*>(baseConstructor->scope()),
base->arguments()
);
).second, "");
if (FunctionDefinition const* constructor = _contract.constructor())
for (ASTPointer<ModifierInvocation> const& modifier: constructor->modifiers())
@ -458,10 +473,10 @@ pair<string, map<ContractDefinition const*, vector<string>>> IRGenerator::evalua
FunctionDefinition const* baseConstructor = baseContract->constructor();
baseConstructor && modifier->arguments()
)
baseConstructorArguments.emplace_back(
solAssert(baseConstructorArguments.emplace(
dynamic_cast<ContractDefinition const*>(baseConstructor->scope()),
modifier->arguments()
);
).second, "");
IRGeneratorForStatements generator{m_context, m_utils};
for (auto&& [baseContract, arguments]: baseConstructorArguments)

View File

@ -302,7 +302,15 @@ optional<string> Predicate::expressionToString(smtutil::Expression const& _expr,
auto const& tupleSort = dynamic_cast<TupleSort const&>(*_expr.sort);
solAssert(tupleSort.components.size() == 2, "");
auto length = stoul(_expr.arguments.at(1).name);
unsigned long length;
try
{
length = stoul(_expr.arguments.at(1).name);
}
catch(out_of_range const&)
{
return {};
}
// Limit this counterexample size to 1k.
// Some OSs give you "unlimited" memory through swap and other virtual memory,
// so purely relying on bad_alloc being thrown is not a good idea.
@ -321,6 +329,22 @@ optional<string> Predicate::expressionToString(smtutil::Expression const& _expr,
// Solver gave a concrete array but length is too large.
}
}
if (smt::isNonRecursiveStruct(*_type))
{
auto const& structType = dynamic_cast<StructType const&>(*_type);
solAssert(_expr.name == "tuple_constructor", "");
auto const& tupleSort = dynamic_cast<TupleSort const&>(*_expr.sort);
auto members = structType.structDefinition().members();
solAssert(tupleSort.components.size() == members.size(), "");
solAssert(_expr.arguments.size() == members.size(), "");
vector<string> elements;
for (unsigned i = 0; i < members.size(); ++i)
{
optional<string> elementStr = expressionToString(_expr.arguments.at(i), members[i]->type());
elements.push_back(members[i]->name() + (elementStr.has_value() ? ": " + elementStr.value() : ""));
}
return "{" + boost::algorithm::join(elements, ", ") + "}";
}
return {};
}
@ -366,5 +390,12 @@ bool Predicate::fillArray(smtutil::Expression const& _expr, vector<string>& _arr
return true;
}
// Special base case, not supported yet.
if (_expr.name.rfind("(_ as-array") == 0)
{
// Z3 expression representing reinterpretation of a different term as an array
return false;
}
solAssert(false, "");
}

View File

@ -1489,7 +1489,7 @@ public:
bytes serialise() const
{
unsigned size = m_data.size() + 1;
size_t size = m_data.size() + 1;
solAssert(size <= 0xffff, "Metadata too large.");
solAssert(m_entryCount <= 0x1f, "Too many map entries.");
@ -1505,7 +1505,7 @@ public:
private:
void pushTextString(string const& key)
{
unsigned length = key.size();
size_t length = key.size();
if (length < 24)
{
m_data += bytes{static_cast<unsigned char>(0x60 + length)};
@ -1521,7 +1521,7 @@ private:
}
void pushByteString(bytes const& key)
{
unsigned length = key.size();
size_t length = key.size();
if (length < 24)
{
m_data += bytes{static_cast<unsigned char>(0x40 + length)};

View File

@ -57,7 +57,7 @@ inline T readFile(std::string const& _file)
is.seekg(0, is.beg);
ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), length);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<streamsize>(length));
return ret;
}

View File

@ -198,4 +198,4 @@ foreach(polyfill IN LISTS POLYFILLS)
configure_file("${CMAKE_SOURCE_DIR}/cmake/templates/ewasm_polyfill.in" ${CMAKE_BINARY_DIR}/include/ewasmPolyfills/${polyfill}.h @ONLY)
endforeach()
target_link_libraries(yul PUBLIC evmasm solutil langutil smtutil)
target_link_libraries(yul PUBLIC evmasm solutil langutil smtutil)

View File

@ -49,7 +49,7 @@ string solidity::yul::reindent(string const& _code)
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 opening - closing;
return int(opening - closing);
};
vector<string> lines;

View File

@ -53,7 +53,7 @@ void EVMAssembly::appendInstruction(evmasm::Instruction _instr)
void EVMAssembly::appendConstant(u256 const& _constant)
{
bytes data = toCompactBigEndian(_constant, 1);
appendInstruction(evmasm::pushInstruction(data.size()));
appendInstruction(evmasm::pushInstruction(static_cast<unsigned>(data.size())));
m_bytecode += data;
}

View File

@ -222,7 +222,7 @@ void CodeTransform::operator()(VariableDeclaration const& _varDecl)
m_unusedStackSlots.erase(m_unusedStackSlots.begin());
m_context->variableStackHeights[&var] = slot;
if (size_t heightDiff = variableHeightDiff(var, varName, true))
m_assembly.appendInstruction(evmasm::swapInstruction(heightDiff - 1));
m_assembly.appendInstruction(evmasm::swapInstruction(static_cast<unsigned>(heightDiff - 1)));
m_assembly.appendInstruction(evmasm::Instruction::POP);
}
}
@ -314,7 +314,7 @@ void CodeTransform::operator()(Identifier const& _identifier)
// TODO: opportunity for optimization: Do not DUP if this is the last reference
// to the top most element of the stack
if (size_t heightDiff = variableHeightDiff(_var, _identifier.name, false))
m_assembly.appendInstruction(evmasm::dupInstruction(heightDiff));
m_assembly.appendInstruction(evmasm::dupInstruction(static_cast<unsigned>(heightDiff)));
else
// Store something to balance the stack
m_assembly.appendConstant(u256(0));
@ -694,7 +694,7 @@ void CodeTransform::generateAssignment(Identifier const& _variableName)
{
Scope::Variable const& _var = std::get<Scope::Variable>(*var);
if (size_t heightDiff = variableHeightDiff(_var, _variableName.name, true))
m_assembly.appendInstruction(evmasm::swapInstruction(heightDiff - 1));
m_assembly.appendInstruction(evmasm::swapInstruction(static_cast<unsigned>(heightDiff - 1)));
m_assembly.appendInstruction(evmasm::Instruction::POP);
decreaseReference(_variableName.name, _var);
}

View File

@ -300,7 +300,7 @@ h160 EVMHost::convertFromEVMC(evmc::address const& _addr)
evmc::address EVMHost::convertToEVMC(h160 const& _addr)
{
evmc::address a;
for (size_t i = 0; i < 20; ++i)
for (unsigned i = 0; i < 20; ++i)
a.bytes[i] = _addr[i];
return a;
}
@ -313,7 +313,7 @@ h256 EVMHost::convertFromEVMC(evmc::bytes32 const& _data)
evmc::bytes32 EVMHost::convertToEVMC(h256 const& _data)
{
evmc::bytes32 d;
for (size_t i = 0; i < 32; ++i)
for (unsigned i = 0; i < 32; ++i)
d.bytes[i] = _data[i];
return d;
}

View File

@ -34,7 +34,7 @@ namespace solidity::test
bytes onlyMetadata(bytes const& _bytecode)
{
unsigned size = _bytecode.size();
size_t size = _bytecode.size();
if (size < 5)
return bytes{};
size_t metadataSize = (static_cast<size_t>(_bytecode[size - 2]) << 8ul) + static_cast<size_t>(_bytecode[size - 1]);
@ -49,10 +49,10 @@ bytes onlyMetadata(bytes const& _bytecode)
bytes bytecodeSansMetadata(bytes const& _bytecode)
{
unsigned metadataSize = onlyMetadata(_bytecode).size();
size_t metadataSize = onlyMetadata(_bytecode).size();
if (metadataSize == 0)
return bytes{};
return bytes(_bytecode.begin(), _bytecode.end() - metadataSize - 2);
return bytes(_bytecode.begin(), _bytecode.end() - static_cast<ptrdiff_t>(metadataSize) - 2);
}
string bytecodeSansMetadata(string const& _bytecode)

View File

@ -1282,7 +1282,7 @@ BOOST_AUTO_TEST_CASE(cse_remove_redundant_shift_masking)
if (!solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting())
return;
for (size_t i = 1; i < 256; i++)
for (unsigned i = 1; i < 256; i++)
{
checkCSE({
u256(boost::multiprecision::pow(u256(2), i) - 1),
@ -1310,7 +1310,7 @@ BOOST_AUTO_TEST_CASE(cse_remove_redundant_shift_masking)
}
// Check that opt. does NOT trigger
for (size_t i = 1; i < 255; i++)
for (unsigned i = 1; i < 255; i++)
{
checkCSE({
u256(boost::multiprecision::pow(u256(2), i) - 1),

View File

@ -133,7 +133,7 @@ TestCase::TestResult ASTJSONTest::run(ostream& _stream, string const& _linePrefi
for (size_t i = 0; i < m_sources.size(); i++)
{
sources[m_sources[i].first] = m_sources[i].second;
sourceIndices[m_sources[i].first] = i + 1;
sourceIndices[m_sources[i].first] = static_cast<unsigned>(i + 1);
}
c.setSources(sources);
c.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());

View File

@ -39,6 +39,7 @@
#include <boost/test/unit_test.hpp>
#include <functional>
#include <numeric>
#include <string>
#include <tuple>
@ -82,7 +83,7 @@ struct SolidityEndToEndTestExecutionFramework: public SolidityExecutionFramework
BOOST_FIXTURE_TEST_SUITE(SolidityEndToEndTest, SolidityEndToEndTestExecutionFramework)
int constexpr roundTo32(int _num)
unsigned constexpr roundTo32(unsigned _num)
{
return (_num + 31) / 32 * 32;
}
@ -2126,8 +2127,7 @@ BOOST_AUTO_TEST_CASE(event_indexed_string)
BOOST_REQUIRE_EQUAL(numLogs(), 1);
BOOST_CHECK_EQUAL(logAddress(0), m_contractAddress);
string dynx(90, 0);
for (size_t i = 0; i < dynx.size(); ++i)
dynx[i] = i;
std::iota(dynx.begin(), dynx.end(), 0);
BOOST_CHECK(logData(0) == bytes());
BOOST_REQUIRE_EQUAL(numLogTopics(0), 3);
BOOST_CHECK_EQUAL(logTopic(0, 1), util::keccak256(dynx));
@ -3362,7 +3362,7 @@ BOOST_AUTO_TEST_CASE(nested_string_as_public_mapping_key)
ABI_CHECK(callContractFunction(
"set(string,string,uint256)",
u256(0x60),
u256(roundTo32(0x80 + strings[i].size())),
u256(roundTo32(static_cast<unsigned>(0x80 + strings[i].size()))),
u256(7 + i),
u256(strings[i].size()),
strings[i],
@ -3373,7 +3373,7 @@ BOOST_AUTO_TEST_CASE(nested_string_as_public_mapping_key)
ABI_CHECK(callContractFunction(
"data(string,string)",
u256(0x40),
u256(roundTo32(0x60 + strings[i].size())),
u256(roundTo32(static_cast<unsigned>(0x60 + strings[i].size()))),
u256(strings[i].size()),
strings[i],
u256(strings[i+1].size()),
@ -3426,7 +3426,7 @@ BOOST_AUTO_TEST_CASE(nested_mixed_string_as_public_mapping_key)
u256(0xA0),
u256(data[i].s2),
u256(data[i].s3),
u256(roundTo32(0xC0 + data[i].s1.size())),
u256(roundTo32(static_cast<unsigned>(0xC0 + data[i].s1.size()))),
u256(i - 3),
u256(data[i].s1.size()),
data[i].s1,
@ -3439,7 +3439,7 @@ BOOST_AUTO_TEST_CASE(nested_mixed_string_as_public_mapping_key)
u256(0x80),
u256(data[i].s2),
u256(data[i].s3),
u256(roundTo32(0xA0 + data[i].s1.size())),
u256(roundTo32(static_cast<unsigned>(0xA0 + data[i].s1.size()))),
u256(data[i].s1.size()),
data[i].s1,
u256(data[i].s4.size()),

View File

@ -149,7 +149,7 @@ bytes compileFirstExpression(
for (vector<string> const& variable: _localVariables)
context.addVariable(
dynamic_cast<VariableDeclaration const&>(resolveDeclaration(*sourceUnit, variable, resolver)),
parametersSize--
static_cast<unsigned>(parametersSize--)
);
ExpressionCompiler(

View File

@ -495,7 +495,7 @@ BOOST_AUTO_TEST_CASE(constant_optimization_early_exit)
maxDuration = numeric_limits<size_t>::max();
BOOST_TEST_MESSAGE("Disabled constant optimizer run time check for address sanitizer build.");
#endif
BOOST_CHECK_MESSAGE(duration <= maxDuration, "Compilation of constants took longer than 20 seconds.");
BOOST_CHECK_MESSAGE(duration <= double(maxDuration), "Compilation of constants took longer than 20 seconds.");
compareVersions("hexEncodeTest(address)", u256(0x123456789));
}

View File

@ -262,13 +262,6 @@ BOOST_AUTO_TEST_CASE(helper_bool_result)
r5.merge(r6, logical_and<bool>());
BOOST_REQUIRE_EQUAL(r5.get(), true);
BOOST_REQUIRE_EQUAL(r5.message(), "");
BoolResult r7{true};
// Attention: this will implicitly convert to bool.
BoolResult r8("true"); // We cannot use {} initializer here because this does not allow narrowing conversion (at least MSVC breaks)
r7.merge(r8, logical_and<bool>());
BOOST_REQUIRE_EQUAL(r7.get(), true);
BOOST_REQUIRE_EQUAL(r7.message(), "");
}
BOOST_AUTO_TEST_CASE(helper_string_result)

View File

@ -0,0 +1,24 @@
contract A {
constructor(uint) {}
}
contract B {
constructor(uint) {}
}
contract C {
constructor(uint) {}
}
contract D {
constructor(uint) {}
}
contract X is D, C, B, A {
uint[] x;
function f(uint _x) internal returns (uint) {
x.push(_x);
}
function g() public view returns (uint[] memory) { return x; }
constructor() A(f(1)) C(f(2)) B(f(3)) D(f(4)) {}
}
// ====
// compileViaYul: also
// ----
// g() -> 0x20, 4, 1, 3, 2, 4

View File

@ -264,13 +264,13 @@ string BytesUtils::formatBytes(
{
auto entropy = [](std::string const& str) -> double {
double result = 0;
map<char, int> frequencies;
map<char, double> frequencies;
for (char c: str)
frequencies[c]++;
for (auto p: frequencies)
{
double freq = static_cast<double>(p.second) / str.length();
result -= freq * (log(freq) / log(2));
double freq = p.second / double(str.length());
result -= freq * (log(freq) / log(2.0));
}
return result;
};

View File

@ -682,11 +682,12 @@ string TestFileParser::Scanner::scanString()
return str;
}
// TODO: use fromHex() from CommonData
char TestFileParser::Scanner::scanHexPart()
{
advance(); // skip 'x'
char value{};
int value{};
if (isdigit(current()))
value = current() - '0';
else if (tolower(current()) >= 'a' && tolower(current()) <= 'f')
@ -696,7 +697,7 @@ char TestFileParser::Scanner::scanHexPart()
advance();
if (current() == '"')
return value;
return static_cast<char>(value);
value <<= 4;
if (isdigit(current()))
@ -706,5 +707,5 @@ char TestFileParser::Scanner::scanHexPart()
advance();
return value;
return static_cast<char>(value);
}

View File

@ -418,7 +418,7 @@ string ProtoConverter::visit(TestFunction const& _x, string const& _storageVarDe
("functionDeclReturndata", functionDeclReturndata)
("storageVarDefs", _storageVarDefs)
("localVarDefs", localVarDefs)
("calldataTestCode", testCallDataFunction(_x.invalid_encoding_length()))
("calldataTestCode", testCallDataFunction(static_cast<unsigned>(_x.invalid_encoding_length())))
("returndataTestCode", testReturnDataFunction())
("return_types", m_types.str())
("return_values", m_argsCoder.str())

View File

@ -37,7 +37,7 @@ struct SolRandomNumGenerator
/// @returns a pseudo random unsigned integer
unsigned operator()()
{
return m_random();
return static_cast<unsigned>(m_random());
}
RandomEngine m_random;

View File

@ -182,9 +182,9 @@ bool ProtoConverter::functionCallNotPossible(FunctionCall_Returns _type)
unsigned ProtoConverter::numVarsInScope()
{
if (m_inFunctionDef)
return m_currentFuncVars.size();
return static_cast<unsigned>(m_currentFuncVars.size());
else
return m_currentGlobalVars.size();
return static_cast<unsigned>(m_currentGlobalVars.size());
}
void ProtoConverter::visit(VarRef const& _x)
@ -1344,12 +1344,12 @@ void ProtoConverter::visit(UnaryOpData const& _x)
{
case UnaryOpData::SIZE:
m_output << Whiskers(R"(datasize("<id>"))")
("id", getObjectIdentifier(_x.identifier()))
("id", getObjectIdentifier(static_cast<unsigned>(_x.identifier())))
.render();
break;
case UnaryOpData::OFFSET:
m_output << Whiskers(R"(dataoffset("<id>"))")
("id", getObjectIdentifier(_x.identifier()))
("id", getObjectIdentifier(static_cast<unsigned>(_x.identifier())))
.render();
break;
}
@ -1473,7 +1473,7 @@ void ProtoConverter::openFunctionScope(vector<string> const& _funcParams)
void ProtoConverter::updateFunctionMaps(string const& _var)
{
unsigned erased = m_functionSigMap.erase(_var);
size_t erased = m_functionSigMap.erase(_var);
for (auto const& i: m_functionDefMap)
if (i.second == _var)
@ -1491,7 +1491,7 @@ void ProtoConverter::closeBlockScope()
// out of scope from the global function map.
for (auto const& f: m_scopeFuncs.back())
{
unsigned numFuncsRemoved = m_functions.size();
size_t numFuncsRemoved = m_functions.size();
m_functions.erase(remove(m_functions.begin(), m_functions.end(), f), m_functions.end());
numFuncsRemoved -= m_functions.size();
yulAssert(
@ -1908,7 +1908,7 @@ void ProtoConverter::buildObjectScopeTree(Object const& _x)
void ProtoConverter::visit(Program const& _x)
{
// Initialize input size
m_inputSize = _x.ByteSizeLong();
m_inputSize = static_cast<unsigned>(_x.ByteSizeLong());
// Record EVM Version
m_evmVersion = evmVersionMapping(_x.ver());

View File

@ -38,7 +38,7 @@ struct YulRandomNumGenerator
unsigned operator()()
{
return m_random();
return static_cast<unsigned>(m_random());
}
RandomEngine m_random;

View File

@ -40,7 +40,7 @@ extern "C" int LLVMFuzzerTestOneInput(uint8_t const* _data, size_t _size)
{
return 0;
}
FuzzerUtil::testCompiler(sourceCode, /*optimize=*/false, /*_rand=*/_size);
FuzzerUtil::testCompiler(sourceCode, /*optimize=*/false, /*_rand=*/static_cast<unsigned>(_size));
}
return 0;
}

View File

@ -40,7 +40,7 @@ extern "C" int LLVMFuzzerTestOneInput(uint8_t const* _data, size_t _size)
{
return 0;
}
FuzzerUtil::testCompiler(sourceCode, /*optimize=*/true, /*rand=*/_size);
FuzzerUtil::testCompiler(sourceCode, /*optimize=*/true, /*rand=*/static_cast<unsigned>(_size));
}
return 0;
}

View File

@ -451,7 +451,8 @@ u256 EVMInstructionInterpreter::evalBuiltin(
else
{
// Force different value than for datasize
arg[31] += 2;
arg[31]++;
arg[31]++;
return u256(keccak256(arg)) & 0xfff;
}
}

View File

@ -135,7 +135,9 @@ u256 EwasmBuiltinInterpreter::evalBuiltin(
return u256(util::keccak256(arg)) & 0xfff;
else if (fun == "dataoffset")
{
arg[31] += 2;
// Force different value than for datasize
arg[31]++;
arg[31]++;
return u256(util::keccak256(arg)) & 0xfff;
}
}
@ -198,7 +200,7 @@ u256 EwasmBuiltinInterpreter::evalBuiltin(
else if (fun == "i32.store")
{
accessMemory(arg[0], 4);
writeMemoryHalfWord(arg[0], arg[1]);
writeMemoryHalfWord(arg[0], static_cast<uint32_t>(arg[1]));
return 0;
}
else if (fun == "i32.load")
@ -453,7 +455,7 @@ u256 EwasmBuiltinInterpreter::evalEthBuiltin(string const& _fun, vector<uint64_t
readBytes32(arg[5]);
if (numberOfTopics > 3)
readBytes32(arg[6]);
logTrace(evmasm::logInstruction(numberOfTopics), {});
logTrace(evmasm::logInstruction(static_cast<unsigned>(numberOfTopics)), {});
return 0;
}
else if (_fun == "getBlockNumber")
@ -538,7 +540,7 @@ uint32_t EwasmBuiltinInterpreter::readMemoryHalfWord(uint64_t _offset)
{
uint32_t r = 0;
for (size_t i = 0; i < 4; i++)
r |= uint64_t(m_state.memory[_offset + i]) << (i * 8);
r |= uint32_t(m_state.memory[_offset + i]) << (i * 8);
return r;
}

View File

@ -112,7 +112,7 @@ public:
auto printPair = [&](auto const& optionAndDescription)
{
cout << optionAndDescription.first << ": ";
cout << setw(longestDescriptionLength) << setiosflags(ios::left);
cout << setw(static_cast<int>(longestDescriptionLength)) << setiosflags(ios::left);
cout << optionAndDescription.second << " ";
++index;
@ -165,8 +165,9 @@ public:
printUsageBanner(abbreviationMap, extraOptions, 4);
cout << "? ";
cout.flush();
int option = readStandardInputChar();
cout << ' ' << char(option) << endl;
// TODO: handle EOF properly.
char option = static_cast<char>(readStandardInputChar());
cout << ' ' << option << endl;
OptimiserStepContext context{m_dialect, *m_nameDispenser, reservedIdentifiers};

View File

@ -83,8 +83,8 @@ BOOST_AUTO_TEST_CASE(makeRandom_should_use_every_possible_step_with_the_same_pro
for (auto& step: chromosome.optimisationSteps())
samples.push_back(stepIndices.at(step));
const double expectedValue = (stepIndices.size() - 1) / 2.0;
const double variance = (stepIndices.size() * stepIndices.size() - 1) / 12.0;
const double expectedValue = double(stepIndices.size() - 1) / 2.0;
const double variance = double(stepIndices.size() * stepIndices.size() - 1) / 12.0;
BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);
@ -157,8 +157,8 @@ BOOST_AUTO_TEST_CASE(randomOptimisationStep_should_return_each_step_with_same_pr
for (size_t i = 0; i <= stepIndices.size() * samplesPerStep; ++i)
samples.push_back(stepIndices.at(Chromosome::randomOptimisationStep()));
const double expectedValue = (stepIndices.size() - 1) / 2.0;
const double variance = (stepIndices.size() * stepIndices.size() - 1) / 12.0;
const double expectedValue = double(stepIndices.size() - 1) / 2.0;
const double variance = double(stepIndices.size() * stepIndices.size() - 1) / 12.0;
BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);

View File

@ -183,7 +183,7 @@ BOOST_FIXTURE_TEST_CASE(evaluate_should_compute_the_size_ratio_between_optimised
{
BOOST_TEST(
RelativeProgramSize(m_program, nullptr, 3, m_weights).evaluate(m_chromosome) ==
round(1000.0 * m_optimisedProgram.codeSize(m_weights) / m_program.codeSize(m_weights))
round(1000.0 * double(m_optimisedProgram.codeSize(m_weights)) / double(m_program.codeSize(m_weights)))
);
}
@ -191,7 +191,7 @@ BOOST_FIXTURE_TEST_CASE(evaluate_should_be_able_to_use_program_cache_if_availabl
{
BOOST_TEST(
RelativeProgramSize(nullopt, m_programCache, 3, m_weights).evaluate(m_chromosome) ==
round(1000.0 * m_optimisedProgram.codeSize(m_weights) / m_program.codeSize(m_weights))
round(1000.0 * double(m_optimisedProgram.codeSize(m_weights)) / double(m_program.codeSize(m_weights)))
);
BOOST_TEST(m_programCache->size() == m_chromosome.length());
}
@ -206,7 +206,7 @@ BOOST_FIXTURE_TEST_CASE(evaluate_should_repeat_the_optimisation_specified_number
BOOST_TEST(fitness != 1000);
BOOST_TEST(fitness != RelativeProgramSize(programOptimisedTwice, nullptr, 3, m_weights, 1).evaluate(m_chromosome));
BOOST_TEST(fitness == round(1000.0 * programOptimisedTwice.codeSize(m_weights) / m_program.codeSize(m_weights)));
BOOST_TEST(fitness == round(1000.0 * double(programOptimisedTwice.codeSize(m_weights)) / double(m_program.codeSize(m_weights))));
}
BOOST_FIXTURE_TEST_CASE(evaluate_should_return_one_if_number_of_repetitions_is_zero, ProgramBasedMetricFixture)
@ -230,7 +230,7 @@ BOOST_FIXTURE_TEST_CASE(evaluate_should_return_one_if_the_original_program_size_
BOOST_FIXTURE_TEST_CASE(evaluate_should_multiply_the_result_by_scaling_factor, ProgramBasedMetricFixture)
{
double sizeRatio = static_cast<double>(m_optimisedProgram.codeSize(m_weights)) / m_program.codeSize(m_weights);
double sizeRatio = double(m_optimisedProgram.codeSize(m_weights)) / double(m_program.codeSize(m_weights));
BOOST_TEST(RelativeProgramSize(m_program, nullptr, 0, m_weights).evaluate(m_chromosome) == round(1.0 * sizeRatio));
BOOST_TEST(RelativeProgramSize(m_program, nullptr, 1, m_weights).evaluate(m_chromosome) == round(10.0 * sizeRatio));
BOOST_TEST(RelativeProgramSize(m_program, nullptr, 2, m_weights).evaluate(m_chromosome) == round(100.0 * sizeRatio));

View File

@ -53,7 +53,7 @@ BOOST_AUTO_TEST_CASE(geneRandomisation_should_iterate_over_genes_and_replace_the
SimulationRNG::reset(1);
for (size_t randomisationChancePercent = 20; randomisationChancePercent <= 100; randomisationChancePercent += 20)
{
double const randomisationChance = (randomisationChancePercent / 100.0);
double const randomisationChance = double(randomisationChancePercent) / 100.0;
Chromosome output = geneRandomisation(randomisationChance)(input);
string outputGenes = output.genes();
@ -61,7 +61,7 @@ BOOST_AUTO_TEST_CASE(geneRandomisation_should_iterate_over_genes_and_replace_the
double const expectedValue = randomisationChance;
double const variance = randomisationChance * (1 - randomisationChance);
double const randomisedGeneCount = input.length() - static_cast<size_t>(count(outputGenes.begin(), outputGenes.end(), '.'));
double const randomisedGeneCount = double(input.length() - static_cast<size_t>(count(outputGenes.begin(), outputGenes.end(), '.')));
double const squaredError =
(inputLength - randomisedGeneCount) * expectedValue * expectedValue +
randomisedGeneCount * (1 - expectedValue) * (1 - expectedValue);
@ -91,7 +91,7 @@ BOOST_AUTO_TEST_CASE(geneDeletion_should_iterate_over_genes_and_delete_them_with
SimulationRNG::reset(1);
for (size_t deletionChancePercent = 20; deletionChancePercent < 100; deletionChancePercent += 20)
{
double const deletionChance = (deletionChancePercent / 100.0);
double const deletionChance = double(deletionChancePercent) / 100.0;
Chromosome output = geneDeletion(deletionChance)(input);
string outputGenes = output.genes();
@ -99,14 +99,14 @@ BOOST_AUTO_TEST_CASE(geneDeletion_should_iterate_over_genes_and_delete_them_with
BOOST_REQUIRE(static_cast<size_t>(count(outputGenes.begin(), outputGenes.end(), '.')) == output.length());
double const expectedValue = deletionChance;
double const variance = deletionChance * (1 - deletionChance);
double const deletedGeneCount = input.length() - output.length();
double const variance = deletionChance * (1.0 - deletionChance);
double const deletedGeneCount = double(input.length() - output.length());
double const squaredError =
(inputLength - deletedGeneCount) * expectedValue * expectedValue +
deletedGeneCount * (1 - expectedValue) * (1 - expectedValue);
(double(inputLength) - deletedGeneCount) * expectedValue * expectedValue +
deletedGeneCount * (1.0 - expectedValue) * (1.0 - expectedValue);
BOOST_TEST(abs(deletedGeneCount / inputLength - expectedValue) < tolerance);
BOOST_TEST(abs(squaredError / inputLength - variance) < tolerance);
BOOST_TEST(abs(deletedGeneCount / double(inputLength) - expectedValue) < tolerance);
BOOST_TEST(abs(squaredError / double(inputLength) - variance) < tolerance);
}
}
@ -139,7 +139,7 @@ BOOST_AUTO_TEST_CASE(geneAddition_should_iterate_over_gene_positions_and_insert_
SimulationRNG::reset(1);
for (size_t additionChancePercent = 20; additionChancePercent < 100; additionChancePercent += 20)
{
double const additionChance = (additionChancePercent / 100.0);
double const additionChance = double(additionChancePercent) / 100.0;
Chromosome output = geneAddition(additionChance)(input);
BOOST_REQUIRE(output.length() >= input.length());
@ -150,14 +150,14 @@ BOOST_AUTO_TEST_CASE(geneAddition_should_iterate_over_gene_positions_and_insert_
BOOST_REQUIRE(preservedGeneCount == input.length());
double const expectedValue = additionChance;
double const variance = additionChance * (1 - additionChance);
double const addedGeneCount = (output.length() - preservedGeneCount);
double const variance = additionChance * (1.0 - additionChance);
double const addedGeneCount = double(output.length() - preservedGeneCount);
double const squaredError =
(maxAdditions - addedGeneCount) * expectedValue * expectedValue +
addedGeneCount * (1 - expectedValue) * (1 - expectedValue);
(double(maxAdditions) - addedGeneCount) * expectedValue * expectedValue +
addedGeneCount * (1.0 - expectedValue) * (1.0 - expectedValue);
BOOST_TEST(abs(addedGeneCount / maxAdditions - expectedValue) < tolerance);
BOOST_TEST(abs(squaredError / maxAdditions - variance) < tolerance);
BOOST_TEST(abs(addedGeneCount / double(maxAdditions) - expectedValue) < tolerance);
BOOST_TEST(abs(squaredError / double(maxAdditions) - variance) < tolerance);
}
}

View File

@ -194,8 +194,8 @@ BOOST_FIXTURE_TEST_CASE(makeRandom_should_return_population_with_random_chromoso
for (auto& step: individual.chromosome.optimisationSteps())
samples.push_back(stepIndices.at(step));
const double expectedValue = (stepIndices.size() - 1) / 2.0;
const double variance = (stepIndices.size() * stepIndices.size() - 1) / 12.0;
const double expectedValue = double(stepIndices.size() - 1) / 2.0;
const double variance = double(stepIndices.size() * stepIndices.size() - 1) / 12.0;
BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);

View File

@ -218,7 +218,7 @@ BOOST_AUTO_TEST_CASE(materialise_should_return_random_values_with_equal_probabil
vector<double> bernoulliTrials(collectionSize);
for (size_t i = 0; i < collectionSize; ++i)
bernoulliTrials[i] = indices.count(i);
bernoulliTrials[i] = double(indices.count(i));
BOOST_TEST(abs(mean(bernoulliTrials) - expectedValue) < expectedValue * relativeTolerance);
BOOST_TEST(abs(meanSquaredError(bernoulliTrials, expectedValue) - variance) < variance * relativeTolerance);

View File

@ -95,7 +95,7 @@ BOOST_AUTO_TEST_CASE(uniformInt_returns_different_values_when_called_multiple_ti
constexpr double expectedValue = (minValue + maxValue) / 2.0;
constexpr double variance = ((maxValue - minValue + 1) * (maxValue - minValue + 1) - 1) / 12.0;
vector<uint32_t> samples;
vector<size_t> samples;
for (uint32_t i = 0; i < numSamples; ++i)
samples.push_back(SimulationRNG::uniformInt(minValue, maxValue));
@ -110,21 +110,21 @@ BOOST_AUTO_TEST_CASE(uniformInt_can_be_reset)
constexpr uint32_t maxValue = 80;
SimulationRNG::reset(1);
vector<uint32_t> samples1;
vector<size_t> samples1;
for (uint32_t i = 0; i < numSamples; ++i)
samples1.push_back(SimulationRNG::uniformInt(minValue, maxValue));
vector<uint32_t> samples2;
vector<size_t> samples2;
for (uint32_t i = 0; i < numSamples; ++i)
samples2.push_back(SimulationRNG::uniformInt(minValue, maxValue));
SimulationRNG::reset(1);
vector<uint32_t> samples3;
vector<size_t> samples3;
for (uint32_t i = 0; i < numSamples; ++i)
samples3.push_back(SimulationRNG::uniformInt(minValue, maxValue));
SimulationRNG::reset(2);
vector<uint32_t> samples4;
vector<size_t> samples4;
for (uint32_t i = 0; i < numSamples; ++i)
samples4.push_back(SimulationRNG::uniformInt(minValue, maxValue));
@ -148,7 +148,7 @@ BOOST_AUTO_TEST_CASE(binomialInt_should_produce_samples_with_right_expected_valu
constexpr double expectedValue = numTrials * successProbability;
constexpr double variance = numTrials * successProbability * (1 - successProbability);
vector<uint32_t> samples;
vector<size_t> samples;
for (uint32_t i = 0; i < numSamples; ++i)
samples.push_back(SimulationRNG::binomialInt(numTrials, successProbability));
@ -163,21 +163,21 @@ BOOST_AUTO_TEST_CASE(binomialInt_can_be_reset)
constexpr double successProbability = 0.6;
SimulationRNG::reset(1);
vector<uint32_t> samples1;
vector<size_t> samples1;
for (uint32_t i = 0; i < numSamples; ++i)
samples1.push_back(SimulationRNG::binomialInt(numTrials, successProbability));
vector<uint32_t> samples2;
vector<size_t> samples2;
for (uint32_t i = 0; i < numSamples; ++i)
samples2.push_back(SimulationRNG::binomialInt(numTrials, successProbability));
SimulationRNG::reset(1);
vector<uint32_t> samples3;
vector<size_t> samples3;
for (uint32_t i = 0; i < numSamples; ++i)
samples3.push_back(SimulationRNG::binomialInt(numTrials, successProbability));
SimulationRNG::reset(2);
vector<uint32_t> samples4;
vector<size_t> samples4;
for (uint32_t i = 0; i < numSamples; ++i)
samples4.push_back(SimulationRNG::binomialInt(numTrials, successProbability));

View File

@ -158,9 +158,9 @@ double mean(std::vector<T> const& _samples)
double sum = 0;
for (T const& sample: _samples)
sum += static_cast<double>(sample);
sum += double(sample);
return sum / _samples.size();
return sum / double(_samples.size());
}
/// Calculates the sum of squared differences between @a _expectedValue and the values of a series
@ -179,9 +179,9 @@ double meanSquaredError(std::vector<T> const& _samples, double _expectedValue)
double sumOfSquaredDifferences = 0;
for (T const& sample: _samples)
sumOfSquaredDifferences += (sample - _expectedValue) * (sample - _expectedValue);
sumOfSquaredDifferences += (double(sample) - _expectedValue) * (double(sample) - _expectedValue);
return sumOfSquaredDifferences / _samples.size();
return sumOfSquaredDifferences / double(_samples.size());
}
}

View File

@ -62,16 +62,16 @@ size_t ProgramSize::evaluate(Chromosome const& _chromosome)
size_t RelativeProgramSize::evaluate(Chromosome const& _chromosome)
{
size_t const scalingFactor = pow(10, m_fixedPointPrecision);
double const scalingFactor = pow(10, m_fixedPointPrecision);
size_t unoptimisedSize = optimisedProgram(Chromosome("")).codeSize(codeWeights());
if (unoptimisedSize == 0)
return scalingFactor;
return static_cast<size_t>(scalingFactor);
size_t optimisedSize = optimisedProgram(_chromosome).codeSize(codeWeights());
return static_cast<size_t>(round(
static_cast<double>(optimisedSize) / unoptimisedSize * scalingFactor
double(optimisedSize) / double(unoptimisedSize) * scalingFactor
));
}

View File

@ -171,7 +171,7 @@ function<Crossover> phaser::fixedPointCrossover(double _crossoverPoint)
return [=](Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t minLength = min(_chromosome1.length(), _chromosome2.length());
size_t concretePoint = static_cast<size_t>(round(minLength * _crossoverPoint));
size_t concretePoint = static_cast<size_t>(round(double(minLength) * _crossoverPoint));
return get<0>(fixedPointSwap(_chromosome1, _chromosome2, concretePoint));
};

View File

@ -31,7 +31,7 @@ vector<tuple<size_t, size_t>> RandomPairSelection::materialise(size_t _poolSize)
if (_poolSize < 2)
return {};
auto count = static_cast<size_t>(round(_poolSize * m_selectionSize));
auto count = static_cast<size_t>(round(double(_poolSize) * m_selectionSize));
vector<tuple<size_t, size_t>> selection;
for (size_t i = 0; i < count; ++i)
@ -94,7 +94,7 @@ vector<tuple<size_t, size_t>> PairMosaicSelection::materialise(size_t _poolSize)
if (_poolSize < 2)
return {};
size_t count = static_cast<size_t>(round(_poolSize * m_selectionSize));
size_t count = static_cast<size_t>(round(double(_poolSize) * m_selectionSize));
vector<tuple<size_t, size_t>> selection;
for (size_t i = 0; i < count; ++i)

View File

@ -141,7 +141,7 @@ unique_ptr<GeneticAlgorithm> GeneticAlgorithmFactory::build(
{
case Algorithm::Random:
{
double elitePoolSize = 1.0 / _populationSize;
double elitePoolSize = 1.0 / double(_populationSize);
if (_options.randomElitePoolSize.has_value())
elitePoolSize = _options.randomElitePoolSize.value();
@ -154,7 +154,7 @@ unique_ptr<GeneticAlgorithm> GeneticAlgorithmFactory::build(
}
case Algorithm::GEWEP:
{
double percentGenesToRandomise = 1.0 / _options.maxChromosomeLength;
double percentGenesToRandomise = 1.0 / double(_options.maxChromosomeLength);
double percentGenesToAddOrDelete = percentGenesToRandomise;
if (_options.gewepGenesToRandomise.has_value())
@ -421,8 +421,8 @@ void Phaser::main(int _argc, char** _argv)
Phaser::CommandLineDescription Phaser::buildCommandLineDescription()
{
size_t const lineLength = po::options_description::m_default_line_length;
size_t const minDescriptionLength = lineLength - 23;
unsigned const lineLength = po::options_description::m_default_line_length;
unsigned const minDescriptionLength = lineLength - 23;
po::options_description keywordDescription(
"yul-phaser, a tool for finding the best sequence of Yul optimisation phases.\n"

View File

@ -28,8 +28,8 @@ using namespace solidity::phaser;
vector<size_t> RangeSelection::materialise(size_t _poolSize) const
{
size_t beginIndex = static_cast<size_t>(round(_poolSize * m_startPercent));
size_t endIndex = static_cast<size_t>(round(_poolSize * m_endPercent));
size_t beginIndex = static_cast<size_t>(round(double(_poolSize) * m_startPercent));
size_t endIndex = static_cast<size_t>(round(double(_poolSize) * m_endPercent));
vector<size_t> selection;
for (size_t i = beginIndex; i < endIndex; ++i)
@ -40,7 +40,7 @@ vector<size_t> RangeSelection::materialise(size_t _poolSize) const
vector<size_t> MosaicSelection::materialise(size_t _poolSize) const
{
size_t count = static_cast<size_t>(round(_poolSize * m_selectionSize));
size_t count = static_cast<size_t>(round(double(_poolSize) * m_selectionSize));
vector<size_t> selection;
for (size_t i = 0; i < count; ++i)
@ -51,7 +51,7 @@ vector<size_t> MosaicSelection::materialise(size_t _poolSize) const
vector<size_t> RandomSelection::materialise(size_t _poolSize) const
{
size_t count = static_cast<size_t>(round(_poolSize * m_selectionSize));
size_t count = static_cast<size_t>(round(double(_poolSize) * m_selectionSize));
vector<size_t> selection;
for (size_t i = 0; i < count; ++i)

View File

@ -62,5 +62,5 @@ uint32_t SimulationRNG::generateSeed()
// This is not a secure way to seed the generator but it's good enough for simulation purposes.
// The only thing that matters for us is that the sequence is different on each run and that
// it fits the expected distribution. It does not have to be 100% unpredictable.
return time(nullptr);
return static_cast<uint32_t>(time(nullptr));
}