From a9c8b4b4d1879909a1cf2adec31613f9eb56e968 Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Mon, 10 Jul 2023 13:12:46 +0200 Subject: [PATCH] Purge using namespace std --- CODING_STYLE.md | 20 +--- libevmasm/Assembly.cpp | 121 ++++++++++---------- libevmasm/AssemblyItem.cpp | 88 +++++++------- libevmasm/BlockDeduplicator.cpp | 9 +- libevmasm/CommonSubexpressionEliminator.cpp | 29 +++-- libevmasm/ConstantOptimiser.cpp | 9 +- libevmasm/ControlFlowGraph.cpp | 25 ++-- libevmasm/Disassemble.cpp | 7 +- libevmasm/ExpressionClasses.cpp | 29 +++-- libevmasm/GasMeter.cpp | 3 +- libevmasm/Inliner.cpp | 29 +++-- libevmasm/Instruction.cpp | 3 +- libevmasm/JumpdestRemover.cpp | 11 +- libevmasm/KnownState.cpp | 49 ++++---- libevmasm/LinkerObject.cpp | 17 ++- libevmasm/PathGasMeter.cpp | 15 ++- libevmasm/PeepholeOptimiser.cpp | 43 ++++--- libevmasm/SemanticInformation.cpp | 9 +- libevmasm/SimplificationRules.cpp | 21 ++-- 19 files changed, 255 insertions(+), 282 deletions(-) diff --git a/CODING_STYLE.md b/CODING_STYLE.md index cd46800da..5b9129fbd 100644 --- a/CODING_STYLE.md +++ b/CODING_STYLE.md @@ -51,11 +51,11 @@ To set indentation and tab width settings uniformly, the repository contains an ## 1. Namespaces 1. No `using namespace` declarations in header files. -2. Use `using namespace std;` in cpp files, but avoid importing namespaces from boost and others. -3. All symbols should be declared in a namespace except for final applications. -4. Use anonymous namespaces for helpers whose scope is a cpp file only. -5. Preprocessor symbols should be prefixed with the namespace in all-caps and an underscore. -6. Do not use `std::` qualifier in cpp files (see 2.), except for `std::move` and `std::forward`, which will otherwise cause the `check_style` step to fail. +2. `using namespace solidity;` and other project local namespaces is fine in cpp files, and generally encouraged. +3. Avoid `using namespace` at file level for third party libraries, such as boost, ranges, etc. +4. All symbols should be declared in a namespace except for final applications. +5. Use anonymous namespaces for helpers whose scope is a cpp file only. +6. Preprocessor symbols should be prefixed with the namespace in all-caps and an underscore. Only in the header: ```cpp @@ -66,16 +66,6 @@ std::tuple meanAndSigma(std::vector const& _v); } ``` -Only in the cpp file: -```cpp -#include -using namespace std; -tuple myNamespace::meanAndSigma(vector const& _v) -{ - // ... -} -``` - ## 2. Preprocessor 1. File comment is always at top, and includes: diff --git a/libevmasm/Assembly.cpp b/libevmasm/Assembly.cpp index b9b946aa5..f524aad66 100644 --- a/libevmasm/Assembly.cpp +++ b/libevmasm/Assembly.cpp @@ -42,7 +42,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; @@ -77,7 +76,7 @@ unsigned Assembly::codeSize(unsigned subTagSize) const namespace { -string locationFromSources(StringMap const& _sourceCodes, SourceLocation const& _location) +std::string locationFromSources(StringMap const& _sourceCodes, SourceLocation const& _location) { if (!_location.hasText() || _sourceCodes.empty()) return {}; @@ -92,7 +91,7 @@ string locationFromSources(StringMap const& _sourceCodes, SourceLocation const& class Functionalizer { public: - Functionalizer (ostream& _out, string const& _prefix, StringMap const& _sourceCodes, Assembly const& _assembly): + Functionalizer (std::ostream& _out, std::string const& _prefix, StringMap const& _sourceCodes, Assembly const& _assembly): m_out(_out), m_prefix(_prefix), m_sourceCodes(_sourceCodes), m_assembly(_assembly) {} @@ -105,7 +104,7 @@ public: printLocation(_debugInfoSelection); } - string expression = _item.toAssemblyText(m_assembly); + std::string expression = _item.toAssemblyText(m_assembly); if (!( _item.canBeFunctional() && @@ -114,7 +113,7 @@ public: )) { flush(); - m_out << m_prefix << (_item.type() == Tag ? "" : " ") << expression << endl; + m_out << m_prefix << (_item.type() == Tag ? "" : " ") << expression << std::endl; return; } if (_item.arguments() > 0) @@ -137,8 +136,8 @@ public: void flush() { - for (string const& expression: m_pending) - m_out << m_prefix << " " << expression << endl; + for (std::string const& expression: m_pending) + m_out << m_prefix << " " << expression << std::endl; m_pending.clear(); } @@ -154,7 +153,7 @@ public: if (m_location.sourceName) m_out << " " + escapeAndQuoteString(*m_location.sourceName); if (m_location.hasText()) - m_out << ":" << to_string(m_location.start) + ":" + to_string(m_location.end); + m_out << ":" << std::to_string(m_location.start) + ":" + std::to_string(m_location.end); } if (_debugInfoSelection.snippet) @@ -165,15 +164,15 @@ public: m_out << locationFromSources(m_sourceCodes, m_location); } - m_out << " */" << endl; + m_out << " */" << std::endl; } private: strings m_pending; SourceLocation m_location; - ostream& m_out; - string const& m_prefix; + std::ostream& m_out; + std::string const& m_prefix; StringMap const& m_sourceCodes; Assembly const& m_assembly; }; @@ -181,9 +180,9 @@ private: } void Assembly::assemblyStream( - ostream& _out, + std::ostream& _out, DebugInfoSelection const& _debugInfoSelection, - string const& _prefix, + std::string const& _prefix, StringMap const& _sourceCodes ) const { @@ -195,34 +194,34 @@ void Assembly::assemblyStream( if (!m_data.empty() || !m_subs.empty()) { - _out << _prefix << "stop" << endl; + _out << _prefix << "stop" << std::endl; for (auto const& i: m_data) if (u256(i.first) >= m_subs.size()) - _out << _prefix << "data_" << toHex(u256(i.first)) << " " << util::toHex(i.second) << endl; + _out << _prefix << "data_" << toHex(u256(i.first)) << " " << util::toHex(i.second) << std::endl; for (size_t i = 0; i < m_subs.size(); ++i) { - _out << endl << _prefix << "sub_" << i << ": assembly {\n"; + _out << std::endl << _prefix << "sub_" << i << ": assembly {\n"; m_subs[i]->assemblyStream(_out, _debugInfoSelection, _prefix + " ", _sourceCodes); - _out << _prefix << "}" << endl; + _out << _prefix << "}" << std::endl; } } if (m_auxiliaryData.size() > 0) - _out << endl << _prefix << "auxdata: 0x" << util::toHex(m_auxiliaryData) << endl; + _out << std::endl << _prefix << "auxdata: 0x" << util::toHex(m_auxiliaryData) << std::endl; } -string Assembly::assemblyString( +std::string Assembly::assemblyString( DebugInfoSelection const& _debugInfoSelection, StringMap const& _sourceCodes ) const { - ostringstream tmp; + std::ostringstream tmp; assemblyStream(tmp, _debugInfoSelection, "", _sourceCodes); return tmp.str(); } -Json::Value Assembly::assemblyJSON(map const& _sourceIndices, bool _includeSourceList) const +Json::Value Assembly::assemblyJSON(std::map const& _sourceIndices, bool _includeSourceList) const { Json::Value root; root[".code"] = Json::arrayValue; @@ -244,7 +243,7 @@ Json::Value Assembly::assemblyJSON(map const& _sourceIndices, jsonItem["end"] = item.location().end; if (item.m_modifierDepth != 0) jsonItem["modifierDepth"] = static_cast(item.m_modifierDepth); - string jumpType = item.getJumpTypeAsString(); + std::string jumpType = item.getJumpTypeAsString(); if (!jumpType.empty()) jsonItem["jumpType"] = jumpType; if (name == "PUSHLIB") @@ -286,8 +285,8 @@ Json::Value Assembly::assemblyJSON(map const& _sourceIndices, for (size_t i = 0; i < m_subs.size(); ++i) { - stringstream hexStr; - hexStr << hex << i; + std::stringstream hexStr; + hexStr << std::hex << i; data[hexStr.str()] = m_subs[i]->assemblyJSON(_sourceIndices, /*_includeSourceList = */false); } } @@ -298,7 +297,7 @@ Json::Value Assembly::assemblyJSON(map const& _sourceIndices, return root; } -AssemblyItem Assembly::namedTag(string const& _name, size_t _params, size_t _returns, optional _sourceID) +AssemblyItem Assembly::namedTag(std::string const& _name, size_t _params, size_t _returns, std::optional _sourceID) { assertThrow(!_name.empty(), AssemblyException, "Empty named tag."); if (m_namedTags.count(_name)) @@ -312,21 +311,21 @@ AssemblyItem Assembly::namedTag(string const& _name, size_t _params, size_t _ret return AssemblyItem{Tag, m_namedTags.at(_name).id}; } -AssemblyItem Assembly::newPushLibraryAddress(string const& _identifier) +AssemblyItem Assembly::newPushLibraryAddress(std::string const& _identifier) { h256 h(util::keccak256(_identifier)); m_libraries[h] = _identifier; return AssemblyItem{PushLibraryAddress, h}; } -AssemblyItem Assembly::newPushImmutable(string const& _identifier) +AssemblyItem Assembly::newPushImmutable(std::string const& _identifier) { h256 h(util::keccak256(_identifier)); m_immutables[h] = _identifier; return AssemblyItem{PushImmutable, h}; } -AssemblyItem Assembly::newImmutableAssignment(string const& _identifier) +AssemblyItem Assembly::newImmutableAssignment(std::string const& _identifier) { h256 h(util::keccak256(_identifier)); m_immutables[h] = _identifier; @@ -339,9 +338,9 @@ Assembly& Assembly::optimise(OptimiserSettings const& _settings) return *this; } -map const& Assembly::optimiseInternal( +std::map const& Assembly::optimiseInternal( OptimiserSettings const& _settings, - set _tagsReferencedFromOutside + std::set _tagsReferencedFromOutside ) { if (m_tagReplacements) @@ -352,7 +351,7 @@ map const& Assembly::optimiseInternal( { OptimiserSettings settings = _settings; Assembly& sub = *m_subs[subId]; - map const& subTagReplacements = sub.optimiseInternal( + std::map const& subTagReplacements = sub.optimiseInternal( settings, JumpdestRemover::referencedTags(m_items, subId) ); @@ -360,7 +359,7 @@ map const& Assembly::optimiseInternal( BlockDeduplicator::applyTagReplacement(m_items, subTagReplacements, subId); } - map tagReplacements; + std::map tagReplacements; // Iterate until no new optimisation possibilities are found. for (unsigned count = 1; count > 0;) { @@ -401,7 +400,7 @@ map const& Assembly::optimiseInternal( for (auto const& replacement: deduplicator.replacedTags()) { assertThrow( - replacement.first <= numeric_limits::max() && replacement.second <= numeric_limits::max(), + replacement.first <= std::numeric_limits::max() && replacement.second <= std::numeric_limits::max(), OptimizerException, "Invalid tag replacement." ); @@ -494,7 +493,7 @@ LinkerObject const& Assembly::assemble() const LinkerObject& ret = m_assembledObject; size_t subTagSize = 1; - map>> immutableReferencesBySub; + std::map>> immutableReferencesBySub; for (auto const& sub: m_subs) { auto const& linkerObject = sub->assemble(); @@ -508,7 +507,7 @@ LinkerObject const& Assembly::assemble() const immutableReferencesBySub = linkerObject.immutableReferences; } for (size_t tagPos: sub->m_tagPositionsInBytecode) - if (tagPos != numeric_limits::max() && tagPos > subTagSize) + if (tagPos != std::numeric_limits::max() && tagPos > subTagSize) subTagSize = tagPos; } @@ -531,11 +530,11 @@ LinkerObject const& Assembly::assemble() const ); unsigned bytesRequiredForCode = codeSize(static_cast(subTagSize)); - m_tagPositionsInBytecode = vector(m_usedTags, numeric_limits::max()); - map> tagRef; - multimap dataRef; - multimap subRef; - vector sizeRef; ///< Pointers to code locations where the size of the program is inserted + m_tagPositionsInBytecode = std::vector(m_usedTags, std::numeric_limits::max()); + std::map> tagRef; + std::multimap dataRef; + std::multimap subRef; + std::vector sizeRef; ///< Pointers to code locations where the size of the program is inserted unsigned bytesPerTag = numberEncodingSize(bytesRequiredForCode); uint8_t tagPush = static_cast(pushInstruction(bytesPerTag)); @@ -550,7 +549,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] == numeric_limits::max()) + if (i.type() != Tag && m_tagPositionsInBytecode[0] == std::numeric_limits::max()) m_tagPositionsInBytecode[0] = ret.bytecode.size(); switch (i.type()) @@ -583,21 +582,21 @@ LinkerObject const& Assembly::assemble() const } case PushData: ret.bytecode.push_back(dataRefPush); - dataRef.insert(make_pair(h256(i.data()), ret.bytecode.size())); + dataRef.insert(std::make_pair(h256(i.data()), ret.bytecode.size())); ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef); break; case PushSub: - assertThrow(i.data() <= numeric_limits::max(), AssemblyException, ""); + assertThrow(i.data() <= std::numeric_limits::max(), AssemblyException, ""); ret.bytecode.push_back(dataRefPush); - subRef.insert(make_pair(static_cast(i.data()), ret.bytecode.size())); + subRef.insert(std::make_pair(static_cast(i.data()), ret.bytecode.size())); ret.bytecode.resize(ret.bytecode.size() + bytesPerDataRef); break; case PushSubSize: { - assertThrow(i.data() <= numeric_limits::max(), AssemblyException, ""); + assertThrow(i.data() <= std::numeric_limits::max(), AssemblyException, ""); auto s = subAssemblyById(static_cast(i.data()))->assemble().bytecode.size(); i.setPushedValue(u256(s)); - unsigned b = max(1, numberEncodingSize(s)); + unsigned b = std::max(1, numberEncodingSize(s)); ret.bytecode.push_back(static_cast(pushInstruction(b))); ret.bytecode.resize(ret.bytecode.size() + b); bytesRef byr(&ret.bytecode.back() + 1 - b, b); @@ -618,7 +617,7 @@ LinkerObject const& Assembly::assemble() const break; case PushImmutable: ret.bytecode.push_back(static_cast(Instruction::PUSH32)); - // Maps keccak back to the "identifier" string of that immutable. + // Maps keccak back to the "identifier" std::string of that immutable. ret.immutableReferences[i.data()].first = m_immutables.at(i.data()); // Record the bytecode offset of the PUSH32 argument. ret.immutableReferences[i.data()].second.emplace_back(ret.bytecode.size()); @@ -661,10 +660,10 @@ LinkerObject const& Assembly::assemble() const case Tag: { assertThrow(i.data() != 0, AssemblyException, "Invalid tag position."); - assertThrow(i.splitForeignPushTag().first == numeric_limits::max(), AssemblyException, "Foreign tag."); + assertThrow(i.splitForeignPushTag().first == std::numeric_limits::max(), AssemblyException, "Foreign tag."); size_t tagId = static_cast(i.data()); assertThrow(ret.bytecode.size() < 0xffffffffL, AssemblyException, "Tag too large."); - assertThrow(m_tagPositionsInBytecode[tagId] == numeric_limits::max(), AssemblyException, "Duplicate tag position."); + assertThrow(m_tagPositionsInBytecode[tagId] == std::numeric_limits::max(), AssemblyException, "Duplicate tag position."); m_tagPositionsInBytecode[tagId] = ret.bytecode.size(); ret.bytecode.push_back(static_cast(Instruction::JUMPDEST)); break; @@ -686,7 +685,7 @@ LinkerObject const& Assembly::assemble() const // Append an INVALID here to help tests find miscompilation. ret.bytecode.push_back(static_cast(Instruction::INVALID)); - map subAssemblyOffsets; + std::map subAssemblyOffsets; for (auto const& [subIdPath, bytecodeOffset]: subRef) { LinkerObject subObject = subAssemblyById(subIdPath)->assemble(); @@ -709,15 +708,15 @@ LinkerObject const& Assembly::assemble() const { size_t subId; size_t tagId; - tie(subId, tagId) = i.second; - assertThrow(subId == numeric_limits::max() || subId < m_subs.size(), AssemblyException, "Invalid sub id"); - vector const& tagPositions = - subId == numeric_limits::max() ? + std::tie(subId, tagId) = i.second; + assertThrow(subId == std::numeric_limits::max() || subId < m_subs.size(), AssemblyException, "Invalid sub id"); + std::vector const& tagPositions = + subId == std::numeric_limits::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 != numeric_limits::max(), AssemblyException, "Reference to tag without position."); + assertThrow(pos != std::numeric_limits::max(), AssemblyException, "Reference to tag without position."); assertThrow(numberEncodingSize(pos) <= bytesPerTag, AssemblyException, "Tag too large for reserved space."); bytesRef r(ret.bytecode.data() + i.first, bytesPerTag); toBigEndian(pos, r); @@ -725,7 +724,7 @@ LinkerObject const& Assembly::assemble() const for (auto const& [name, tagInfo]: m_namedTags) { size_t position = m_tagPositionsInBytecode.at(tagInfo.id); - optional tagIndex; + std::optional tagIndex; for (auto&& [index, item]: m_items | ranges::views::enumerate) if (item.type() == Tag && static_cast(item.data()) == tagInfo.id) { @@ -733,7 +732,7 @@ LinkerObject const& Assembly::assemble() const break; } ret.functionDebugData[name] = { - position == numeric_limits::max() ? nullopt : optional{position}, + position == std::numeric_limits::max() ? std::nullopt : std::optional{position}, tagIndex, tagInfo.sourceID, tagInfo.params, @@ -764,7 +763,7 @@ LinkerObject const& Assembly::assemble() const return ret; } -vector Assembly::decodeSubPath(size_t _subObjectId) const +std::vector Assembly::decodeSubPath(size_t _subObjectId) const { if (_subObjectId < m_subs.size()) return {_subObjectId}; @@ -779,7 +778,7 @@ vector Assembly::decodeSubPath(size_t _subObjectId) const return subIdPathIt->first; } -size_t Assembly::encodeSubPath(vector const& _subPath) +size_t Assembly::encodeSubPath(std::vector const& _subPath) { assertThrow(!_subPath.empty(), AssemblyException, ""); if (_subPath.size() == 1) @@ -790,7 +789,7 @@ size_t Assembly::encodeSubPath(vector const& _subPath) if (m_subPaths.find(_subPath) == m_subPaths.end()) { - size_t objectId = numeric_limits::max() - m_subPaths.size(); + size_t objectId = std::numeric_limits::max() - m_subPaths.size(); assertThrow(objectId >= m_subs.size(), AssemblyException, ""); m_subPaths[_subPath] = objectId; } @@ -800,7 +799,7 @@ size_t Assembly::encodeSubPath(vector const& _subPath) Assembly const* Assembly::subAssemblyById(size_t _subId) const { - vector subIds = decodeSubPath(_subId); + std::vector subIds = decodeSubPath(_subId); Assembly const* currentAssembly = this; for (size_t currentSubId: subIds) { diff --git a/libevmasm/AssemblyItem.cpp b/libevmasm/AssemblyItem.cpp index 5661fb940..6c2b673c6 100644 --- a/libevmasm/AssemblyItem.cpp +++ b/libevmasm/AssemblyItem.cpp @@ -30,7 +30,7 @@ #include #include -using namespace std; +using namespace std::literals; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; @@ -40,10 +40,10 @@ static_assert(sizeof(size_t) <= 8, "size_t must be at most 64-bits wide"); namespace { -string toStringInHex(u256 _value) +std::string toStringInHex(u256 _value) { - stringstream hexStr; - hexStr << uppercase << hex << _value; + std::stringstream hexStr; + hexStr << std::uppercase << std::hex << _value; return hexStr.str(); } @@ -60,16 +60,16 @@ AssemblyItem AssemblyItem::toSubAssemblyTag(size_t _subId) const return r; } -pair AssemblyItem::splitForeignPushTag() const +std::pair AssemblyItem::splitForeignPushTag() const { assertThrow(m_type == PushTag || m_type == Tag, util::Exception, ""); u256 combined = u256(data()); size_t subId = static_cast((combined >> 64) - 1); size_t tag = static_cast(combined & 0xffffffffffffffffULL); - return make_pair(subId, tag); + return std::make_pair(subId, tag); } -pair AssemblyItem::nameAndData(langutil::EVMVersion _evmVersion) const +std::pair AssemblyItem::nameAndData(langutil::EVMVersion _evmVersion) const { switch (type()) { @@ -111,7 +111,7 @@ void AssemblyItem::setPushTagSubIdAndTag(size_t _subId, size_t _tag) { assertThrow(m_type == PushTag || m_type == Tag, util::Exception, ""); u256 data = _tag; - if (_subId != numeric_limits::max()) + if (_subId != std::numeric_limits::max()) data |= (u256(_subId) + 1) << 64; setData(data); } @@ -124,7 +124,7 @@ size_t AssemblyItem::bytesRequired(size_t _addressLength, Precision _precision) case Tag: // 1 byte for the JUMPDEST return 1; case Push: - return 1 + max(1, numberEncodingSize(data())); + return 1 + std::max(1, numberEncodingSize(data())); case PushSubSize: case PushProgramSize: return 1 + 4; // worst case: a 16MB program @@ -158,7 +158,7 @@ size_t AssemblyItem::bytesRequired(size_t _addressLength, Precision _precision) return 2; } case VerbatimBytecode: - return get<2>(*m_verbatimBytecode).size(); + return std::get<2>(*m_verbatimBytecode).size(); default: break; } @@ -172,7 +172,7 @@ size_t AssemblyItem::arguments() const // the same across all EVM versions except for the instruction name. return static_cast(instructionInfo(instruction(), EVMVersion()).args); else if (type() == VerbatimBytecode) - return get<0>(*m_verbatimBytecode); + return std::get<0>(*m_verbatimBytecode); else if (type() == AssignImmutable) return 2; else @@ -200,7 +200,7 @@ size_t AssemblyItem::returnValues() const case Tag: return 0; case VerbatimBytecode: - return get<1>(*m_verbatimBytecode); + return std::get<1>(*m_verbatimBytecode); default: break; } @@ -233,7 +233,7 @@ bool AssemblyItem::canBeFunctional() const return false; } -string AssemblyItem::getJumpTypeAsString() const +std::string AssemblyItem::getJumpTypeAsString() const { switch (m_jumpType) { @@ -247,9 +247,9 @@ string AssemblyItem::getJumpTypeAsString() const } } -string AssemblyItem::toAssemblyText(Assembly const& _assembly) const +std::string AssemblyItem::toAssemblyText(Assembly const& _assembly) const { - string text; + std::string text; switch (type()) { case Operation: @@ -265,26 +265,26 @@ string AssemblyItem::toAssemblyText(Assembly const& _assembly) const { size_t sub{0}; size_t tag{0}; - tie(sub, tag) = splitForeignPushTag(); - if (sub == numeric_limits::max()) - text = string("tag_") + to_string(tag); + std::tie(sub, tag) = splitForeignPushTag(); + if (sub == std::numeric_limits::max()) + text = std::string("tag_") + std::to_string(tag); else - text = string("tag_") + to_string(sub) + "_" + to_string(tag); + text = std::string("tag_") + std::to_string(sub) + "_" + std::to_string(tag); break; } case Tag: assertThrow(data() < 0x10000, AssemblyException, "Declaration of sub-assembly tag."); - text = string("tag_") + to_string(static_cast(data())) + ":"; + text = std::string("tag_") + std::to_string(static_cast(data())) + ":"; break; case PushData: - text = string("data_") + toHex(data()); + text = std::string("data_") + toHex(data()); break; case PushSub: case PushSubSize: { - vector subPathComponents; + std::vector subPathComponents; for (size_t subPathComponentId: _assembly.decodeSubPath(static_cast(data()))) - subPathComponents.emplace_back("sub_" + to_string(subPathComponentId)); + subPathComponents.emplace_back("sub_" + std::to_string(subPathComponentId)); text = (type() == PushSub ? "dataOffset"s : "dataSize"s) + "(" + @@ -293,25 +293,25 @@ string AssemblyItem::toAssemblyText(Assembly const& _assembly) const break; } case PushProgramSize: - text = string("bytecodeSize"); + text = std::string("bytecodeSize"); break; case PushLibraryAddress: - text = string("linkerSymbol(\"") + toHex(data()) + string("\")"); + text = std::string("linkerSymbol(\"") + toHex(data()) + std::string("\")"); break; case PushDeployTimeAddress: - text = string("deployTimeAddress()"); + text = std::string("deployTimeAddress()"); break; case PushImmutable: - text = string("immutable(\"") + "0x" + util::toHex(toCompactBigEndian(data(), 1)) + "\")"; + text = std::string("immutable(\"") + "0x" + util::toHex(toCompactBigEndian(data(), 1)) + "\")"; break; case AssignImmutable: - text = string("assignImmutable(\"") + "0x" + util::toHex(toCompactBigEndian(data(), 1)) + "\")"; + text = std::string("assignImmutable(\"") + "0x" + util::toHex(toCompactBigEndian(data(), 1)) + "\")"; break; case UndefinedItem: assertThrow(false, AssemblyException, "Invalid assembly item."); break; case VerbatimBytecode: - text = string("verbatimbytecode_") + util::toHex(get<2>(*m_verbatimBytecode)); + text = std::string("verbatimbytecode_") + util::toHex(std::get<2>(*m_verbatimBytecode)); break; default: assertThrow(false, InvalidOpcode, ""); @@ -328,7 +328,7 @@ string AssemblyItem::toAssemblyText(Assembly const& _assembly) const } // Note: This method is exclusively used for debugging. -ostream& solidity::evmasm::operator<<(ostream& _out, AssemblyItem const& _item) +std::ostream& solidity::evmasm::operator<<(std::ostream& _out, AssemblyItem const& _item) { switch (_item.type()) { @@ -338,12 +338,12 @@ ostream& solidity::evmasm::operator<<(ostream& _out, AssemblyItem const& _item) _out << "\t" << _item.getJumpTypeAsString(); break; case Push: - _out << " PUSH " << hex << _item.data() << dec; + _out << " PUSH " << std::hex << _item.data() << std::dec; break; case PushTag: { size_t subId = _item.splitForeignPushTag().first; - if (subId == numeric_limits::max()) + if (subId == std::numeric_limits::max()) _out << " PushTag " << _item.splitForeignPushTag().second; else _out << " PushTag " << subId << ":" << _item.splitForeignPushTag().second; @@ -353,20 +353,20 @@ ostream& solidity::evmasm::operator<<(ostream& _out, AssemblyItem const& _item) _out << " Tag " << _item.data(); break; case PushData: - _out << " PushData " << hex << static_cast(_item.data()) << dec; + _out << " PushData " << std::hex << static_cast(_item.data()) << std::dec; break; case PushSub: - _out << " PushSub " << hex << static_cast(_item.data()) << dec; + _out << " PushSub " << std::hex << static_cast(_item.data()) << std::dec; break; case PushSubSize: - _out << " PushSubSize " << hex << static_cast(_item.data()) << dec; + _out << " PushSubSize " << std::hex << static_cast(_item.data()) << std::dec; break; case PushProgramSize: _out << " PushProgramSize"; break; case PushLibraryAddress: { - string hash(util::h256((_item.data())).hex()); + std::string hash(util::h256((_item.data())).hex()); _out << " PushLibraryAddress " << hash.substr(0, 8) + "..." + hash.substr(hash.length() - 8); break; } @@ -411,12 +411,12 @@ size_t AssemblyItem::opcodeCount() const noexcept } } -string AssemblyItem::computeSourceMapping( +std::string AssemblyItem::computeSourceMapping( AssemblyItems const& _items, - map const& _sourceIndicesMap + std::map const& _sourceIndicesMap ) { - string ret; + std::string ret; int prevStart = -1; int prevLength = -1; @@ -465,17 +465,17 @@ string AssemblyItem::computeSourceMapping( if (components-- > 0) { if (location.start != prevStart) - ret += to_string(location.start); + ret += std::to_string(location.start); if (components-- > 0) { ret += ':'; if (length != prevLength) - ret += to_string(length); + ret += std::to_string(length); if (components-- > 0) { ret += ':'; if (sourceIndex != prevSourceIndex) - ret += to_string(sourceIndex); + ret += std::to_string(sourceIndex); if (components-- > 0) { ret += ':'; @@ -485,7 +485,7 @@ string AssemblyItem::computeSourceMapping( { ret += ':'; if (modifierDepth != prevModifierDepth) - ret += to_string(modifierDepth); + ret += std::to_string(modifierDepth); } } } @@ -493,7 +493,7 @@ string AssemblyItem::computeSourceMapping( } if (item.opcodeCount() > 1) - ret += string(item.opcodeCount() - 1, ';'); + ret += std::string(item.opcodeCount() - 1, ';'); prevStart = location.start; prevLength = length; diff --git a/libevmasm/BlockDeduplicator.cpp b/libevmasm/BlockDeduplicator.cpp index 5f9fa768f..c978bae2b 100644 --- a/libevmasm/BlockDeduplicator.cpp +++ b/libevmasm/BlockDeduplicator.cpp @@ -30,7 +30,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; @@ -49,7 +48,7 @@ bool BlockDeduplicator::deduplicate() ) return false; - function comparator = [&](size_t _i, size_t _j) + std::function comparator = [&](size_t _i, size_t _j) { if (_i == _j) return false; @@ -81,7 +80,7 @@ bool BlockDeduplicator::deduplicate() for (; ; ++iterations) { //@todo this should probably be optimized. - set> blocksSeen(comparator); + std::set> blocksSeen(comparator); for (size_t i = 0; i < m_items.size(); ++i) { if (m_items.at(i).type() != Tag) @@ -101,7 +100,7 @@ bool BlockDeduplicator::deduplicate() bool BlockDeduplicator::applyTagReplacement( AssemblyItems& _items, - map const& _replacements, + std::map const& _replacements, size_t _subId ) { @@ -111,7 +110,7 @@ bool BlockDeduplicator::applyTagReplacement( { size_t subId; size_t tagId; - tie(subId, tagId) = item.splitForeignPushTag(); + std::tie(subId, tagId) = item.splitForeignPushTag(); if (subId != _subId) continue; auto it = _replacements.find(tagId); diff --git a/libevmasm/CommonSubexpressionEliminator.cpp b/libevmasm/CommonSubexpressionEliminator.cpp index d097f3c72..de1e5a364 100644 --- a/libevmasm/CommonSubexpressionEliminator.cpp +++ b/libevmasm/CommonSubexpressionEliminator.cpp @@ -30,12 +30,11 @@ #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; -vector CommonSubexpressionEliminator::getOptimizedItems() +std::vector CommonSubexpressionEliminator::getOptimizedItems() { optimizeBreakingItem(); @@ -52,11 +51,11 @@ vector CommonSubexpressionEliminator::getOptimizedItems() m_state = std::move(nextState); }); - map initialStackContents; - map targetStackContents; + std::map initialStackContents; + std::map targetStackContents; int minHeight = m_state.stackHeight() + 1; if (!m_state.stackElements().empty()) - minHeight = min(minHeight, m_state.stackElements().begin()->first); + minHeight = std::min(minHeight, m_state.stackElements().begin()->first); for (int height = minHeight; height <= m_initialState.stackHeight(); ++height) initialStackContents[height] = m_initialState.stackElement(height, SourceLocation()); for (int height = minHeight; height <= m_state.stackHeight(); ++height) @@ -125,19 +124,19 @@ void CommonSubexpressionEliminator::optimizeBreakingItem() CSECodeGenerator::CSECodeGenerator( ExpressionClasses& _expressionClasses, - vector const& _storeOperations + std::vector const& _storeOperations ): m_expressionClasses(_expressionClasses) { for (auto const& store: _storeOperations) - m_storeOperations[make_pair(store.target, store.slot)].push_back(store); + m_storeOperations[std::make_pair(store.target, store.slot)].push_back(store); } AssemblyItems CSECodeGenerator::generateCode( unsigned _initialSequenceNumber, int _initialStackHeight, - map const& _initialStack, - map const& _targetStackContents + std::map const& _initialStack, + std::map const& _targetStackContents ) { m_stackHeight = _initialStackHeight; @@ -156,7 +155,7 @@ AssemblyItems CSECodeGenerator::generateCode( } // store all needed sequenced expressions - set> sequencedExpressions; + std::set> sequencedExpressions; for (auto const& p: m_neededBy) for (auto id: {p.first, p.second}) if (unsigned seqNr = m_expressionClasses.representative(id).sequenceNumber) @@ -165,7 +164,7 @@ AssemblyItems CSECodeGenerator::generateCode( // @todo quick fix for now. Proper fix needs to choose representative with higher // sequence number during dependency analysis. assertThrow(seqNr >= _initialSequenceNumber, StackTooDeepException, util::stackTooDeepString); - sequencedExpressions.insert(make_pair(seqNr, id)); + sequencedExpressions.insert(std::make_pair(seqNr, id)); } // Perform all operations on storage and memory in order, if they are needed. @@ -230,7 +229,7 @@ void CSECodeGenerator::addDependencies(Id _c) for (Id argument: expr.arguments) { addDependencies(argument); - m_neededBy.insert(make_pair(argument, _c)); + m_neededBy.insert(std::make_pair(argument, _c)); } if (expr.item && expr.item->type() == Operation && ( expr.item->instruction() == Instruction::SLOAD || @@ -294,7 +293,7 @@ void CSECodeGenerator::addDependencies(Id _c) if (it->sequenceNumber < expr.sequenceNumber) latestStore = it->expression; addDependencies(latestStore); - m_neededBy.insert(make_pair(latestStore, _c)); + m_neededBy.insert(std::make_pair(latestStore, _c)); } } } @@ -331,7 +330,7 @@ void CSECodeGenerator::generateClassElement(Id _c, bool _allowSequenced) OptimizerException, "Undefined item requested but not available." ); - vector const& arguments = expr.arguments; + std::vector const& arguments = expr.arguments; for (Id arg: arguments | ranges::views::reverse) generateClassElement(arg); @@ -495,7 +494,7 @@ void CSECodeGenerator::appendOrRemoveSwap(int _fromPosition, SourceLocation cons m_classPositions[m_stack[m_stackHeight]].insert(_fromPosition); m_classPositions[m_stack[_fromPosition]].erase(_fromPosition); m_classPositions[m_stack[_fromPosition]].insert(m_stackHeight); - swap(m_stack[m_stackHeight], m_stack[_fromPosition]); + std::swap(m_stack[m_stackHeight], m_stack[_fromPosition]); } if (m_generatedItems.size() >= 2 && SemanticInformation::isSwapInstruction(m_generatedItems.back()) && diff --git a/libevmasm/ConstantOptimiser.cpp b/libevmasm/ConstantOptimiser.cpp index 5bce21cf1..62dbc803b 100644 --- a/libevmasm/ConstantOptimiser.cpp +++ b/libevmasm/ConstantOptimiser.cpp @@ -24,7 +24,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; @@ -39,11 +38,11 @@ unsigned ConstantOptimisationMethod::optimiseConstants( AssemblyItems& _items = _assembly.items(); unsigned optimisations = 0; - map pushes; + std::map pushes; for (AssemblyItem const& item: _items) if (item.type() == Push) pushes[item]++; - map pendingReplacements; + std::map pendingReplacements; for (auto it: pushes) { AssemblyItem const& item = it.first; @@ -108,7 +107,7 @@ size_t ConstantOptimisationMethod::bytesRequired(AssemblyItems const& _items) void ConstantOptimisationMethod::replaceConstants( AssemblyItems& _items, - map const& _replacements + std::map const& _replacements ) { AssemblyItems replaced; @@ -255,7 +254,7 @@ AssemblyItems ComputeMethod::findRepresentation(u256 const& _value) bool ComputeMethod::checkRepresentation(u256 const& _value, AssemblyItems const& _routine) const { // This is a tiny EVM that can only evaluate some instructions. - vector stack; + std::vector stack; for (AssemblyItem const& item: _routine) { switch (item.type()) diff --git a/libevmasm/ControlFlowGraph.cpp b/libevmasm/ControlFlowGraph.cpp index cb648f90f..9d2927ed9 100644 --- a/libevmasm/ControlFlowGraph.cpp +++ b/libevmasm/ControlFlowGraph.cpp @@ -31,7 +31,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; @@ -64,7 +63,7 @@ void ControlFlowGraph::findLargestTag() { // Assert that it can be converted. BlockId(item.data()); - m_lastUsedId = max(unsigned(item.data()), m_lastUsedId); + m_lastUsedId = std::max(unsigned(item.data()), m_lastUsedId); } } @@ -111,7 +110,7 @@ void ControlFlowGraph::splitBlocks() void ControlFlowGraph::resolveNextLinks() { - map blockByBeginPos; + std::map blockByBeginPos; for (auto const& idAndBlock: m_blocks) if (idAndBlock.second.begin != idAndBlock.second.end) blockByBeginPos[idAndBlock.second.begin] = idAndBlock.first; @@ -138,8 +137,8 @@ void ControlFlowGraph::resolveNextLinks() void ControlFlowGraph::removeUnusedBlocks() { - vector blocksToProcess{BlockId::initial()}; - set neededBlocks{BlockId::initial()}; + std::vector blocksToProcess{BlockId::initial()}; + std::set neededBlocks{BlockId::initial()}; while (!blocksToProcess.empty()) { BasicBlock const& block = m_blocks.at(blocksToProcess.back()); @@ -219,16 +218,16 @@ void ControlFlowGraph::gatherKnowledge() { // @todo actually we know that memory is filled with zeros at the beginning, // we could make use of that. - KnownStatePointer emptyState = make_shared(); + KnownStatePointer emptyState = std::make_shared(); bool unknownJumpEncountered = false; struct WorkQueueItem { BlockId blockId; KnownStatePointer state; - set blocksSeen; + std::set blocksSeen; }; - vector workQueue{WorkQueueItem{BlockId::initial(), emptyState->copy(), set()}}; + std::vector workQueue{WorkQueueItem{BlockId::initial(), emptyState->copy(), std::set()}}; auto addWorkQueueItem = [&](WorkQueueItem const& _currentItem, BlockId _to, KnownStatePointer const& _state) { WorkQueueItem item; @@ -275,7 +274,7 @@ void ControlFlowGraph::gatherKnowledge() assertThrow(block.begin <= pc && pc == block.end - 1, OptimizerException, ""); //@todo in the case of JUMPI, add knowledge about the condition to the state // (for both values of the condition) - set tags = state->tagsInExpression( + std::set tags = state->tagsInExpression( state->stackElement(state->stackHeight(), langutil::SourceLocation{}) ); state->feedItem(m_items.at(pc++)); @@ -289,7 +288,7 @@ void ControlFlowGraph::gatherKnowledge() unknownJumpEncountered = true; for (auto const& it: m_blocks) if (it.second.begin < it.second.end && m_items[it.second.begin].type() == Tag) - workQueue.push_back(WorkQueueItem{it.first, emptyState->copy(), set()}); + workQueue.push_back(WorkQueueItem{it.first, emptyState->copy(), std::set()}); } } else @@ -321,16 +320,16 @@ void ControlFlowGraph::gatherKnowledge() BasicBlocks ControlFlowGraph::rebuildCode() { - map pushes; + std::map pushes; for (auto& idAndBlock: m_blocks) for (BlockId ref: idAndBlock.second.pushedTags) if (m_blocks.count(ref)) pushes[ref]++; - set blocksToAdd; + std::set blocksToAdd; for (auto it: m_blocks) blocksToAdd.insert(it.first); - set blocksAdded; + std::set blocksAdded; BasicBlocks blocks; for ( diff --git a/libevmasm/Disassemble.cpp b/libevmasm/Disassemble.cpp index f1c904b69..27e860661 100644 --- a/libevmasm/Disassemble.cpp +++ b/libevmasm/Disassemble.cpp @@ -22,7 +22,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; @@ -31,7 +30,7 @@ using namespace solidity::evmasm; void solidity::evmasm::eachInstruction( bytes const& _mem, langutil::EVMVersion _evmVersion, - function const& _onInstruction + std::function const& _onInstruction ) { for (auto it = _mem.begin(); it < _mem.end(); ++it) @@ -58,9 +57,9 @@ void solidity::evmasm::eachInstruction( } } -string solidity::evmasm::disassemble(bytes const& _mem, langutil::EVMVersion _evmVersion, string const& _delimiter) +std::string solidity::evmasm::disassemble(bytes const& _mem, langutil::EVMVersion _evmVersion, std::string const& _delimiter) { - stringstream ret; + std::stringstream ret; eachInstruction(_mem, _evmVersion, [&](Instruction _instr, u256 const& _data) { if (!isValidInstruction(_instr)) ret << "0x" << std::uppercase << std::hex << static_cast(_instr) << _delimiter; diff --git a/libevmasm/ExpressionClasses.cpp b/libevmasm/ExpressionClasses.cpp index 8cd97b6a8..dd66eea32 100644 --- a/libevmasm/ExpressionClasses.cpp +++ b/libevmasm/ExpressionClasses.cpp @@ -34,7 +34,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; @@ -58,10 +57,10 @@ bool ExpressionClasses::Expression::operator==(ExpressionClasses::Expression con std::tie(_other.item->data(), _other.arguments, _other.sequenceNumber); } -std::size_t ExpressionClasses::Expression::ExpressionHash::operator()(Expression const& _expression) const +size_t ExpressionClasses::Expression::ExpressionHash::operator()(Expression const& _expression) const { assertThrow(!!_expression.item, OptimizerException, ""); - std::size_t seed = 0; + size_t seed = 0; auto type = _expression.item->type(); boost::hash_combine(seed, type); @@ -171,7 +170,7 @@ bool ExpressionClasses::knownNonZero(Id _c) u256 const* ExpressionClasses::knownConstant(Id _c) { - map matchGroups; + std::map matchGroups; Pattern constant(Push); constant.setMatchGroup(1, matchGroups); if (!constant.matches(representative(_c), *this)) @@ -181,15 +180,15 @@ u256 const* ExpressionClasses::knownConstant(Id _c) AssemblyItem const* ExpressionClasses::storeItem(AssemblyItem const& _item) { - m_spareAssemblyItems.push_back(make_shared(_item)); + m_spareAssemblyItems.push_back(std::make_shared(_item)); return m_spareAssemblyItems.back().get(); } -string ExpressionClasses::fullDAGToString(ExpressionClasses::Id _id) const +std::string ExpressionClasses::fullDAGToString(ExpressionClasses::Id _id) const { Expression const& expr = representative(_id); - stringstream str; - str << dec << expr.id << ":"; + std::stringstream str; + str << std::dec << expr.id << ":"; if (expr.item) { str << *expr.item << "("; @@ -212,25 +211,25 @@ ExpressionClasses::Id ExpressionClasses::tryToSimplify(Expression const& _expr) _expr.item->type() != Operation || !SemanticInformation::isDeterministic(*_expr.item) ) - return numeric_limits::max(); + return std::numeric_limits::max(); if (auto match = rules.findFirstMatch(_expr, *this)) { // Debug info if (false) { - cout << "Simplifying " << *_expr.item << "("; + std::cout << "Simplifying " << *_expr.item << "("; for (Id arg: _expr.arguments) - cout << fullDAGToString(arg) << ", "; - cout << ")" << endl; - cout << "with rule " << match->pattern.toString() << endl; - cout << "to " << match->action().toString() << endl; + std::cout << fullDAGToString(arg) << ", "; + std::cout << ")" << std::endl; + std::cout << "with rule " << match->pattern.toString() << std::endl; + std::cout << "to " << match->action().toString() << std::endl; } return rebuildExpression(ExpressionTemplate(match->action(), _expr.item->location())); } - return numeric_limits::max(); + return std::numeric_limits::max(); } ExpressionClasses::Id ExpressionClasses::rebuildExpression(ExpressionTemplate const& _template) diff --git a/libevmasm/GasMeter.cpp b/libevmasm/GasMeter.cpp index 6a0c597db..271a6ce2d 100644 --- a/libevmasm/GasMeter.cpp +++ b/libevmasm/GasMeter.cpp @@ -20,7 +20,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; @@ -32,7 +31,7 @@ GasMeter::GasConsumption& GasMeter::GasConsumption::operator+=(GasConsumption co if (isInfinite) return *this; bigint v = bigint(value) + _other.value; - if (v > numeric_limits::max()) + if (v > std::numeric_limits::max()) *this = infinite(); else value = u256(v); diff --git a/libevmasm/Inliner.cpp b/libevmasm/Inliner.cpp index d365e312a..ded5172dd 100644 --- a/libevmasm/Inliner.cpp +++ b/libevmasm/Inliner.cpp @@ -38,7 +38,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; @@ -54,7 +53,7 @@ u256 executionCost(RangeType const& _itemRange, langutil::EVMVersion _evmVersion [&gasMeter](auto const& _item) { return gasMeter.estimateMax(_item, false); } ), GasMeter::GasConsumption()); if (gasConsumption.isInfinite) - return numeric_limits::max(); + return std::numeric_limits::max(); else return gasConsumption.value; } @@ -66,14 +65,14 @@ uint64_t codeSize(RangeType const& _itemRange) [](auto const& _item) { return _item.bytesRequired(2, Precision::Approximate); } ), 0u); } -/// @returns the tag id, if @a _item is a PushTag or Tag into the current subassembly, nullopt otherwise. -optional getLocalTag(AssemblyItem const& _item) +/// @returns the tag id, if @a _item is a PushTag or Tag into the current subassembly, std::nullopt otherwise. +std::optional getLocalTag(AssemblyItem const& _item) { if (_item.type() != PushTag && _item.type() != Tag) - return nullopt; + return std::nullopt; auto [subId, tag] = _item.splitForeignPushTag(); - if (subId != numeric_limits::max()) - return nullopt; + if (subId != std::numeric_limits::max()) + return std::nullopt; return tag; } } @@ -99,7 +98,7 @@ bool Inliner::isInlineCandidate(size_t _tag, ranges::span _i return true; } -map Inliner::determineInlinableBlocks(AssemblyItems const& _items) const +std::map Inliner::determineInlinableBlocks(AssemblyItems const& _items) const { std::map> inlinableBlockItems; std::map numPushTags; @@ -108,7 +107,7 @@ map Inliner::determineInlinableBlocks(AssemblyI { // The number of PushTags approximates the number of calls to a block. if (item.type() == PushTag) - if (optional tag = getLocalTag(item)) + if (std::optional tag = getLocalTag(item)) ++numPushTags[*tag]; // We can only inline blocks with straight control flow that end in a jump. @@ -116,7 +115,7 @@ map Inliner::determineInlinableBlocks(AssemblyI if (lastTag && SemanticInformation::breaksCSEAnalysisBlock(item, false)) { ranges::span block = _items | ranges::views::slice(*lastTag + 1, index + 1); - if (optional tag = getLocalTag(_items[*lastTag])) + if (std::optional tag = getLocalTag(_items[*lastTag])) if (isInlineCandidate(*tag, block)) inlinableBlockItems[*tag] = block; lastTag.reset(); @@ -130,7 +129,7 @@ map Inliner::determineInlinableBlocks(AssemblyI } // Store the number of PushTags alongside the assembly items and discard tags that are never pushed. - map result; + std::map result; for (auto&& [tag, items]: inlinableBlockItems) if (uint64_t const* numPushes = util::valueOrNullptr(numPushTags, tag)) result.emplace(tag, InlinableBlock{items, *numPushes}); @@ -199,7 +198,7 @@ bool Inliner::shouldInlineFullFunctionBody(size_t _tag, ranges::span Inliner::shouldInline(size_t _tag, AssemblyItem const& _jump, InlinableBlock const& _block) const +std::optional Inliner::shouldInline(size_t _tag, AssemblyItem const& _jump, InlinableBlock const& _block) const { assertThrow(_jump == Instruction::JUMP, OptimizerException, ""); AssemblyItem blockExit = _block.items.back(); @@ -232,7 +231,7 @@ optional Inliner::shouldInline(size_t _tag, AssemblyItem const& _j return blockExit; } - return nullopt; + return std::nullopt; } @@ -252,7 +251,7 @@ void Inliner::optimise() AssemblyItem const& nextItem = *next(it); if (item.type() == PushTag && nextItem == Instruction::JUMP) { - if (optional tag = getLocalTag(item)) + if (std::optional tag = getLocalTag(item)) if (auto* inlinableBlock = util::valueOrNullptr(inlinableBlocks, *tag)) if (auto exitItem = shouldInline(*tag, nextItem, *inlinableBlock)) { @@ -264,7 +263,7 @@ void Inliner::optimise() // We might increase the number of push tags to other blocks. for (AssemblyItem const& inlinedItem: inlinableBlock->items) if (inlinedItem.type() == PushTag) - if (optional duplicatedTag = getLocalTag(inlinedItem)) + if (std::optional duplicatedTag = getLocalTag(inlinedItem)) if (auto* block = util::valueOrNullptr(inlinableBlocks, *duplicatedTag)) ++block->pushTagCount; diff --git a/libevmasm/Instruction.cpp b/libevmasm/Instruction.cpp index 2c313fd75..174d12b5e 100644 --- a/libevmasm/Instruction.cpp +++ b/libevmasm/Instruction.cpp @@ -22,7 +22,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; @@ -335,7 +334,7 @@ InstructionInfo solidity::evmasm::instructionInfo(Instruction _inst, langutil::E } catch (...) { - return InstructionInfo({"(_inst)) + ">", 0, 0, 0, false, Tier::Invalid}); + return InstructionInfo({"(_inst)) + ">", 0, 0, 0, false, Tier::Invalid}); } } diff --git a/libevmasm/JumpdestRemover.cpp b/libevmasm/JumpdestRemover.cpp index 2c0c5875e..7afa715a8 100644 --- a/libevmasm/JumpdestRemover.cpp +++ b/libevmasm/JumpdestRemover.cpp @@ -26,14 +26,13 @@ #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; -bool JumpdestRemover::optimise(set const& _tagsReferencedFromOutside) +bool JumpdestRemover::optimise(std::set const& _tagsReferencedFromOutside) { - set references{referencedTags(m_items, numeric_limits::max())}; + std::set references{referencedTags(m_items, std::numeric_limits::max())}; references.insert(_tagsReferencedFromOutside.begin(), _tagsReferencedFromOutside.end()); size_t initialSize = m_items.size(); @@ -46,7 +45,7 @@ bool JumpdestRemover::optimise(set const& _tagsReferencedFromOutside) if (_item.type() != Tag) return false; auto asmIdAndTag = _item.splitForeignPushTag(); - assertThrow(asmIdAndTag.first == numeric_limits::max(), OptimizerException, "Sub-assembly tag used as label."); + assertThrow(asmIdAndTag.first == std::numeric_limits::max(), OptimizerException, "Sub-assembly tag used as label."); size_t tag = asmIdAndTag.second; return !references.count(tag); } @@ -55,9 +54,9 @@ bool JumpdestRemover::optimise(set const& _tagsReferencedFromOutside) return m_items.size() != initialSize; } -set JumpdestRemover::referencedTags(AssemblyItems const& _items, size_t _subId) +std::set JumpdestRemover::referencedTags(AssemblyItems const& _items, size_t _subId) { - set ret; + std::set ret; for (auto const& item: _items) if (item.type() == PushTag) { diff --git a/libevmasm/KnownState.cpp b/libevmasm/KnownState.cpp index a2bda5af7..91f798bf3 100644 --- a/libevmasm/KnownState.cpp +++ b/libevmasm/KnownState.cpp @@ -28,17 +28,16 @@ #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; -ostream& KnownState::stream(ostream& _out) const +std::ostream& KnownState::stream(std::ostream& _out) const { - auto streamExpressionClass = [this](ostream& _out, Id _id) + auto streamExpressionClass = [this](std::ostream& _out, Id _id) { auto const& expr = m_expressionClasses->representative(_id); - _out << " " << dec << _id << ": "; + _out << " " << std::dec << _id << ": "; if (!expr.item) _out << " no item"; else if (expr.item->type() == UndefinedItem) @@ -46,26 +45,26 @@ ostream& KnownState::stream(ostream& _out) const else _out << *expr.item; if (expr.sequenceNumber) - _out << "@" << dec << expr.sequenceNumber; + _out << "@" << std::dec << expr.sequenceNumber; _out << "("; for (Id arg: expr.arguments) - _out << dec << arg << ","; - _out << ")" << endl; + _out << std::dec << arg << ","; + _out << ")" << std::endl; }; - _out << "=== State ===" << endl; - _out << "Stack height: " << dec << m_stackHeight << endl; - _out << "Equivalence classes:" << endl; + _out << "=== State ===" << std::endl; + _out << "Stack height: " << std::dec << m_stackHeight << std::endl; + _out << "Equivalence classes:" << std::endl; for (Id eqClass = 0; eqClass < m_expressionClasses->size(); ++eqClass) streamExpressionClass(_out, eqClass); - _out << "Stack:" << endl; + _out << "Stack:" << std::endl; for (auto const& it: m_stackElements) { - _out << " " << dec << it.first << ": "; + _out << " " << std::dec << it.first << ": "; streamExpressionClass(_out, it.second); } - _out << "Storage:" << endl; + _out << "Storage:" << std::endl; for (auto const& it: m_storageContent) { _out << " "; @@ -73,7 +72,7 @@ ostream& KnownState::stream(ostream& _out) const _out << ": "; streamExpressionClass(_out, it.second); } - _out << "Memory:" << endl; + _out << "Memory:" << std::endl; for (auto const& it: m_memoryContent) { _out << " "; @@ -149,7 +148,7 @@ KnownState::StoreOperation KnownState::feedItem(AssemblyItem const& _item, bool ); else if (instruction != Instruction::POP) { - vector arguments(static_cast(info.args)); + std::vector arguments(static_cast(info.args)); for (size_t i = 0; i < static_cast(info.args); ++i) arguments[i] = stackElement(m_stackHeight - static_cast(i), _item.location()); switch (_item.instruction()) @@ -233,8 +232,8 @@ void KnownState::reduceToCommonKnowledge(KnownState const& _other, bool _combine ++it; else { - set theseTags = tagsInExpression(it->second); - set otherTags = tagsInExpression(other); + std::set theseTags = tagsInExpression(it->second); + std::set otherTags = tagsInExpression(other); if (!theseTags.empty() && !otherTags.empty()) { theseTags.insert(otherTags.begin(), otherTags.end()); @@ -251,7 +250,7 @@ void KnownState::reduceToCommonKnowledge(KnownState const& _other, bool _combine // Use the smaller stack height. Essential to terminate in case of loops. if (m_stackHeight > _other.m_stackHeight) { - map shiftedStack; + std::map shiftedStack; for (auto const& stackElement: m_stackElements) shiftedStack[stackElement.first - stackDiff] = stackElement.second; m_stackElements = std::move(shiftedStack); @@ -261,7 +260,7 @@ void KnownState::reduceToCommonKnowledge(KnownState const& _other, bool _combine intersect(m_storageContent, _other.m_storageContent); intersect(m_memoryContent, _other.m_memoryContent); if (_combineSequenceNumbers) - m_sequenceNumber = max(m_sequenceNumber, _other.m_sequenceNumber); + m_sequenceNumber = std::max(m_sequenceNumber, _other.m_sequenceNumber); } bool KnownState::operator==(KnownState const& _other) const @@ -316,7 +315,7 @@ void KnownState::swapStackElements( stackElement(_stackHeightA, _location); stackElement(_stackHeightB, _location); - swap(m_stackElements[_stackHeightA], m_stackElements[_stackHeightB]); + std::swap(m_stackElements[_stackHeightA], m_stackElements[_stackHeightB]); } KnownState::StoreOperation KnownState::storeInStorage( @@ -400,7 +399,7 @@ KnownState::Id KnownState::applyKeccak256( if (!l || *l > 128) return m_expressionClasses->find(keccak256Item, {_start, _length}, true, m_sequenceNumber); unsigned length = unsigned(*l); - vector arguments; + std::vector arguments; for (unsigned i = 0; i < length; i += 32) { Id slot = m_expressionClasses->find( @@ -426,19 +425,19 @@ KnownState::Id KnownState::applyKeccak256( return m_knownKeccak256Hashes[{arguments, length}] = v; } -set KnownState::tagsInExpression(KnownState::Id _expressionId) +std::set KnownState::tagsInExpression(KnownState::Id _expressionId) { if (m_tagUnions.left.count(_expressionId)) return m_tagUnions.left.at(_expressionId); // Might be a tag, then return the set of itself. ExpressionClasses::Expression expr = m_expressionClasses->representative(_expressionId); if (expr.item && expr.item->type() == PushTag) - return set({expr.item->data()}); + return std::set({expr.item->data()}); else - return set(); + return std::set(); } -KnownState::Id KnownState::tagUnion(set _tags) +KnownState::Id KnownState::tagUnion(std::set _tags) { if (m_tagUnions.right.count(_tags)) return m_tagUnions.right.at(_tags); diff --git a/libevmasm/LinkerObject.cpp b/libevmasm/LinkerObject.cpp index 5a0631e32..1b09f4ced 100644 --- a/libevmasm/LinkerObject.cpp +++ b/libevmasm/LinkerObject.cpp @@ -24,7 +24,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; @@ -36,24 +35,24 @@ void LinkerObject::append(LinkerObject const& _other) bytecode += _other.bytecode; } -void LinkerObject::link(map const& _libraryAddresses) +void LinkerObject::link(std::map const& _libraryAddresses) { std::map remainingRefs; for (auto const& linkRef: linkReferences) if (h160 const* address = matchLibrary(linkRef.second, _libraryAddresses)) - copy(address->data(), address->data() + 20, bytecode.begin() + vector::difference_type(linkRef.first)); + copy(address->data(), address->data() + 20, bytecode.begin() + std::vector::difference_type(linkRef.first)); else remainingRefs.insert(linkRef); linkReferences.swap(remainingRefs); } -string LinkerObject::toHex() const +std::string LinkerObject::toHex() const { - string hex = solidity::util::toHex(bytecode); + std::string hex = solidity::util::toHex(bytecode); for (auto const& ref: linkReferences) { size_t pos = ref.first * 2; - string hash = libraryPlaceholder(ref.second); + std::string hash = libraryPlaceholder(ref.second); hex[pos] = hex[pos + 1] = hex[pos + 38] = hex[pos + 39] = '_'; for (size_t i = 0; i < 36; ++i) hex[pos + 2 + i] = hash.at(i); @@ -61,15 +60,15 @@ string LinkerObject::toHex() const return hex; } -string LinkerObject::libraryPlaceholder(string const& _libraryName) +std::string LinkerObject::libraryPlaceholder(std::string const& _libraryName) { return "$" + keccak256(_libraryName).hex().substr(0, 34) + "$"; } h160 const* LinkerObject::matchLibrary( - string const& _linkRefName, - map const& _libraryAddresses + std::string const& _linkRefName, + std::map const& _libraryAddresses ) { auto it = _libraryAddresses.find(_linkRefName); diff --git a/libevmasm/PathGasMeter.cpp b/libevmasm/PathGasMeter.cpp index c165985cf..2acafea22 100644 --- a/libevmasm/PathGasMeter.cpp +++ b/libevmasm/PathGasMeter.cpp @@ -24,7 +24,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; @@ -38,17 +37,17 @@ PathGasMeter::PathGasMeter(AssemblyItems const& _items, langutil::EVMVersion _ev GasMeter::GasConsumption PathGasMeter::estimateMax( size_t _startIndex, - shared_ptr const& _state + std::shared_ptr const& _state ) { - auto path = make_unique(); + auto path = std::make_unique(); path->index = _startIndex; path->state = _state->copy(); queue(std::move(path)); GasMeter::GasConsumption gas; while (!m_queue.empty() && !gas.isInfinite) - gas = max(gas, handleQueueItem()); + gas = std::max(gas, handleQueueItem()); return gas; } @@ -67,10 +66,10 @@ GasMeter::GasConsumption PathGasMeter::handleQueueItem() { assertThrow(!m_queue.empty(), OptimizerException, ""); - unique_ptr path = std::move(m_queue.rbegin()->second); + std::unique_ptr path = std::move(m_queue.rbegin()->second); m_queue.erase(--m_queue.end()); - shared_ptr state = path->state; + std::shared_ptr state = path->state; GasMeter meter(state, m_evmVersion, path->largestMemoryAccess); ExpressionClasses& classes = state->expressionClasses(); GasMeter::GasConsumption gas = path->gas; @@ -82,7 +81,7 @@ GasMeter::GasConsumption PathGasMeter::handleQueueItem() // return the current gas value. return gas; - set jumpTags; + std::set jumpTags; for (; index < m_items.size() && !gas.isInfinite; ++index) { bool branchStops = false; @@ -121,7 +120,7 @@ GasMeter::GasConsumption PathGasMeter::handleQueueItem() for (u256 const& tag: jumpTags) { - auto newPath = make_unique(); + auto newPath = std::make_unique(); newPath->index = m_items.size(); if (m_tagPositions.count(tag)) newPath->index = m_tagPositions.at(tag); diff --git a/libevmasm/PeepholeOptimiser.cpp b/libevmasm/PeepholeOptimiser.cpp index 22d40c8ea..e9231c0a5 100644 --- a/libevmasm/PeepholeOptimiser.cpp +++ b/libevmasm/PeepholeOptimiser.cpp @@ -25,7 +25,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; @@ -38,7 +37,7 @@ struct OptimiserState { AssemblyItems const& items; size_t i; - back_insert_iterator out; + std::back_insert_iterator out; }; template @@ -55,8 +54,8 @@ struct SimplePeepholeOptimizerMethod template static bool applyRule( AssemblyItems::const_iterator _in, - back_insert_iterator _out, - index_sequence + std::back_insert_iterator _out, + std::index_sequence ) { return Method::applySimple(_in[Indices]..., _out); @@ -66,7 +65,7 @@ struct SimplePeepholeOptimizerMethod static constexpr size_t WindowSize = FunctionParameterCount::value - 1; if ( _state.i + WindowSize <= _state.items.size() && - applyRule(_state.items.begin() + static_cast(_state.i), _state.out, make_index_sequence{}) + applyRule(_state.items.begin() + static_cast(_state.i), _state.out, std::make_index_sequence{}) ) { _state.i += WindowSize; @@ -81,7 +80,7 @@ struct Identity: SimplePeepholeOptimizerMethod { static bool applySimple( AssemblyItem const& _item, - back_insert_iterator _out + std::back_insert_iterator _out ) { *_out = _item; @@ -94,7 +93,7 @@ struct PushPop: SimplePeepholeOptimizerMethod static bool applySimple( AssemblyItem const& _push, AssemblyItem const& _pop, - back_insert_iterator + std::back_insert_iterator ) { auto t = _push.type(); @@ -111,7 +110,7 @@ struct OpPop: SimplePeepholeOptimizerMethod static bool applySimple( AssemblyItem const& _op, AssemblyItem const& _pop, - back_insert_iterator _out + std::back_insert_iterator _out ) { if (_pop == Instruction::POP && _op.type() == Operation) @@ -133,7 +132,7 @@ struct OpStop: SimplePeepholeOptimizerMethod static bool applySimple( AssemblyItem const& _op, AssemblyItem const& _stop, - back_insert_iterator _out + std::back_insert_iterator _out ) { if (_stop == Instruction::STOP) @@ -164,7 +163,7 @@ struct OpReturnRevert: SimplePeepholeOptimizerMethod AssemblyItem const& _push, AssemblyItem const& _pushOrDup, AssemblyItem const& _returnRevert, - back_insert_iterator _out + std::back_insert_iterator _out ) { if ( @@ -191,7 +190,7 @@ struct DoubleSwap: SimplePeepholeOptimizerMethod static size_t applySimple( AssemblyItem const& _s1, AssemblyItem const& _s2, - back_insert_iterator + std::back_insert_iterator ) { return _s1 == _s2 && SemanticInformation::isSwapInstruction(_s1); @@ -203,7 +202,7 @@ struct DoublePush: SimplePeepholeOptimizerMethod static bool applySimple( AssemblyItem const& _push1, AssemblyItem const& _push2, - back_insert_iterator _out + std::back_insert_iterator _out ) { if (_push1.type() == Push && _push2.type() == Push && _push1.data() == _push2.data()) @@ -222,7 +221,7 @@ struct CommutativeSwap: SimplePeepholeOptimizerMethod static bool applySimple( AssemblyItem const& _swap, AssemblyItem const& _op, - back_insert_iterator _out + std::back_insert_iterator _out ) { // Remove SWAP1 if following instruction is commutative @@ -244,10 +243,10 @@ struct SwapComparison: SimplePeepholeOptimizerMethod static bool applySimple( AssemblyItem const& _swap, AssemblyItem const& _op, - back_insert_iterator _out + std::back_insert_iterator _out ) { - static map const swappableOps{ + static std::map const swappableOps{ { Instruction::LT, Instruction::GT }, { Instruction::GT, Instruction::LT }, { Instruction::SLT, Instruction::SGT }, @@ -274,7 +273,7 @@ struct DupSwap: SimplePeepholeOptimizerMethod static size_t applySimple( AssemblyItem const& _dupN, AssemblyItem const& _swapN, - back_insert_iterator _out + std::back_insert_iterator _out ) { if ( @@ -299,7 +298,7 @@ struct IsZeroIsZeroJumpI: SimplePeepholeOptimizerMethod AssemblyItem const& _iszero2, AssemblyItem const& _pushTag, AssemblyItem const& _jumpi, - back_insert_iterator _out + std::back_insert_iterator _out ) { if ( @@ -325,7 +324,7 @@ struct EqIsZeroJumpI: SimplePeepholeOptimizerMethod AssemblyItem const& _iszero, AssemblyItem const& _pushTag, AssemblyItem const& _jumpi, - back_insert_iterator _out + std::back_insert_iterator _out ) { if ( @@ -354,7 +353,7 @@ struct DoubleJump: SimplePeepholeOptimizerMethod AssemblyItem const& _pushTag2, AssemblyItem const& _jump, AssemblyItem const& _tag1, - back_insert_iterator _out + std::back_insert_iterator _out ) { if ( @@ -383,7 +382,7 @@ struct JumpToNext: SimplePeepholeOptimizerMethod AssemblyItem const& _pushTag, AssemblyItem const& _jump, AssemblyItem const& _tag, - back_insert_iterator _out + std::back_insert_iterator _out ) { if ( @@ -409,7 +408,7 @@ struct TagConjunctions: SimplePeepholeOptimizerMethod AssemblyItem const& _pushTag, AssemblyItem const& _pushConstant, AssemblyItem const& _and, - back_insert_iterator _out + std::back_insert_iterator _out ) { if (_and != Instruction::AND) @@ -444,7 +443,7 @@ struct TruthyAnd: SimplePeepholeOptimizerMethod AssemblyItem const& _push, AssemblyItem const& _not, AssemblyItem const& _and, - back_insert_iterator + std::back_insert_iterator ) { return ( diff --git a/libevmasm/SemanticInformation.cpp b/libevmasm/SemanticInformation.cpp index b6bcc8280..1971d9d45 100644 --- a/libevmasm/SemanticInformation.cpp +++ b/libevmasm/SemanticInformation.cpp @@ -25,11 +25,10 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; -vector SemanticInformation::readWriteOperations(Instruction _instruction) +std::vector SemanticInformation::readWriteOperations(Instruction _instruction) { switch (_instruction) { @@ -111,7 +110,7 @@ vector SemanticInformation::readWriteOperations( case Instruction::DELEGATECALL: { size_t paramCount = static_cast(instructionInfo(_instruction, langutil::EVMVersion()).args); - vector operations{ + std::vector operations{ Operation{Location::Memory, Effect::Read, paramCount - 4, paramCount - 3, {}}, Operation{Location::Storage, Effect::Read, {}, {}, {}} }; @@ -130,7 +129,7 @@ vector SemanticInformation::readWriteOperations( } case Instruction::CREATE: case Instruction::CREATE2: - return vector{ + return std::vector{ Operation{ Location::Memory, Effect::Read, @@ -143,7 +142,7 @@ vector SemanticInformation::readWriteOperations( }; case Instruction::MSIZE: // This is just to satisfy the assert below. - return vector{}; + return std::vector{}; default: assertThrow(storage(_instruction) == None && memory(_instruction) == None, AssemblyException, ""); } diff --git a/libevmasm/SimplificationRules.cpp b/libevmasm/SimplificationRules.cpp index bcb8da388..ef2d68c7f 100644 --- a/libevmasm/SimplificationRules.cpp +++ b/libevmasm/SimplificationRules.cpp @@ -32,7 +32,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; @@ -92,7 +91,7 @@ Rules::Rules() Y.setMatchGroup(6, m_matchGroups); Z.setMatchGroup(7, m_matchGroups); - addRules(simplificationRuleList(nullopt, A, B, C, W, X, Y, Z)); + addRules(simplificationRuleList(std::nullopt, A, B, C, W, X, Y, Z)); assertThrow(isInitialized(), OptimizerException, "Rule list not properly initialized."); } @@ -103,7 +102,7 @@ Pattern::Pattern(Instruction _instruction, std::initializer_list _argum { } -void Pattern::setMatchGroup(unsigned _group, map& _matchGroups) +void Pattern::setMatchGroup(unsigned _group, std::map& _matchGroups) { m_matchGroup = _group; m_matchGroups = &_matchGroups; @@ -135,9 +134,9 @@ AssemblyItem Pattern::toAssemblyItem(SourceLocation const& _location) const return AssemblyItem(m_type, data(), _location); } -string Pattern::toString() const +std::string Pattern::toString() const { - stringstream s; + std::stringstream s; switch (m_type) { case Operation: @@ -146,7 +145,7 @@ string Pattern::toString() const break; case Push: if (m_data) - s << "PUSH " << hex << data(); + s << "PUSH " << std::hex << data(); else s << "PUSH "; break; @@ -155,15 +154,15 @@ string Pattern::toString() const break; default: if (m_data) - s << "t=" << dec << m_type << " d=" << hex << data(); + s << "t=" << std::dec << m_type << " d=" << std::hex << data(); else - s << "t=" << dec << m_type << " d: nullptr"; + s << "t=" << std::dec << m_type << " d: nullptr"; break; } if (!m_requireDataMatch) s << " ~"; if (m_matchGroup) - s << "[" << dec << m_matchGroup << "]"; + s << "[" << std::dec << m_matchGroup << "]"; s << "("; for (Pattern const& p: m_arguments) s << p.toString() << ", "; @@ -216,9 +215,9 @@ ExpressionTemplate::ExpressionTemplate(Pattern const& _pattern, SourceLocation c arguments.emplace_back(arg, _location); } -string ExpressionTemplate::toString() const +std::string ExpressionTemplate::toString() const { - stringstream s; + std::stringstream s; if (hasId) s << id; else