Merge pull request #9118 from ethereum/develop

Merge develop into breaking.
This commit is contained in:
chriseth 2020-06-04 10:18:46 +02:00 committed by GitHub
commit 259292c884
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 436 additions and 235 deletions

View File

@ -44,6 +44,7 @@ Bugfixes:
* Type Checker: Fix internal compiler error when trying to decode too large static arrays.
* Type Checker: Fix wrong compiler error when referencing an overridden function without calling it.
* Type Checker: Fix internal compiler error when forward referencing non-literal constants from inline assembly.
* Type Checker: Disallow usage of override with non-public state variables.
* NatSpec: DocString block is terminated when encountering an empty line.
* Scanner: Fix bug when two empty NatSpec comments lead to scanning past EOL.
* Code Generator: Trigger proper unimplemented errors on certain array copy operations.

View File

@ -41,7 +41,7 @@ using namespace solidity::util;
AssemblyItem const& Assembly::append(AssemblyItem const& _i)
{
assertThrow(m_deposit >= 0, AssemblyException, "Stack underflow.");
m_deposit += _i.deposit();
m_deposit += static_cast<int>(_i.deposit());
m_items.emplace_back(_i);
if (!m_items.back().location().isValid() && m_currentSourceLocation.isValid())
m_items.back().setLocation(m_currentSourceLocation);
@ -77,10 +77,10 @@ string locationFromSources(StringMap const& _sourceCodes, SourceLocation const&
return "";
string const& source = it->second;
if (size_t(_location.start) >= source.size())
if (static_cast<size_t>(_location.start) >= source.size())
return "";
string cut = source.substr(_location.start, _location.end - _location.start);
string cut = source.substr(static_cast<size_t>(_location.start), static_cast<size_t>(_location.end - _location.start));
auto newLinePos = cut.find_first_of("\n");
if (newLinePos != string::npos)
cut = cut.substr(0, newLinePos) + "...";
@ -106,7 +106,7 @@ public:
if (!(
_item.canBeFunctional() &&
_item.returnValues() <= 1 &&
_item.arguments() <= int(m_pending.size())
_item.arguments() <= m_pending.size()
))
{
flush();
@ -117,7 +117,7 @@ public:
if (_item.arguments() > 0)
{
expression += "(";
for (int i = 0; i < _item.arguments(); ++i)
for (size_t i = 0; i < _item.arguments(); ++i)
{
expression += m_pending.back();
m_pending.pop_back();
@ -225,12 +225,12 @@ Json::Value Assembly::assemblyJSON(map<string, unsigned> const& _sourceIndices)
Json::Value& collection = root[".code"] = Json::arrayValue;
for (AssemblyItem const& i: m_items)
{
unsigned sourceIndex = unsigned(-1);
int sourceIndex = -1;
if (i.location().source)
{
auto iter = _sourceIndices.find(i.location().source->name());
if (iter != _sourceIndices.end())
sourceIndex = iter->second;
sourceIndex = static_cast<int>(iter->second);
}
switch (i.type())
@ -340,7 +340,7 @@ AssemblyItem Assembly::namedTag(string const& _name)
{
assertThrow(!_name.empty(), AssemblyException, "Empty named tag.");
if (!m_namedTags.count(_name))
m_namedTags[_name] = size_t(newTag().data());
m_namedTags[_name] = static_cast<size_t>(newTag().data());
return AssemblyItem{Tag, m_namedTags.at(_name)};
}
@ -441,7 +441,7 @@ map<u256, u256> Assembly::optimiseInternal(
for (auto const& replacement: deduplicator.replacedTags())
{
assertThrow(
replacement.first <= size_t(-1) && replacement.second <= size_t(-1),
replacement.first <= numeric_limits<size_t>::max() && replacement.second <= numeric_limits<size_t>::max(),
OptimizerException,
"Invalid tag replacement."
);
@ -451,8 +451,8 @@ map<u256, u256> Assembly::optimiseInternal(
"Replacement already known."
);
tagReplacements[replacement.first] = replacement.second;
if (_tagsReferencedFromOutside.erase(size_t(replacement.first)))
_tagsReferencedFromOutside.insert(size_t(replacement.second));
if (_tagsReferencedFromOutside.erase(static_cast<size_t>(replacement.first)))
_tagsReferencedFromOutside.insert(static_cast<size_t>(replacement.second));
}
count++;
}
@ -479,7 +479,7 @@ map<u256, u256> Assembly::optimiseInternal(
try
{
optimisedChunk = eliminator.getOptimizedItems();
shouldReplace = (optimisedChunk.size() < size_t(iter - orig));
shouldReplace = (optimisedChunk.size() < static_cast<size_t>(iter - orig));
}
catch (StackTooDeepException const&)
{
@ -544,7 +544,7 @@ LinkerObject const& Assembly::assemble() const
immutableReferencesBySub = linkerObject.immutableReferences;
}
for (size_t tagPos: sub->m_tagPositionsInBytecode)
if (tagPos != size_t(-1) && tagPos > subTagSize)
if (tagPos != numeric_limits<size_t>::max() && tagPos > subTagSize)
subTagSize = tagPos;
}
@ -567,7 +567,7 @@ LinkerObject const& Assembly::assemble() const
);
size_t bytesRequiredForCode = bytesRequired(subTagSize);
m_tagPositionsInBytecode = vector<size_t>(m_usedTags, -1);
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;
@ -586,7 +586,7 @@ LinkerObject const& Assembly::assemble() const
for (AssemblyItem const& i: m_items)
{
// store position of the invalid jump destination
if (i.type() != Tag && m_tagPositionsInBytecode[0] == size_t(-1))
if (i.type() != Tag && m_tagPositionsInBytecode[0] == numeric_limits<size_t>::max())
m_tagPositionsInBytecode[0] = ret.bytecode.size();
switch (i.type())
@ -629,15 +629,15 @@ LinkerObject const& Assembly::assemble() const
ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef);
break;
case PushSub:
assertThrow(i.data() <= size_t(-1), AssemblyException, "");
assertThrow(i.data() <= numeric_limits<size_t>::max(), AssemblyException, "");
ret.bytecode.push_back(dataRefPush);
subRef.insert(make_pair(size_t(i.data()), ret.bytecode.size()));
subRef.insert(make_pair(static_cast<size_t>(i.data()), ret.bytecode.size()));
ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef);
break;
case PushSubSize:
{
assertThrow(i.data() <= size_t(-1), AssemblyException, "");
auto s = m_subs.at(size_t(i.data()))->assemble().bytecode.size();
assertThrow(i.data() <= numeric_limits<size_t>::max(), AssemblyException, "");
auto s = m_subs.at(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)Instruction::PUSH1 - 1 + b);
@ -683,10 +683,10 @@ LinkerObject const& Assembly::assemble() const
break;
case Tag:
assertThrow(i.data() != 0, AssemblyException, "Invalid tag position.");
assertThrow(i.splitForeignPushTag().first == size_t(-1), AssemblyException, "Foreign tag.");
assertThrow(i.splitForeignPushTag().first == numeric_limits<size_t>::max(), AssemblyException, "Foreign tag.");
assertThrow(ret.bytecode.size() < 0xffffffffL, AssemblyException, "Tag too large.");
assertThrow(m_tagPositionsInBytecode[size_t(i.data())] == size_t(-1), AssemblyException, "Duplicate tag position.");
m_tagPositionsInBytecode[size_t(i.data())] = ret.bytecode.size();
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);
break;
default:
@ -722,14 +722,14 @@ LinkerObject const& Assembly::assemble() const
size_t subId;
size_t tagId;
tie(subId, tagId) = i.second;
assertThrow(subId == size_t(-1) || subId < m_subs.size(), AssemblyException, "Invalid sub id");
assertThrow(subId == numeric_limits<size_t>::max() || subId < m_subs.size(), AssemblyException, "Invalid sub id");
std::vector<size_t> const& tagPositions =
subId == size_t(-1) ?
subId == numeric_limits<size_t>::max() ?
m_tagPositionsInBytecode :
m_subs[subId]->m_tagPositionsInBytecode;
assertThrow(tagId < tagPositions.size(), AssemblyException, "Reference to non-existing tag.");
size_t pos = tagPositions[tagId];
assertThrow(pos != size_t(-1), AssemblyException, "Reference to tag without position.");
assertThrow(pos != numeric_limits<size_t>::max(), AssemblyException, "Reference to tag without position.");
assertThrow(util::bytesRequired(pos) <= bytesPerTag, AssemblyException, "Tag too large for reserved space.");
bytesRef r(ret.bytecode.data() + i.first, bytesPerTag);
toBigEndian(pos, r);

View File

@ -34,7 +34,7 @@ AssemblyItem AssemblyItem::toSubAssemblyTag(size_t _subId) const
{
assertThrow(data() < (u256(1) << 64), util::Exception, "Tag already has subassembly set.");
assertThrow(m_type == PushTag || m_type == Tag, util::Exception, "");
size_t tag = size_t(u256(data()) & 0xffffffffffffffffULL);
auto tag = static_cast<size_t>(u256(data()) & 0xffffffffffffffffULL);
AssemblyItem r = *this;
r.m_type = PushTag;
r.setPushTagSubIdAndTag(_subId, tag);
@ -45,8 +45,8 @@ pair<size_t, size_t> AssemblyItem::splitForeignPushTag() const
{
assertThrow(m_type == PushTag || m_type == Tag, util::Exception, "");
u256 combined = u256(data());
size_t subId = size_t((combined >> 64) - 1);
size_t tag = size_t(combined & 0xffffffffffffffffULL);
size_t subId = static_cast<size_t>((combined >> 64) - 1);
size_t tag = static_cast<size_t>(combined & 0xffffffffffffffffULL);
return make_pair(subId, tag);
}
@ -54,7 +54,7 @@ void AssemblyItem::setPushTagSubIdAndTag(size_t _subId, size_t _tag)
{
assertThrow(m_type == PushTag || m_type == Tag, util::Exception, "");
u256 data = _tag;
if (_subId != size_t(-1))
if (_subId != numeric_limits<size_t>::max())
data |= (u256(_subId) + 1) << 64;
setData(data);
}
@ -93,22 +93,22 @@ unsigned AssemblyItem::bytesRequired(unsigned _addressLength) const
assertThrow(false, InvalidOpcode, "");
}
int AssemblyItem::arguments() const
size_t AssemblyItem::arguments() const
{
if (type() == Operation)
return instructionInfo(instruction()).args;
return static_cast<size_t>(instructionInfo(instruction()).args);
else if (type() == AssignImmutable)
return 1;
else
return 0;
}
int AssemblyItem::returnValues() const
size_t AssemblyItem::returnValues() const
{
switch (m_type)
{
case Operation:
return instructionInfo(instruction()).ret;
return static_cast<size_t>(instructionInfo(instruction()).ret);
case Push:
case PushString:
case PushTag:
@ -193,7 +193,7 @@ string AssemblyItem::toAssemblyText() const
size_t sub{0};
size_t tag{0};
tie(sub, tag) = splitForeignPushTag();
if (sub == size_t(-1))
if (sub == numeric_limits<size_t>::max())
text = string("tag_") + to_string(tag);
else
text = string("tag_") + to_string(sub) + "_" + to_string(tag);
@ -201,16 +201,16 @@ string AssemblyItem::toAssemblyText() const
}
case Tag:
assertThrow(data() < 0x10000, AssemblyException, "Declaration of sub-assembly tag.");
text = string("tag_") + to_string(size_t(data())) + ":";
text = string("tag_") + to_string(static_cast<size_t>(data())) + ":";
break;
case PushData:
text = string("data_") + util::toHex(data());
break;
case PushSub:
text = string("dataOffset(sub_") + to_string(size_t(data())) + ")";
text = string("dataOffset(sub_") + to_string(static_cast<size_t>(data())) + ")";
break;
case PushSubSize:
text = string("dataSize(sub_") + to_string(size_t(data())) + ")";
text = string("dataSize(sub_") + to_string(static_cast<size_t>(data())) + ")";
break;
case PushProgramSize:
text = string("bytecodeSize");
@ -262,7 +262,7 @@ ostream& solidity::evmasm::operator<<(ostream& _out, AssemblyItem const& _item)
case PushTag:
{
size_t subId = _item.splitForeignPushTag().first;
if (subId == size_t(-1))
if (subId == numeric_limits<size_t>::max())
_out << " PushTag " << _item.splitForeignPushTag().second;
else
_out << " PushTag " << subId << ":" << _item.splitForeignPushTag().second;
@ -272,13 +272,13 @@ ostream& solidity::evmasm::operator<<(ostream& _out, AssemblyItem const& _item)
_out << " Tag " << _item.data();
break;
case PushData:
_out << " PushData " << hex << (unsigned)_item.data() << dec;
_out << " PushData " << hex << static_cast<unsigned>(_item.data()) << dec;
break;
case PushSub:
_out << " PushSub " << hex << size_t(_item.data()) << dec;
_out << " PushSub " << hex << static_cast<size_t>(_item.data()) << dec;
break;
case PushSubSize:
_out << " PushSubSize " << hex << size_t(_item.data()) << dec;
_out << " PushSubSize " << hex << static_cast<size_t>(_item.data()) << dec;
break;
case PushProgramSize:
_out << " PushProgramSize";
@ -317,7 +317,7 @@ std::string AssemblyItem::computeSourceMapping(
int prevStart = -1;
int prevLength = -1;
int prevSourceIndex = -1;
size_t prevModifierDepth = -1;
int prevModifierDepth = -1;
char prevJump = 0;
for (auto const& item: _items)
{
@ -328,14 +328,14 @@ std::string AssemblyItem::computeSourceMapping(
int length = location.start != -1 && location.end != -1 ? location.end - location.start : -1;
int sourceIndex =
location.source && _sourceIndicesMap.count(location.source->name()) ?
_sourceIndicesMap.at(location.source->name()) :
static_cast<int>(_sourceIndicesMap.at(location.source->name())) :
-1;
char jump = '-';
if (item.getJumpType() == evmasm::AssemblyItem::JumpType::IntoFunction)
jump = 'i';
else if (item.getJumpType() == evmasm::AssemblyItem::JumpType::OutOfFunction)
jump = 'o';
size_t modifierDepth = item.m_modifierDepth;
int modifierDepth = static_cast<int>(item.m_modifierDepth);
unsigned components = 5;
if (modifierDepth == prevModifierDepth)

View File

@ -134,9 +134,9 @@ public:
/// @returns an upper bound for the number of bytes required by this item, assuming that
/// the value of a jump tag takes @a _addressLength bytes.
unsigned bytesRequired(unsigned _addressLength) const;
int arguments() const;
int returnValues() const;
int deposit() const { return returnValues() - arguments(); }
size_t arguments() const;
size_t returnValues() const;
size_t deposit() const { return returnValues() - arguments(); }
/// @returns true if the assembly item can be used in a functional context.
bool canBeFunctional() const;

View File

@ -63,8 +63,9 @@ bool BlockDeduplicator::deduplicate()
if (_j < m_items.size() && m_items.at(_j).type() == Tag)
pushSecondTag = m_items.at(_j).pushTag();
BlockIterator first{m_items.begin() + _i, m_items.end(), &pushFirstTag, &pushSelf};
BlockIterator second{m_items.begin() + _j, m_items.end(), &pushSecondTag, &pushSelf};
using diff_type = BlockIterator::difference_type;
BlockIterator first{m_items.begin() + diff_type(_i), m_items.end(), &pushFirstTag, &pushSelf};
BlockIterator second{m_items.begin() + diff_type(_j), m_items.end(), &pushSecondTag, &pushSelf};
BlockIterator end{m_items.end(), m_items.end()};
if (first != end && (*first).type() == Tag)
@ -120,7 +121,7 @@ bool BlockDeduplicator::applyTagReplacement(
if (it != _replacements.end())
{
changed = true;
item.setPushTagSubIdAndTag(subId, size_t(it->second));
item.setPushTagSubIdAndTag(subId, static_cast<size_t>(it->second));
}
}
return changed;

View File

@ -386,7 +386,11 @@ void CSECodeGenerator::generateClassElement(Id _c, bool _allowSequenced)
"Opcodes with more than two arguments not implemented yet."
);
for (size_t i = 0; i < arguments.size(); ++i)
assertThrow(m_stack[m_stackHeight - i] == arguments[i], OptimizerException, "Expected arguments not present." );
assertThrow(
m_stack[m_stackHeight - static_cast<int>(i)] == arguments[i],
OptimizerException,
"Expected arguments not present."
);
while (SemanticInformation::isCommutativeOperation(*expr.item) &&
!m_generatedItems.empty() &&
@ -395,8 +399,8 @@ void CSECodeGenerator::generateClassElement(Id _c, bool _allowSequenced)
appendOrRemoveSwap(m_stackHeight - 1, itemLocation);
for (size_t i = 0; i < arguments.size(); ++i)
{
m_classPositions[m_stack[m_stackHeight - i]].erase(m_stackHeight - i);
m_stack.erase(m_stackHeight - i);
m_classPositions[m_stack[m_stackHeight - static_cast<int>(i)]].erase(m_stackHeight - static_cast<int>(i));
m_stack.erase(m_stackHeight - static_cast<int>(i));
}
appendItem(*expr.item);
if (expr.item->type() != Operation || instructionInfo(expr.item->instruction()).ret == 1)
@ -467,7 +471,7 @@ void CSECodeGenerator::appendDup(int _fromPosition, SourceLocation const& _locat
int instructionNum = 1 + m_stackHeight - _fromPosition;
assertThrow(instructionNum <= 16, StackTooDeepException, "Stack too deep, try removing local variables.");
assertThrow(1 <= instructionNum, OptimizerException, "Invalid stack access.");
appendItem(AssemblyItem(dupInstruction(instructionNum), _location));
appendItem(AssemblyItem(dupInstruction(static_cast<unsigned>(instructionNum)), _location));
m_stack[m_stackHeight] = m_stack[_fromPosition];
m_classPositions[m_stack[m_stackHeight]].insert(m_stackHeight);
}
@ -480,7 +484,7 @@ void CSECodeGenerator::appendOrRemoveSwap(int _fromPosition, SourceLocation cons
int instructionNum = m_stackHeight - _fromPosition;
assertThrow(instructionNum <= 16, StackTooDeepException, "Stack too deep, try removing local variables.");
assertThrow(1 <= instructionNum, OptimizerException, "Invalid stack access.");
appendItem(AssemblyItem(swapInstruction(instructionNum), _location));
appendItem(AssemblyItem(swapInstruction(static_cast<unsigned>(instructionNum)), _location));
if (m_stack[m_stackHeight] != m_stack[_fromPosition])
{
@ -502,5 +506,5 @@ void CSECodeGenerator::appendOrRemoveSwap(int _fromPosition, SourceLocation cons
void CSECodeGenerator::appendItem(AssemblyItem const& _item)
{
m_generatedItems.push_back(_item);
m_stackHeight += _item.deposit();
m_stackHeight += static_cast<int>(_item.deposit());
}

View File

@ -262,7 +262,7 @@ bool ComputeMethod::checkRepresentation(u256 const& _value, AssemblyItems const&
{
case Operation:
{
if (stack.size() < size_t(item.arguments()))
if (stack.size() < item.arguments())
return false;
u256* sp = &stack.back();
switch (item.instruction())
@ -320,7 +320,7 @@ bool ComputeMethod::checkRepresentation(u256 const& _value, AssemblyItems const&
bigint ComputeMethod::gasNeeded(AssemblyItems const& _routine) const
{
size_t numExps = count(_routine.begin(), _routine.end(), Instruction::EXP);
auto numExps = static_cast<size_t>(count(_routine.begin(), _routine.end(), Instruction::EXP));
return combineGas(
simpleRunGas(_routine) + numExps * (GasCosts::expGas + GasCosts::expByteGas(m_params.evmVersion)),
// Data gas for routine: Some bytes are zero, but we ignore them.

View File

@ -45,8 +45,8 @@ public:
BlockId() { *this = invalid(); }
explicit BlockId(unsigned _id): m_id(_id) {}
explicit BlockId(u256 const& _id);
static BlockId initial() { return BlockId(-2); }
static BlockId invalid() { return BlockId(-1); }
static BlockId initial() { return BlockId(std::numeric_limits<unsigned>::max() - 1); }
static BlockId invalid() { return BlockId(std::numeric_limits<unsigned>::max()); }
bool operator==(BlockId const& _other) const { return m_id == _other.m_id; }
bool operator!=(BlockId const& _other) const { return m_id != _other.m_id; }

View File

@ -190,7 +190,7 @@ ExpressionClasses::Id ExpressionClasses::tryToSimplify(Expression const& _expr)
_expr.item->type() != Operation ||
!SemanticInformation::isDeterministic(*_expr.item)
)
return -1;
return numeric_limits<unsigned>::max();
if (auto match = rules.findFirstMatch(_expr, *this))
{
@ -208,7 +208,7 @@ ExpressionClasses::Id ExpressionClasses::tryToSimplify(Expression const& _expr)
return rebuildExpression(ExpressionTemplate(match->action(), _expr.item->location()));
}
return -1;
return numeric_limits<unsigned>::max();
}
ExpressionClasses::Id ExpressionClasses::rebuildExpression(ExpressionTemplate const& _template)

View File

@ -330,8 +330,8 @@ void solidity::evmasm::eachInstruction(
{
for (auto it = _mem.begin(); it < _mem.end(); ++it)
{
Instruction instr = Instruction(*it);
size_t additional = 0;
auto instr = Instruction(*it);
int additional = 0;
if (isValidInstruction(instr))
additional = instructionInfo(instr).additional;
@ -357,7 +357,7 @@ string solidity::evmasm::disassemble(bytes const& _mem)
stringstream ret;
eachInstruction(_mem, [&](Instruction _instr, u256 const& _data) {
if (!isValidInstruction(_instr))
ret << "0x" << std::uppercase << std::hex << int(_instr) << " ";
ret << "0x" << std::uppercase << std::hex << static_cast<int>(_instr) << " ";
else
{
InstructionInfo info = instructionInfo(_instr);

View File

@ -30,7 +30,7 @@ using namespace solidity::evmasm;
bool JumpdestRemover::optimise(set<size_t> const& _tagsReferencedFromOutside)
{
set<size_t> references{referencedTags(m_items, -1)};
set<size_t> references{referencedTags(m_items, numeric_limits<size_t>::max())};
references.insert(_tagsReferencedFromOutside.begin(), _tagsReferencedFromOutside.end());
size_t initialSize = m_items.size();
@ -43,7 +43,7 @@ bool JumpdestRemover::optimise(set<size_t> const& _tagsReferencedFromOutside)
if (_item.type() != Tag)
return false;
auto asmIdAndTag = _item.splitForeignPushTag();
assertThrow(asmIdAndTag.first == size_t(-1), OptimizerException, "Sub-assembly tag used as label.");
assertThrow(asmIdAndTag.first == numeric_limits<size_t>::max(), OptimizerException, "Sub-assembly tag used as label.");
size_t tag = asmIdAndTag.second;
return !references.count(tag);
}

View File

@ -41,7 +41,7 @@ ostream& KnownState::stream(ostream& _out) const
if (!expr.item)
_out << " no item";
else if (expr.item->type() == UndefinedItem)
_out << " unknown " << int(expr.item->data());
_out << " unknown " << static_cast<int>(expr.item->data());
else
_out << *expr.item;
if (expr.sequenceNumber)
@ -112,21 +112,21 @@ KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool
setStackElement(
m_stackHeight + 1,
stackElement(
m_stackHeight - int(instruction) + int(Instruction::DUP1),
m_stackHeight - static_cast<int>(instruction) + static_cast<int>(Instruction::DUP1),
_item.location()
)
);
else if (SemanticInformation::isSwapInstruction(_item))
swapStackElements(
m_stackHeight,
m_stackHeight - 1 - int(instruction) + int(Instruction::SWAP1),
m_stackHeight - 1 - static_cast<int>(instruction) + static_cast<int>(Instruction::SWAP1),
_item.location()
);
else if (instruction != Instruction::POP)
{
vector<Id> arguments(info.args);
for (int i = 0; i < info.args; ++i)
arguments[i] = stackElement(m_stackHeight - i, _item.location());
vector<Id> arguments(static_cast<size_t>(info.args));
for (size_t i = 0; i < static_cast<size_t>(info.args); ++i)
arguments[i] = stackElement(m_stackHeight - static_cast<int>(i), _item.location());
switch (_item.instruction())
{
case Instruction::SSTORE:
@ -134,7 +134,7 @@ KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool
break;
case Instruction::SLOAD:
setStackElement(
m_stackHeight + _item.deposit(),
m_stackHeight + static_cast<int>(_item.deposit()),
loadFromStorage(arguments[0], _item.location())
);
break;
@ -143,13 +143,13 @@ KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool
break;
case Instruction::MLOAD:
setStackElement(
m_stackHeight + _item.deposit(),
m_stackHeight + static_cast<int>(_item.deposit()),
loadFromMemory(arguments[0], _item.location())
);
break;
case Instruction::KECCAK256:
setStackElement(
m_stackHeight + _item.deposit(),
m_stackHeight + static_cast<int>(_item.deposit()),
applyKeccak256(arguments.at(0), arguments.at(1), _item.location())
);
break;
@ -167,16 +167,16 @@ KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool
assertThrow(info.ret <= 1, InvalidDeposit, "");
if (info.ret == 1)
setStackElement(
m_stackHeight + _item.deposit(),
m_stackHeight + static_cast<int>(_item.deposit()),
m_expressionClasses->find(_item, arguments, _copyItem)
);
}
}
m_stackElements.erase(
m_stackElements.upper_bound(m_stackHeight + _item.deposit()),
m_stackElements.upper_bound(m_stackHeight + static_cast<int>(_item.deposit())),
m_stackElements.end()
);
m_stackHeight += _item.deposit();
m_stackHeight += static_cast<int>(_item.deposit());
}
return op;
}
@ -388,7 +388,7 @@ KnownState::Id KnownState::applyKeccak256(
bytes data;
for (Id a: arguments)
data += util::toBigEndian(*m_expressionClasses->knownConstant(a));
data.resize(size_t(*l));
data.resize(static_cast<size_t>(*l));
v = m_expressionClasses->find(AssemblyItem(u256(util::keccak256(data)), _location));
}
else

View File

@ -40,7 +40,7 @@ void LinkerObject::link(map<string, h160> const& _libraryAddresses)
std::map<size_t, std::string> remainingRefs;
for (auto const& linkRef: linkReferences)
if (h160 const* address = matchLibrary(linkRef.second, _libraryAddresses))
copy(address->data(), address->data() + 20, bytecode.begin() + linkRef.first);
copy(address->data(), address->data() + 20, bytecode.begin() + vector<uint8_t>::difference_type(linkRef.first));
else
remainingRefs.insert(linkRef);
linkReferences.swap(remainingRefs);

View File

@ -84,7 +84,7 @@ struct SimplePeepholeOptimizerMethod
{
if (
_state.i + WindowSize <= _state.items.size() &&
ApplyRule<Method, WindowSize>::applyRule(_state.items.begin() + _state.i, _state.out)
ApplyRule<Method, WindowSize>::applyRule(_state.items.begin() + static_cast<ptrdiff_t>(_state.i), _state.out)
)
{
_state.i += WindowSize;
@ -303,7 +303,7 @@ struct UnreachableCode
{
static bool apply(OptimiserState& _state)
{
auto it = _state.items.begin() + _state.i;
auto it = _state.items.begin() + static_cast<ptrdiff_t>(_state.i);
auto end = _state.items.end();
if (it == end)
return false;
@ -317,13 +317,13 @@ struct UnreachableCode
)
return false;
size_t i = 1;
ptrdiff_t i = 1;
while (it + i != end && it[i].type() != Tag)
i++;
if (i > 1)
{
*_state.out = it[0];
_state.i += i;
_state.i += static_cast<size_t>(i);
return true;
}
else
@ -345,7 +345,7 @@ void applyMethods(OptimiserState& _state, Method, OtherMethods... _other)
size_t numberOfPops(AssemblyItems const& _items)
{
return std::count(_items.begin(), _items.end(), Instruction::POP);
return static_cast<size_t>(std::count(_items.begin(), _items.end(), Instruction::POP));
}
}

View File

@ -85,7 +85,7 @@ string CharStream::lineAtPosition(int _position) const
{
// if _position points to \n, it returns the line before the \n
using size_type = string::size_type;
size_type searchStart = min<size_type>(m_source.size(), _position);
size_type searchStart = min<size_type>(m_source.size(), size_type(_position));
if (searchStart > 0)
searchStart--;
size_type lineStart = m_source.rfind('\n', searchStart);
@ -105,8 +105,9 @@ string CharStream::lineAtPosition(int _position) const
tuple<int, int> CharStream::translatePositionToLineColumn(int _position) const
{
using size_type = string::size_type;
size_type searchPosition = min<size_type>(m_source.size(), _position);
int lineNumber = count(m_source.begin(), m_source.begin() + searchPosition, '\n');
using diff_type = string::difference_type;
size_type searchPosition = min<size_type>(m_source.size(), size_type(_position));
int lineNumber = count(m_source.begin(), m_source.begin() + diff_type(searchPosition), '\n');
size_type lineStart;
if (searchPosition == 0)
lineStart = 0;

View File

@ -72,7 +72,7 @@ public:
explicit CharStream(std::string _source, std::string name):
m_source(std::move(_source)), m_name(std::move(name)) {}
int position() const { return m_position; }
size_t position() const { return m_position; }
bool isPastEndOfInput(size_t _charsForward = 0) const { return (m_position + _charsForward) >= m_source.size(); }
char get(size_t _charsForward = 0) const { return m_source[m_position + _charsForward]; }

View File

@ -106,7 +106,7 @@ void ParserBase::expectTokenOrConsumeUntil(Token _value, string const& _currentN
if (m_scanner->currentToken() == Token::EOS)
{
// rollback to where the token started, and raise exception to be caught at a higher level.
m_scanner->setPosition(startPosition);
m_scanner->setPosition(static_cast<size_t>(startPosition));
m_inParserRecovery = true;
fatalParserError(1957_error, errorLoc, msg);
}

View File

@ -171,7 +171,7 @@ void Scanner::supportPeriodInIdentifier(bool _value)
bool Scanner::scanHexByte(char& o_scannedByte)
{
char x = 0;
for (int i = 0; i < 2; i++)
for (size_t i = 0; i < 2; i++)
{
int d = hexValue(m_char);
if (d < 0)
@ -189,7 +189,7 @@ bool Scanner::scanHexByte(char& o_scannedByte)
std::optional<unsigned> Scanner::scanUnicode()
{
unsigned x = 0;
for (int i = 0; i < 4; i++)
for (size_t i = 0; i < 4; i++)
{
int d = hexValue(m_char);
if (d < 0)
@ -197,7 +197,7 @@ std::optional<unsigned> Scanner::scanUnicode()
rollback(i);
return {};
}
x = x * 16 + d;
x = x * 16 + static_cast<size_t>(d);
advance();
}
return x;
@ -207,17 +207,17 @@ std::optional<unsigned> Scanner::scanUnicode()
void Scanner::addUnicodeAsUTF8(unsigned codepoint)
{
if (codepoint <= 0x7f)
addLiteralChar(codepoint);
addLiteralChar(char(codepoint));
else if (codepoint <= 0x7ff)
{
addLiteralChar(0xc0 | (codepoint >> 6));
addLiteralChar(0x80 | (codepoint & 0x3f));
addLiteralChar(char(0xc0u | (codepoint >> 6u)));
addLiteralChar(char(0x80u | (codepoint & 0x3fu)));
}
else
{
addLiteralChar(0xe0 | (codepoint >> 12));
addLiteralChar(0x80 | ((codepoint >> 6) & 0x3f));
addLiteralChar(0x80 | (codepoint & 0x3f));
addLiteralChar(char(0xe0u | (codepoint >> 12u)));
addLiteralChar(char(0x80u | ((codepoint >> 6u) & 0x3fu)));
addLiteralChar(char(0x80u | (codepoint & 0x3fu)));
}
}
@ -225,10 +225,10 @@ void Scanner::rescan()
{
size_t rollbackTo = 0;
if (m_skippedComments[Current].literal.empty())
rollbackTo = m_tokens[Current].location.start;
rollbackTo = static_cast<size_t>(m_tokens[Current].location.start);
else
rollbackTo = m_skippedComments[Current].location.start;
m_char = m_source->rollback(size_t(m_source->position()) - rollbackTo);
rollbackTo = static_cast<size_t>(m_skippedComments[Current].location.start);
m_char = m_source->rollback(m_source->position() - rollbackTo);
next();
next();
next();
@ -260,7 +260,7 @@ Token Scanner::selectToken(char _next, Token _then, Token _else)
bool Scanner::skipWhitespace()
{
int const startPosition = sourcePos();
size_t const startPosition = sourcePos();
while (isWhiteSpace(m_char))
advance();
// Return whether or not we skipped any characters.
@ -269,7 +269,7 @@ bool Scanner::skipWhitespace()
bool Scanner::skipWhitespaceExceptUnicodeLinebreak()
{
int const startPosition = sourcePos();
size_t const startPosition = sourcePos();
while (isWhiteSpace(m_char) && !isUnicodeLinebreak())
advance();
// Return whether or not we skipped any characters.
@ -309,10 +309,10 @@ bool Scanner::tryScanEndOfLine()
return false;
}
int Scanner::scanSingleLineDocComment()
size_t Scanner::scanSingleLineDocComment()
{
LiteralScope literal(this, LITERAL_TYPE_COMMENT);
int endPosition = m_source->position();
size_t endPosition = m_source->position();
advance(); //consume the last '/' at ///
skipWhitespaceExceptUnicodeLinebreak();
@ -429,7 +429,7 @@ Token Scanner::scanMultiLineDocComment()
Token Scanner::scanSlash()
{
int firstSlashPosition = sourcePos();
int firstSlashPosition = static_cast<int>(sourcePos());
advance();
if (m_char == '/')
{
@ -441,7 +441,7 @@ Token Scanner::scanSlash()
m_skippedComments[NextNext].location.start = firstSlashPosition;
m_skippedComments[NextNext].location.source = m_source;
m_skippedComments[NextNext].token = Token::CommentLiteral;
m_skippedComments[NextNext].location.end = scanSingleLineDocComment();
m_skippedComments[NextNext].location.end = static_cast<int>(scanSingleLineDocComment());
return Token::Whitespace;
}
else
@ -467,7 +467,7 @@ Token Scanner::scanSlash()
m_skippedComments[NextNext].location.start = firstSlashPosition;
m_skippedComments[NextNext].location.source = m_source;
comment = scanMultiLineDocComment();
m_skippedComments[NextNext].location.end = sourcePos();
m_skippedComments[NextNext].location.end = static_cast<int>(sourcePos());
m_skippedComments[NextNext].token = comment;
if (comment == Token::Illegal)
return Token::Illegal; // error already set
@ -495,7 +495,7 @@ void Scanner::scanToken()
do
{
// Remember the position of the next token
m_tokens[NextNext].location.start = sourcePos();
m_tokens[NextNext].location.start = static_cast<int>(sourcePos());
switch (m_char)
{
case '"':
@ -690,7 +690,7 @@ void Scanner::scanToken()
// whitespace.
}
while (token == Token::Whitespace);
m_tokens[NextNext].location.end = sourcePos();
m_tokens[NextNext].location.end = static_cast<int>(sourcePos());
m_tokens[NextNext].location.source = m_source;
m_tokens[NextNext].token = token;
m_tokens[NextNext].extendedTokenInfo = make_tuple(m, n);

View File

@ -196,7 +196,7 @@ private:
///@}
bool advance() { m_char = m_source->advanceAndGet(); return !m_source->isPastEndOfInput(); }
void rollback(int _amount) { m_char = m_source->rollback(_amount); }
void rollback(size_t _amount) { m_char = m_source->rollback(_amount); }
/// Rolls back to the start of the current token and re-runs the scanner.
void rescan();
@ -231,7 +231,7 @@ private:
Token scanString();
Token scanHexString();
/// Scans a single line comment and returns its corrected end position.
int scanSingleLineDocComment();
size_t scanSingleLineDocComment();
Token scanMultiLineDocComment();
/// Scans a slash '/' and depending on the characters returns the appropriate token
Token scanSlash();
@ -245,7 +245,7 @@ private:
bool isUnicodeLinebreak();
/// Return the current source position.
int sourcePos() const { return m_source->position(); }
size_t sourcePos() const { return m_source->position(); }
bool isSourcePastEndOfInput() const { return m_source->isPastEndOfInput(); }
bool m_supportPeriodInIdentifier = false;

View File

@ -37,7 +37,7 @@ SemVerVersion::SemVerVersion(string const& _versionString)
{
unsigned v = 0;
for (; i != end && '0' <= *i && *i <= '9'; ++i)
v = v * 10 + (*i - '0');
v = v * 10 + unsigned(*i - '0');
numbers[level] = v;
if (level < 2)
{
@ -100,10 +100,10 @@ bool SemVerMatchExpression::MatchComponent::matches(SemVerVersion const& _versio
int cmp = 0;
bool didCompare = false;
for (unsigned i = 0; i < levelsPresent && cmp == 0; i++)
if (version.numbers[i] != unsigned(-1))
if (version.numbers[i] != std::numeric_limits<unsigned>::max())
{
didCompare = true;
cmp = _version.numbers[i] - version.numbers[i];
cmp = static_cast<int>(_version.numbers[i] - version.numbers[i]);
}
if (cmp == 0 && !_version.prerelease.empty() && didCompare)
@ -245,14 +245,14 @@ unsigned SemVerMatchExpressionParser::parseVersionPart()
return 0;
else if ('1' <= c && c <= '9')
{
unsigned v = c - '0';
unsigned v(c - '0');
// If we skip to the next token, the current number is terminated.
while (m_pos == startPos && '0' <= currentChar() && currentChar() <= '9')
{
c = currentChar();
if (v * 10 < v || v * 10 + (c - '0') < v * 10)
if (v * 10 < v || v * 10 + unsigned(c - '0') < v * 10)
throw SemVerError();
v = v * 10 + c - '0';
v = v * 10 + unsigned(c - '0');
nextChar();
}
return v;

View File

@ -85,7 +85,7 @@ struct SourceLocation
assertThrow(0 <= start, SourceLocationError, "Invalid source location.");
assertThrow(start <= end, SourceLocationError, "Invalid source location.");
assertThrow(end <= int(source->source().length()), SourceLocationError, "Invalid source location.");
return source->source().substr(start, end - start);
return source->source().substr(size_t(start), size_t(end - start));
}
/// @returns the smallest SourceLocation that contains both @param _a and @param _b.
@ -113,7 +113,11 @@ struct SourceLocation
std::shared_ptr<CharStream> source;
};
SourceLocation const parseSourceLocation(std::string const& _input, std::string const& _sourceName, size_t _maxIndex = -1);
SourceLocation const parseSourceLocation(
std::string const& _input,
std::string const& _sourceName,
size_t _maxIndex = std::numeric_limits<size_t>::max()
);
/// Stream output for Location (used e.g. in boost exceptions).
inline std::ostream& operator<<(std::ostream& _out, SourceLocation const& _location)

View File

@ -58,11 +58,15 @@ SourceReference SourceReferenceExtractor::extract(SourceLocation const* _locatio
string line = source->lineAtPosition(_location->start);
int locationLength = isMultiline ? line.length() - start.column : end.column - start.column;
int locationLength =
isMultiline ?
int(line.length()) - start.column :
end.column - start.column;
if (locationLength > 150)
{
int const lhs = start.column + 35;
int const rhs = (isMultiline ? line.length() : end.column) - 35;
auto const lhs = static_cast<size_t>(start.column) + 35;
string::size_type const rhs = (isMultiline ? line.length() : static_cast<size_t>(end.column)) - 35;
line = line.substr(0, lhs) + " ... " + line.substr(rhs);
end.column = start.column + 75;
locationLength = 75;
@ -70,8 +74,13 @@ SourceReference SourceReferenceExtractor::extract(SourceLocation const* _locatio
if (line.length() > 150)
{
int const len = line.length();
line = line.substr(max(0, start.column - 35), min(start.column, 35) + min(locationLength + 35, len - start.column));
int const len = static_cast<int>(line.length());
line = line.substr(
static_cast<size_t>(max(0, start.column - 35)),
static_cast<size_t>(min(start.column, 35)) + static_cast<size_t>(
min(locationLength + 35,len - start.column)
)
);
if (start.column + locationLength + 35 < len)
line += " ...";
if (start.column > 35)
@ -79,7 +88,7 @@ SourceReference SourceReferenceExtractor::extract(SourceLocation const* _locatio
line = " ... " + line;
start.column = 40;
}
end.column = start.column + locationLength;
end.column = start.column + static_cast<int>(locationLength);
}
return SourceReference{

View File

@ -51,7 +51,7 @@ void SourceReferenceFormatter::printSourceLocation(SourceReference const& _ref)
);
m_stream << "^";
if (_ref.endColumn > _ref.startColumn + 2)
m_stream << string(_ref.endColumn - _ref.startColumn - 2, '-');
m_stream << string(static_cast<size_t>(_ref.endColumn - _ref.startColumn - 2), '-');
if (_ref.endColumn > _ref.startColumn + 1)
m_stream << "^";
m_stream << endl;
@ -60,7 +60,7 @@ void SourceReferenceFormatter::printSourceLocation(SourceReference const& _ref)
m_stream <<
_ref.text <<
endl <<
string(_ref.startColumn, ' ') <<
string(static_cast<size_t>(_ref.startColumn), ' ') <<
"^ (Relevant source part starts here and spans across multiple lines)." <<
endl;
}

View File

@ -104,7 +104,7 @@ void SourceReferenceFormatterHuman::printSourceLocation(SourceReference const& _
if (!_ref.multiline)
{
int const locationLength = _ref.endColumn - _ref.startColumn;
auto const locationLength = static_cast<size_t>(_ref.endColumn - _ref.startColumn);
// line 1:
m_stream << leftpad << ' ';
@ -113,15 +113,17 @@ void SourceReferenceFormatterHuman::printSourceLocation(SourceReference const& _
// line 2:
frameColored() << line << " |";
m_stream << ' ' << text.substr(0, _ref.startColumn);
highlightColored() << text.substr(_ref.startColumn, locationLength);
m_stream << text.substr(_ref.endColumn) << '\n';
m_stream << ' ' << text.substr(0, static_cast<size_t>(_ref.startColumn));
highlightColored() << text.substr(static_cast<size_t>(_ref.startColumn), locationLength);
m_stream << text.substr(static_cast<size_t>(_ref.endColumn)) << '\n';
// line 3:
m_stream << leftpad << ' ';
frameColored() << '|';
m_stream << ' ' << replaceNonTabs(text.substr(0, _ref.startColumn), ' ');
diagColored() << replaceNonTabs(text.substr(_ref.startColumn, locationLength), '^');
m_stream << ' ' << replaceNonTabs(text.substr(0, static_cast<size_t>(_ref.startColumn)), ' ');
diagColored() << replaceNonTabs(text.substr(static_cast<size_t>(_ref.startColumn), locationLength), '^');
m_stream << '\n';
}
else
@ -133,13 +135,13 @@ void SourceReferenceFormatterHuman::printSourceLocation(SourceReference const& _
// line 2:
frameColored() << line << " |";
m_stream << ' ' << text.substr(0, _ref.startColumn);
highlightColored() << text.substr(_ref.startColumn) << '\n';
m_stream << ' ' << text.substr(0, static_cast<size_t>(_ref.startColumn));
highlightColored() << text.substr(static_cast<size_t>(_ref.startColumn)) << '\n';
// line 3:
m_stream << leftpad << ' ';
frameColored() << '|';
m_stream << ' ' << replaceNonTabs(text.substr(0, _ref.startColumn), ' ');
m_stream << ' ' << replaceNonTabs(text.substr(0, static_cast<size_t>(_ref.startColumn)), ' ');
diagColored() << "^ (Relevant source part starts here and spans across multiple lines).";
m_stream << '\n';
}

View File

@ -130,7 +130,7 @@ int parseSize(string::const_iterator _begin, string::const_iterator _end)
{
try
{
unsigned int m = boost::lexical_cast<int>(boost::make_iterator_range(_begin, _end));
int m = boost::lexical_cast<int>(boost::make_iterator_range(_begin, _end));
return m;
}
catch(boost::bad_lexical_cast const&)

View File

@ -481,7 +481,12 @@ void OverrideChecker::checkIllegalOverrides(ContractDefinition const& _contract)
for (auto const* stateVar: _contract.stateVariables())
{
if (!stateVar->isPublic())
{
if (stateVar->overrides())
m_errorReporter.typeError(8022_error, stateVar->location(), "Override can only be used with public state variables.");
continue;
}
if (contains_if(inheritedMods, MatchByName{stateVar->name()}))
m_errorReporter.typeError(1456_error, stateVar->location(), "Override changes modifier to public state variable.");

View File

@ -1276,7 +1276,8 @@ string YulUtilFunctions::mappingIndexAccessFunction(MappingType const& _mappingT
string YulUtilFunctions::readFromStorage(Type const& _type, size_t _offset, bool _splitFunctionTypes)
{
solUnimplementedAssert(!_splitFunctionTypes, "");
if (_type.category() == Type::Category::Function)
solUnimplementedAssert(!_splitFunctionTypes, "");
string functionName =
"read_from_storage_" +
string(_splitFunctionTypes ? "split_" : "") +
@ -1299,7 +1300,8 @@ string YulUtilFunctions::readFromStorage(Type const& _type, size_t _offset, bool
string YulUtilFunctions::readFromStorageDynamic(Type const& _type, bool _splitFunctionTypes)
{
solUnimplementedAssert(!_splitFunctionTypes, "");
if (_type.category() == Type::Category::Function)
solUnimplementedAssert(!_splitFunctionTypes, "");
string functionName =
"read_from_storage_dynamic" +
string(_splitFunctionTypes ? "split_" : "") +
@ -1429,7 +1431,8 @@ string YulUtilFunctions::writeToMemoryFunction(Type const& _type)
string YulUtilFunctions::extractFromStorageValueDynamic(Type const& _type, bool _splitFunctionTypes)
{
solUnimplementedAssert(!_splitFunctionTypes, "");
if (_type.category() == Type::Category::Function)
solUnimplementedAssert(!_splitFunctionTypes, "");
string functionName =
"extract_from_storage_value_dynamic" +
@ -1474,7 +1477,8 @@ string YulUtilFunctions::extractFromStorageValue(Type const& _type, size_t _offs
string YulUtilFunctions::cleanupFromStorageFunction(Type const& _type, bool _splitFunctionTypes)
{
solAssert(_type.isValueType(), "");
solUnimplementedAssert(!_splitFunctionTypes, "");
if (_type.category() == Type::Category::Function)
solUnimplementedAssert(!_splitFunctionTypes, "");
string functionName = string("cleanup_from_storage_") + (_splitFunctionTypes ? "split_" : "") + _type.identifier();
return m_functionCollector.createFunction(functionName, [&] {

View File

@ -268,101 +268,145 @@ string IRGenerator::generateFunction(FunctionDefinition const& _function)
string IRGenerator::generateGetter(VariableDeclaration const& _varDecl)
{
string functionName = IRNames::function(_varDecl);
return m_context.functionCollector().createFunction(functionName, [&]() {
Type const* type = _varDecl.annotation().type;
Type const* type = _varDecl.annotation().type;
solAssert(_varDecl.isStateVariable(), "");
if (auto const* mappingType = dynamic_cast<MappingType const*>(type))
return m_context.functionCollector().createFunction(functionName, [&]() {
solAssert(!_varDecl.isConstant() && !_varDecl.immutable(), "");
pair<u256, unsigned> slot_offset = m_context.storageLocationOfVariable(_varDecl);
solAssert(slot_offset.second == 0, "");
FunctionType funType(_varDecl);
solUnimplementedAssert(funType.returnParameterTypes().size() == 1, "");
TypePointer returnType = funType.returnParameterTypes().front();
unsigned num_keys = 0;
stringstream indexAccesses;
string slot = m_context.newYulVariable();
do
{
solUnimplementedAssert(
mappingType->keyType()->sizeOnStack() == 1,
"Multi-slot mapping key unimplemented - might not be a problem"
);
indexAccesses <<
slot <<
" := " <<
m_utils.mappingIndexAccessFunction(*mappingType, *mappingType->keyType()) <<
"(" <<
slot;
if (mappingType->keyType()->sizeOnStack() > 0)
indexAccesses <<
", " <<
suffixedVariableNameList("key", num_keys, num_keys + mappingType->keyType()->sizeOnStack());
indexAccesses << ")\n";
num_keys += mappingType->keyType()->sizeOnStack();
}
while ((mappingType = dynamic_cast<MappingType const*>(mappingType->valueType())));
solAssert(_varDecl.isStateVariable(), "");
FunctionType accessorType(_varDecl);
TypePointers paramTypes = accessorType.parameterTypes();
if (_varDecl.immutable())
{
solAssert(paramTypes.empty(), "");
solUnimplementedAssert(type->sizeOnStack() == 1, "");
return Whiskers(R"(
function <functionName>(<keys>) -> rval {
let <slot> := <base>
<indexAccesses>
rval := <readStorage>(<slot>)
function <functionName>() -> rval {
rval := loadimmutable("<id>")
}
)")
("functionName", functionName)
("keys", suffixedVariableNameList("key", 0, num_keys))
("readStorage", m_utils.readFromStorage(*returnType, 0, false))
("indexAccesses", indexAccesses.str())
("slot", slot)
("base", slot_offset.first.str())
("id", to_string(_varDecl.id()))
.render();
});
else
{
solUnimplementedAssert(type->isValueType(), "");
}
else if (_varDecl.isConstant())
{
solAssert(paramTypes.empty(), "");
return Whiskers(R"(
function <functionName>() -> <ret> {
<ret> := <constantValueFunction>()
}
)")
("functionName", functionName)
("constantValueFunction", IRGeneratorForStatements(m_context, m_utils).constantValueFunction(_varDecl))
("ret", suffixedVariableNameList("ret_", 0, _varDecl.type()->sizeOnStack()))
.render();
}
return m_context.functionCollector().createFunction(functionName, [&]() {
if (_varDecl.immutable())
string code;
auto const& location = m_context.storageLocationOfVariable(_varDecl);
code += Whiskers(R"(
let slot := <slot>
let offset := <offset>
)")
("slot", location.first.str())
("offset", to_string(location.second))
.render();
if (!paramTypes.empty())
solAssert(
location.second == 0,
"If there are parameters, we are dealing with structs or mappings and thus should have offset zero."
);
// The code of an accessor is of the form `x[a][b][c]` (it is slightly more complicated
// if the final type is a struct).
// In each iteration of the loop below, we consume one parameter, perform an
// index access, reassign the yul variable `slot` and move @a currentType further "down".
// The initial value of @a currentType is only used if we skip the loop completely.
TypePointer currentType = _varDecl.annotation().type;
vector<string> parameters;
vector<string> returnVariables;
for (size_t i = 0; i < paramTypes.size(); ++i)
{
MappingType const* mappingType = dynamic_cast<MappingType const*>(currentType);
ArrayType const* arrayType = dynamic_cast<ArrayType const*>(currentType);
solAssert(mappingType || arrayType, "");
vector<string> keys = IRVariable("key_" + to_string(i),
mappingType ? *mappingType->keyType() : *TypeProvider::uint256()
).stackSlots();
parameters += keys;
code += Whiskers(R"(
slot<?array>, offset</array> := <indexAccess>(slot<?+keys>, <keys></+keys>)
)")
(
"indexAccess",
mappingType ?
m_utils.mappingIndexAccessFunction(*mappingType, *mappingType->keyType()) :
m_utils.storageArrayIndexAccessFunction(*arrayType)
)
("array", arrayType != nullptr)
("keys", joinHumanReadable(keys))
.render();
currentType = mappingType ? mappingType->valueType() : arrayType->baseType();
}
auto returnTypes = accessorType.returnParameterTypes();
solAssert(returnTypes.size() >= 1, "");
if (StructType const* structType = dynamic_cast<StructType const*>(currentType))
{
solAssert(location.second == 0, "");
auto const& names = accessorType.returnParameterNames();
for (size_t i = 0; i < names.size(); ++i)
{
solUnimplementedAssert(type->sizeOnStack() == 1, "");
return Whiskers(R"(
function <functionName>() -> rval {
rval := loadimmutable("<id>")
}
if (returnTypes[i]->category() == Type::Category::Mapping)
continue;
if (auto arrayType = dynamic_cast<ArrayType const*>(returnTypes[i]))
if (!arrayType->isByteArray())
continue;
// TODO conversion from storage byte arrays is not yet implemented.
pair<u256, unsigned> const& offsets = structType->storageOffsetsOfMember(names[i]);
vector<string> retVars = IRVariable("ret_" + to_string(returnVariables.size()), *returnTypes[i]).stackSlots();
returnVariables += retVars;
code += Whiskers(R"(
<ret> := <readStorage>(add(slot, <slotOffset>))
)")
("functionName", functionName)
("id", to_string(_varDecl.id()))
("ret", joinHumanReadable(retVars))
("readStorage", m_utils.readFromStorage(*returnTypes[i], offsets.second, true))
("slotOffset", offsets.first.str())
.render();
}
else if (_varDecl.isConstant())
return Whiskers(R"(
function <functionName>() -> <ret> {
<ret> := <constantValueFunction>()
}
)")
("functionName", functionName)
("constantValueFunction", IRGeneratorForStatements(m_context, m_utils).constantValueFunction(_varDecl))
("ret", suffixedVariableNameList("ret_", 0, _varDecl.type()->sizeOnStack()))
.render();
else
{
pair<u256, unsigned> slot_offset = m_context.storageLocationOfVariable(_varDecl);
}
else
{
solAssert(returnTypes.size() == 1, "");
vector<string> retVars = IRVariable("ret", *returnTypes.front()).stackSlots();
returnVariables += retVars;
// TODO conversion from storage byte arrays is not yet implemented.
code += Whiskers(R"(
<ret> := <readStorage>(slot, offset)
)")
("ret", joinHumanReadable(retVars))
("readStorage", m_utils.readFromStorageDynamic(*returnTypes.front(), true))
.render();
}
return Whiskers(R"(
function <functionName>() -> rval {
rval := <readStorage>(<slot>)
}
)")
("functionName", functionName)
("readStorage", m_utils.readFromStorage(*type, slot_offset.second, false))
("slot", slot_offset.first.str())
.render();
return Whiskers(R"(
function <functionName>(<params>) -> <retVariables> {
<code>
}
});
}
)")
("functionName", functionName)
("params", joinHumanReadable(parameters))
("retVariables", joinHumanReadable(returnVariables))
("code", std::move(code))
.render();
});
}
string IRGenerator::generateInitialAssignment(VariableDeclaration const& _varDecl)

View File

@ -1467,7 +1467,43 @@ void IRGeneratorForStatements::endVisit(MemberAccess const& _memberAccess)
break;
case Type::Category::Struct:
{
solUnimplementedAssert(false, "");
auto const& structType = dynamic_cast<StructType const&>(*_memberAccess.expression().annotation().type);
IRVariable expression(_memberAccess.expression());
switch (structType.location())
{
case DataLocation::Storage:
{
pair<u256, unsigned> const& offsets = structType.storageOffsetsOfMember(member);
string slot = m_context.newYulVariable();
m_code << "let " << slot << " := " <<
("add(" + expression.name() + ", " + offsets.first.str() + ")\n");
setLValue(_memberAccess, IRLValue{
type(_memberAccess),
IRLValue::Storage{slot, offsets.second}
});
break;
}
case DataLocation::Memory:
{
string pos = m_context.newYulVariable();
m_code << "let " << pos << " := " <<
("add(" + expression.part("mpos").name() + ", " + structType.memoryOffsetOfMember(member).str() + ")\n");
setLValue(_memberAccess, IRLValue{
type(_memberAccess),
IRLValue::Memory{pos}
});
break;
}
case DataLocation::CallData:
{
solUnimplementedAssert(false, "");
break;
}
default:
solAssert(false, "Illegal data location for struct.");
}
break;
}
case Type::Category::Enum:
{

View File

@ -1174,6 +1174,12 @@ bool CommandLineInterface::processInput()
endl;
return false;
}
if (targetMachine == Machine::Ewasm && inputLanguage != Input::StrictAssembly && inputLanguage != Input::Ewasm)
{
serr() << "The selected input language is not directly supported when targeting the Ewasm machine ";
serr() << "and automatic translation is not available." << endl;
return false;
}
serr() <<
"Warning: Yul is still experimental. Please use the output with care." <<
endl;

View File

@ -0,0 +1 @@
--assemble --machine ewasm

View File

@ -0,0 +1 @@
The selected input language is not directly supported when targeting the Ewasm machine and automatic translation is not available.

View File

@ -0,0 +1 @@
1

View File

@ -0,0 +1,3 @@
{
sstore(0, 1)
}

View File

@ -0,0 +1 @@

View File

@ -85,7 +85,7 @@ BOOST_AUTO_TEST_CASE(all_assembly_items)
// PushSubSize
auto sub = _assembly.appendSubroutine(_subAsmPtr);
// PushSub
_assembly.pushSubroutineOffset(size_t(sub.data()));
_assembly.pushSubroutineOffset(static_cast<size_t>(sub.data()));
// PushDeployTimeAddress
_assembly.append(PushDeployTimeAddress);
// AssignImmutable.
@ -187,7 +187,7 @@ BOOST_AUTO_TEST_CASE(immutable)
_assembly.appendImmutableAssignment("someOtherImmutable");
auto sub = _assembly.appendSubroutine(_subAsmPtr);
_assembly.pushSubroutineOffset(size_t(sub.data()));
_assembly.pushSubroutineOffset(static_cast<size_t>(sub.data()));
checkCompilation(_assembly);

View File

@ -1227,7 +1227,7 @@ BOOST_AUTO_TEST_CASE(jumpdest_removal_subassemblies)
sub->append(t4.pushTag());
sub->append(Instruction::JUMP);
size_t subId = size_t(main.appendSubroutine(sub).data());
size_t subId = static_cast<size_t>(main.appendSubroutine(sub).data());
main.append(t1.toSubAssemblyTag(subId));
main.append(t1.toSubAssemblyTag(subId));
main.append(u256(8));
@ -1281,10 +1281,10 @@ BOOST_AUTO_TEST_CASE(cse_remove_redundant_shift_masking)
if (!solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting())
return;
for (int i = 1; i < 256; i++)
for (size_t i = 1; i < 256; i++)
{
checkCSE({
u256(boost::multiprecision::pow(u256(2), i)-1),
u256(boost::multiprecision::pow(u256(2), i) - 1),
Instruction::CALLVALUE,
u256(256-i),
Instruction::SHR,
@ -1309,10 +1309,10 @@ BOOST_AUTO_TEST_CASE(cse_remove_redundant_shift_masking)
}
// Check that opt. does NOT trigger
for (int i = 1; i < 255; i++)
for (size_t i = 1; i < 255; i++)
{
checkCSE({
u256(boost::multiprecision::pow(u256(2), i)-1),
u256(boost::multiprecision::pow(u256(2), i) - 1),
Instruction::CALLVALUE,
u256(255-i),
Instruction::SHR,

View File

@ -0,0 +1,14 @@
contract C {
uint8[][2] public a;
constructor() public {
a[1].push(3);
a[1].push(4);
}
}
// ====
// compileViaYul: also
// ----
// a(uint256,uint256): 0, 0 -> FAILURE
// a(uint256,uint256): 1, 0 -> 3
// a(uint256,uint256): 1, 1 -> 4
// a(uint256,uint256): 2, 0 -> FAILURE

View File

@ -0,0 +1,11 @@
contract C {
mapping(uint => mapping(uint => uint)) public x;
constructor() public {
x[1][2] = 3;
}
}
// ====
// compileViaYul: also
// ----
// x(uint256,uint256): 1, 2 -> 3
// x(uint256,uint256): 0, 0 -> 0

View File

@ -0,0 +1,20 @@
contract C {
struct S {
uint8 a;
uint16 b;
uint128 c;
uint d;
}
mapping(uint => mapping(uint => S)) public x;
constructor() public {
x[1][2].a = 3;
x[1][2].b = 4;
x[1][2].c = 5;
x[1][2].d = 6;
}
}
// ====
// compileViaYul: also
// ----
// x(uint256,uint256): 1, 2 -> 3, 4, 5, 6
// x(uint256,uint256): 0, 0 -> 0x00, 0x00, 0x00, 0x00

View File

@ -0,0 +1,19 @@
contract C {
uint8 public a;
uint16 public b;
uint128 public c;
uint public d;
constructor() public {
a = 3;
b = 4;
c = 5;
d = 6;
}
}
// ====
// compileViaYul: also
// ----
// a() -> 3
// b() -> 4
// c() -> 5
// d() -> 6

View File

@ -8,8 +8,10 @@ contract test {
dynamicData[2][2] = 8;
}
}
// ====
// compileViaYul: also
// ----
// data(uint256,uint256): 2, 2 -> 8
// data(uint256,uint256): 2, 8 -> FAILURE # NB: the original code contained a bug here #
// data(uint256,uint256): 2, 8 -> FAILURE # NB: the original code contained a bug here #
// dynamicData(uint256,uint256): 2, 2 -> 8
// dynamicData(uint256,uint256): 2, 8 -> FAILURE

View File

@ -8,5 +8,7 @@ contract test {
data[7].d = true;
}
}
// ====
// compileViaYul: also
// ----
// data(uint256): 7 -> 1, 2, true

View File

@ -0,0 +1,9 @@
contract C1 {
function f() external pure returns(int) { return 42; }
}
contract C is C1 {
int override f;
}
// ----
// TypeError: (96-110): Override can only be used with public state variables.