From 342ba0324fafabd5f0e49101b20f365da9eeae86 Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Tue, 15 Aug 2023 10:53:51 +0200 Subject: [PATCH] Purge using namespace std from libsolidity/interface --- libsolidity/interface/ABI.cpp | 19 +- libsolidity/interface/CompilerStack.cpp | 230 ++++++++++----------- libsolidity/interface/FileReader.cpp | 30 ++- libsolidity/interface/GasEstimator.cpp | 19 +- libsolidity/interface/ImportRemapper.cpp | 45 ++-- libsolidity/interface/Natspec.cpp | 40 ++-- libsolidity/interface/SMTSolverCommand.cpp | 9 +- libsolidity/interface/StandardCompiler.cpp | 156 +++++++------- libsolidity/interface/StorageLayout.cpp | 3 +- libsolidity/interface/Version.cpp | 20 +- scripts/check_style.sh | 1 + 11 files changed, 276 insertions(+), 296 deletions(-) diff --git a/libsolidity/interface/ABI.cpp b/libsolidity/interface/ABI.cpp index bfc9c07a5..cf6e863bb 100644 --- a/libsolidity/interface/ABI.cpp +++ b/libsolidity/interface/ABI.cpp @@ -23,7 +23,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::frontend; @@ -42,9 +41,9 @@ bool anyDataStoredInStorage(TypePointers const& _pointers) Json::Value ABI::generate(ContractDefinition const& _contractDef) { auto compare = [](Json::Value const& _a, Json::Value const& _b) -> bool { - return make_tuple(_a["type"], _a["name"]) < make_tuple(_b["type"], _b["name"]); + return std::make_tuple(_a["type"], _a["name"]) < std::make_tuple(_b["type"], _b["name"]); }; - multiset abi(compare); + std::multiset abi(compare); for (auto it: _contractDef.interfaceFunctions()) { @@ -144,9 +143,9 @@ Json::Value ABI::generate(ContractDefinition const& _contractDef) } Json::Value ABI::formatTypeList( - vector const& _names, - vector const& _encodingTypes, - vector const& _solidityTypes, + std::vector const& _names, + std::vector const& _encodingTypes, + std::vector const& _solidityTypes, bool _forLibrary ) { @@ -162,7 +161,7 @@ Json::Value ABI::formatTypeList( } Json::Value ABI::formatType( - string const& _name, + std::string const& _name, Type const& _encodingType, Type const& _solidityType, bool _forLibrary @@ -171,7 +170,7 @@ Json::Value ABI::formatType( Json::Value ret{Json::objectValue}; ret["name"] = _name; ret["internalType"] = _solidityType.toString(true); - string suffix = (_forLibrary && _encodingType.dataStoredIn(DataLocation::Storage)) ? " storage" : ""; + std::string suffix = (_forLibrary && _encodingType.dataStoredIn(DataLocation::Storage)) ? " storage" : ""; if (_encodingType.isValueType() || (_forLibrary && _encodingType.dataStoredIn(DataLocation::Storage))) ret["type"] = _encodingType.canonicalName() + suffix; else if (ArrayType const* arrayType = dynamic_cast(&_encodingType)) @@ -180,11 +179,11 @@ Json::Value ABI::formatType( ret["type"] = _encodingType.canonicalName() + suffix; else { - string suffix; + std::string suffix; if (arrayType->isDynamicallySized()) suffix = "[]"; else - suffix = string("[") + arrayType->length().str() + "]"; + suffix = std::string("[") + arrayType->length().str() + "]"; solAssert(arrayType->baseType(), ""); Json::Value subtype = formatType( "", diff --git a/libsolidity/interface/CompilerStack.cpp b/libsolidity/interface/CompilerStack.cpp index 84f886d72..295811fd0 100644 --- a/libsolidity/interface/CompilerStack.cpp +++ b/libsolidity/interface/CompilerStack.cpp @@ -94,11 +94,11 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; using namespace solidity::stdlib; +using namespace std::string_literals; using solidity::util::errinfo_comment; @@ -132,10 +132,10 @@ void CompilerStack::createAndAssignCallGraphs() ContractDefinitionAnnotation& annotation = m_contracts.at(contract->fullyQualifiedName()).contract->annotation(); - annotation.creationCallGraph = make_unique( + annotation.creationCallGraph = std::make_unique( FunctionCallGraphBuilder::buildCreationGraph(*contract) ); - annotation.deployedCallGraph = make_unique( + annotation.deployedCallGraph = std::make_unique( FunctionCallGraphBuilder::buildDeployedGraph( *contract, **annotation.creationCallGraph @@ -155,7 +155,7 @@ void CompilerStack::createAndAssignCallGraphs() void CompilerStack::findAndReportCyclicContractDependencies() { // Cycles we found, used to avoid duplicate reports for the same reference - set foundCycles; + std::set foundCycles; for (Source const* source: m_sourceOrder) { @@ -208,7 +208,7 @@ void CompilerStack::findAndReportCyclicContractDependencies() } } -void CompilerStack::setRemappings(vector _remappings) +void CompilerStack::setRemappings(std::vector _remappings) { if (m_stackState >= ParsedAndImported) solThrow(CompilerError, "Must set remappings before parsing."); @@ -247,7 +247,7 @@ void CompilerStack::setModelCheckerSettings(ModelCheckerSettings _settings) m_modelCheckerSettings = _settings; } -void CompilerStack::setLibraries(map const& _libraries) +void CompilerStack::setLibraries(std::map const& _libraries) { if (m_stackState >= ParsedAndImported) solThrow(CompilerError, "Must set libraries before parsing."); @@ -271,7 +271,7 @@ void CompilerStack::setOptimiserSettings(OptimiserSettings _settings) void CompilerStack::setRevertStringBehaviour(RevertStrings _revertStrings) { if (m_stackState >= ParsedAndImported) - solThrow(CompilerError, "Must set revert string settings before parsing."); + solThrow(CompilerError, "Must set revert std::string settings before parsing."); solUnimplementedAssert(_revertStrings != RevertStrings::VerboseDebug); m_revertStrings = _revertStrings; } @@ -297,7 +297,7 @@ void CompilerStack::selectDebugInfo(DebugInfoSelection _debugInfoSelection) m_debugInfoSelection = _debugInfoSelection; } -void CompilerStack::addSMTLib2Response(h256 const& _hash, string const& _response) +void CompilerStack::addSMTLib2Response(h256 const& _hash, std::string const& _response) { if (m_stackState >= ParsedAndImported) solThrow(CompilerError, "Must add SMTLib2 responses before parsing."); @@ -340,7 +340,7 @@ void CompilerStack::setSources(StringMap _sources) if (m_stackState != Empty) solThrow(CompilerError, "Must set sources before parsing."); for (auto source: _sources) - m_sources[source.first].charStream = make_unique(/*content*/std::move(source.second), /*name*/source.first); + m_sources[source.first].charStream = std::make_unique(/*content*/std::move(source.second), /*name*/source.first); m_stackState = SourcesSet; } @@ -350,18 +350,18 @@ bool CompilerStack::parse() solThrow(CompilerError, "Must call parse only after the SourcesSet state."); m_errorReporter.clear(); - if (SemVerVersion{string(VersionString)}.isPrerelease()) + if (SemVerVersion{std::string(VersionString)}.isPrerelease()) m_errorReporter.warning(3805_error, "This is a pre-release compiler version, please do not use it in production."); Parser parser{m_errorReporter, m_evmVersion, m_parserErrorRecovery}; - vector sourcesToParse; + std::vector sourcesToParse; for (auto const& s: m_sources) sourcesToParse.push_back(s.first); for (size_t i = 0; i < sourcesToParse.size(); ++i) { - string const& path = sourcesToParse[i]; + std::string const& path = sourcesToParse[i]; Source& source = m_sources[path]; source.ast = parser.parse(*source.charStream); if (!source.ast) @@ -379,7 +379,7 @@ bool CompilerStack::parse() if (it != stdlib::sources.end()) { auto [name, content] = *it; - m_sources[name].charStream = make_unique(content, name); + m_sources[name].charStream = std::make_unique(content, name); sourcesToParse.push_back(name); } @@ -395,9 +395,9 @@ bool CompilerStack::parse() if (m_stopAfter >= ParsedAndImported) for (auto const& newSource: loadMissingSources(*source.ast)) { - string const& newPath = newSource.first; - string const& newContents = newSource.second; - m_sources[newPath].charStream = make_shared(newContents, newPath); + std::string const& newPath = newSource.first; + std::string const& newContents = newSource.second; + m_sources[newPath].charStream = std::make_shared(newContents, newPath); sourcesToParse.push_back(newPath); } } @@ -415,17 +415,17 @@ bool CompilerStack::parse() return !m_hasError; } -void CompilerStack::importASTs(map const& _sources) +void CompilerStack::importASTs(std::map const& _sources) { if (m_stackState != Empty) solThrow(CompilerError, "Must call importASTs only before the SourcesSet state."); - map> reconstructedSources = ASTJsonImporter(m_evmVersion).jsonToSourceUnit(_sources); + std::map> reconstructedSources = ASTJsonImporter(m_evmVersion).jsonToSourceUnit(_sources); for (auto& src: reconstructedSources) { - string const& path = src.first; + std::string const& path = src.first; Source source; source.ast = src.second; - source.charStream = make_shared( + source.charStream = std::make_shared( util::jsonCompactPrint(_sources.at(src.first)), src.first, true // imported from AST @@ -459,14 +459,14 @@ bool CompilerStack::analyze() if (source->ast && !syntaxChecker.checkSyntax(*source->ast)) noErrors = false; - m_globalContext = make_shared(); + m_globalContext = std::make_shared(); // We need to keep the same resolver during the whole process. NameAndTypeResolver resolver(*m_globalContext, m_evmVersion, m_errorReporter); for (Source const* source: m_sourceOrder) if (source->ast && !resolver.registerDeclarations(*source->ast)) return false; - map sourceUnitsByName; + std::map sourceUnitsByName; for (auto& source: m_sources) sourceUnitsByName[source.first] = source.second.ast.get(); for (Source const* source: m_sourceOrder) @@ -591,7 +591,7 @@ bool CompilerStack::analyze() if (noErrors) { // Check for state mutability in every function. - vector> ast; + std::vector> ast; for (Source const* source: m_sourceOrder) if (source->ast) ast.push_back(source->ast); @@ -647,7 +647,7 @@ bool CompilerStack::parseAndAnalyze(State _stopAfter) return success; } -bool CompilerStack::isRequestedSource(string const& _sourceName) const +bool CompilerStack::isRequestedSource(std::string const& _sourceName) const { return m_requestedContractNames.empty() || @@ -661,7 +661,7 @@ bool CompilerStack::isRequestedContract(ContractDefinition const& _contract) con if (m_requestedContractNames.empty()) return true; - for (auto const& key: vector{"", _contract.sourceUnitName()}) + for (auto const& key: std::vector{"", _contract.sourceUnitName()}) { auto const& it = m_requestedContractNames.find(key); if (it != m_requestedContractNames.end()) @@ -686,7 +686,7 @@ bool CompilerStack::compile(State _stopAfter) solThrow(CompilerError, "Called compile with errors."); // Only compile contracts individually which have been requested. - map> otherCompilers; + std::map> otherCompilers; for (Source const* source: m_sourceOrder) for (ASTPointer const& node: source->ast->nodes()) @@ -719,7 +719,7 @@ bool CompilerStack::compile(State _stopAfter) boost::get_error_info(_unimplementedError) ) { - string const* comment = _unimplementedError.comment(); + std::string const* comment = _unimplementedError.comment(); m_errorReporter.error( 1834_error, Error::Type::CodeGenerationError, @@ -751,22 +751,22 @@ void CompilerStack::link() } } -vector CompilerStack::contractNames() const +std::vector CompilerStack::contractNames() const { if (m_stackState < Parsed) solThrow(CompilerError, "Parsing was not successful."); - vector contractNames; + std::vector contractNames; for (auto const& contract: m_contracts) contractNames.push_back(contract.first); return contractNames; } -string const CompilerStack::lastContractName(optional const& _sourceName) const +std::string const CompilerStack::lastContractName(std::optional const& _sourceName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Parsing was not successful."); // try to find some user-supplied contract - string contractName; + std::string contractName; for (auto const& it: m_sources) if (_sourceName.value_or(it.first) == it.first) for (auto const* contract: ASTNode::filteredNodes(it.second.ast->nodes())) @@ -774,7 +774,7 @@ string const CompilerStack::lastContractName(optional const& _sourceName return contractName; } -evmasm::AssemblyItems const* CompilerStack::assemblyItems(string const& _contractName) const +evmasm::AssemblyItems const* CompilerStack::assemblyItems(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -783,7 +783,7 @@ evmasm::AssemblyItems const* CompilerStack::assemblyItems(string const& _contrac return currentContract.evmAssembly ? ¤tContract.evmAssembly->items() : nullptr; } -evmasm::AssemblyItems const* CompilerStack::runtimeAssemblyItems(string const& _contractName) const +evmasm::AssemblyItems const* CompilerStack::runtimeAssemblyItems(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -792,7 +792,7 @@ evmasm::AssemblyItems const* CompilerStack::runtimeAssemblyItems(string const& _ return currentContract.evmRuntimeAssembly ? ¤tContract.evmRuntimeAssembly->items() : nullptr; } -Json::Value CompilerStack::generatedSources(string const& _contractName, bool _runtime) const +Json::Value CompilerStack::generatedSources(std::string const& _contractName, bool _runtime) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -809,19 +809,19 @@ Json::Value CompilerStack::generatedSources(string const& _contractName, bool _r if (c.compiler) { solAssert(!m_viaIR, ""); - string source = + std::string source = _runtime ? c.compiler->runtimeGeneratedYulUtilityCode() : c.compiler->generatedYulUtilityCode(); if (!source.empty()) { - string sourceName = CompilerContext::yulUtilityFileName(); + std::string sourceName = CompilerContext::yulUtilityFileName(); unsigned sourceIndex = sourceIndices()[sourceName]; ErrorList errors; ErrorReporter errorReporter(errors); CharStream charStream(source, sourceName); yul::EVMDialect const& dialect = yul::EVMDialect::strictAssemblyForEVM(m_evmVersion); - shared_ptr parserResult = yul::Parser{errorReporter, dialect}.parse(charStream); + std::shared_ptr parserResult = yul::Parser{errorReporter, dialect}.parse(charStream); solAssert(parserResult, ""); sources[0]["ast"] = yul::AsmJsonConverter{sourceIndex}(*parserResult); sources[0]["name"] = sourceName; @@ -834,7 +834,7 @@ Json::Value CompilerStack::generatedSources(string const& _contractName, bool _r }); } -string const* CompilerStack::sourceMapping(string const& _contractName) const +std::string const* CompilerStack::sourceMapping(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -848,7 +848,7 @@ string const* CompilerStack::sourceMapping(string const& _contractName) const return c.sourceMapping ? &*c.sourceMapping : nullptr; } -string const* CompilerStack::runtimeSourceMapping(string const& _contractName) const +std::string const* CompilerStack::runtimeSourceMapping(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -864,7 +864,7 @@ string const* CompilerStack::runtimeSourceMapping(string const& _contractName) c return c.runtimeSourceMapping ? &*c.runtimeSourceMapping : nullptr; } -string const CompilerStack::filesystemFriendlyName(string const& _contractName) const +std::string const CompilerStack::filesystemFriendlyName(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "No compiled contracts found."); @@ -878,7 +878,7 @@ string const CompilerStack::filesystemFriendlyName(string const& _contractName) contract.second.contract != matchContract.contract) { // If it does, then return its fully-qualified name, made fs-friendly - string friendlyName = boost::algorithm::replace_all_copy(_contractName, "/", "_"); + std::string friendlyName = boost::algorithm::replace_all_copy(_contractName, "/", "_"); boost::algorithm::replace_all(friendlyName, ":", "_"); boost::algorithm::replace_all(friendlyName, ".", "_"); return friendlyName; @@ -888,7 +888,7 @@ string const CompilerStack::filesystemFriendlyName(string const& _contractName) return matchContract.contract->name(); } -string const& CompilerStack::yulIR(string const& _contractName) const +std::string const& CompilerStack::yulIR(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -896,7 +896,7 @@ string const& CompilerStack::yulIR(string const& _contractName) const return contract(_contractName).yulIR; } -Json::Value const& CompilerStack::yulIRAst(string const& _contractName) const +Json::Value const& CompilerStack::yulIRAst(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -904,7 +904,7 @@ Json::Value const& CompilerStack::yulIRAst(string const& _contractName) const return contract(_contractName).yulIRAst; } -string const& CompilerStack::yulIROptimized(string const& _contractName) const +std::string const& CompilerStack::yulIROptimized(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -912,7 +912,7 @@ string const& CompilerStack::yulIROptimized(string const& _contractName) const return contract(_contractName).yulIROptimized; } -Json::Value const& CompilerStack::yulIROptimizedAst(string const& _contractName) const +Json::Value const& CompilerStack::yulIROptimizedAst(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -920,7 +920,7 @@ Json::Value const& CompilerStack::yulIROptimizedAst(string const& _contractName) return contract(_contractName).yulIROptimizedAst; } -evmasm::LinkerObject const& CompilerStack::object(string const& _contractName) const +evmasm::LinkerObject const& CompilerStack::object(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -928,7 +928,7 @@ evmasm::LinkerObject const& CompilerStack::object(string const& _contractName) c return contract(_contractName).object; } -evmasm::LinkerObject const& CompilerStack::runtimeObject(string const& _contractName) const +evmasm::LinkerObject const& CompilerStack::runtimeObject(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -936,8 +936,8 @@ evmasm::LinkerObject const& CompilerStack::runtimeObject(string const& _contract return contract(_contractName).runtimeObject; } -/// TODO: cache this string -string CompilerStack::assemblyString(string const& _contractName, StringMap const& _sourceCodes) const +/// TODO: cache this std::string +std::string CompilerStack::assemblyString(std::string const& _contractName, StringMap const& _sourceCodes) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -946,11 +946,11 @@ string CompilerStack::assemblyString(string const& _contractName, StringMap cons if (currentContract.evmAssembly) return currentContract.evmAssembly->assemblyString(m_debugInfoSelection, _sourceCodes); else - return string(); + return std::string(); } /// TODO: cache the JSON -Json::Value CompilerStack::assemblyJSON(string const& _contractName) const +Json::Value CompilerStack::assemblyJSON(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -962,14 +962,14 @@ Json::Value CompilerStack::assemblyJSON(string const& _contractName) const return Json::Value(); } -vector CompilerStack::sourceNames() const +std::vector CompilerStack::sourceNames() const { - return ranges::to(m_sources | ranges::views::keys); + return ranges::to(m_sources | ranges::views::keys); } -map CompilerStack::sourceIndices() const +std::map CompilerStack::sourceIndices() const { - map indices; + std::map indices; unsigned index = 0; for (auto const& s: m_sources) indices[s.first] = index++; @@ -978,7 +978,7 @@ map CompilerStack::sourceIndices() const return indices; } -Json::Value const& CompilerStack::contractABI(string const& _contractName) const +Json::Value const& CompilerStack::contractABI(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -996,7 +996,7 @@ Json::Value const& CompilerStack::contractABI(Contract const& _contract) const return _contract.abi.init([&]{ return ABI::generate(*_contract.contract); }); } -Json::Value const& CompilerStack::storageLayout(string const& _contractName) const +Json::Value const& CompilerStack::storageLayout(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1014,7 +1014,7 @@ Json::Value const& CompilerStack::storageLayout(Contract const& _contract) const return _contract.storageLayout.init([&]{ return StorageLayout().generate(*_contract.contract); }); } -Json::Value const& CompilerStack::natspecUser(string const& _contractName) const +Json::Value const& CompilerStack::natspecUser(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1032,7 +1032,7 @@ Json::Value const& CompilerStack::natspecUser(Contract const& _contract) const return _contract.userDocumentation.init([&]{ return Natspec::userDocumentation(*_contract.contract); }); } -Json::Value const& CompilerStack::natspecDev(string const& _contractName) const +Json::Value const& CompilerStack::natspecDev(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1050,7 +1050,7 @@ Json::Value const& CompilerStack::natspecDev(Contract const& _contract) const return _contract.devDocumentation.init([&]{ return Natspec::devDocumentation(*_contract.contract); }); } -Json::Value CompilerStack::interfaceSymbols(string const& _contractName) const +Json::Value CompilerStack::interfaceSymbols(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1063,7 +1063,7 @@ Json::Value CompilerStack::interfaceSymbols(string const& _contractName) const interfaceSymbols["methods"][it.second->externalSignature()] = it.first.hex(); for (ErrorDefinition const* error: contractDefinition(_contractName).interfaceErrors()) { - string signature = error->functionType(true)->externalSignature(); + std::string signature = error->functionType(true)->externalSignature(); interfaceSymbols["errors"][signature] = util::toHex(toCompactBigEndian(util::selectorFromSignatureU32(signature), 4)); } @@ -1073,14 +1073,14 @@ Json::Value CompilerStack::interfaceSymbols(string const& _contractName) const )) if (!event->isAnonymous()) { - string signature = event->functionType(true)->externalSignature(); + std::string signature = event->functionType(true)->externalSignature(); interfaceSymbols["events"][signature] = toHex(u256(h256::Arith(util::keccak256(signature)))); } return interfaceSymbols; } -bytes CompilerStack::cborMetadata(string const& _contractName, bool _forIR) const +bytes CompilerStack::cborMetadata(std::string const& _contractName, bool _forIR) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1088,7 +1088,7 @@ bytes CompilerStack::cborMetadata(string const& _contractName, bool _forIR) cons return createCBORMetadata(contract(_contractName), _forIR); } -string const& CompilerStack::metadata(Contract const& _contract) const +std::string const& CompilerStack::metadata(Contract const& _contract) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1098,7 +1098,7 @@ string const& CompilerStack::metadata(Contract const& _contract) const return _contract.metadata.init([&]{ return createMetadata(_contract, m_viaIR); }); } -CharStream const& CompilerStack::charStream(string const& _sourceName) const +CharStream const& CompilerStack::charStream(std::string const& _sourceName) const { if (m_stackState < SourcesSet) solThrow(CompilerError, "No sources set."); @@ -1108,7 +1108,7 @@ CharStream const& CompilerStack::charStream(string const& _sourceName) const return *source(_sourceName).charStream; } -SourceUnit const& CompilerStack::ast(string const& _sourceName) const +SourceUnit const& CompilerStack::ast(std::string const& _sourceName) const { if (m_stackState < Parsed) solThrow(CompilerError, "Parsing not yet performed."); @@ -1118,7 +1118,7 @@ SourceUnit const& CompilerStack::ast(string const& _sourceName) const return *source(_sourceName).ast; } -ContractDefinition const& CompilerStack::contractDefinition(string const& _contractName) const +ContractDefinition const& CompilerStack::contractDefinition(std::string const& _contractName) const { if (m_stackState < AnalysisPerformed) solThrow(CompilerError, "Analysis was not successful."); @@ -1127,7 +1127,7 @@ ContractDefinition const& CompilerStack::contractDefinition(string const& _contr } size_t CompilerStack::functionEntryPoint( - string const& _contractName, + std::string const& _contractName, FunctionDefinition const& _function ) const { @@ -1155,7 +1155,7 @@ h256 const& CompilerStack::Source::swarmHash() const return swarmHashCached; } -string const& CompilerStack::Source::ipfsUrl() const +std::string const& CompilerStack::Source::ipfsUrl() const { if (ipfsUrlCached.empty()) ipfsUrlCached = "dweb:/ipfs/" + util::ipfsHashBase58(charStream->source()); @@ -1171,12 +1171,12 @@ StringMap CompilerStack::loadMissingSources(SourceUnit const& _ast) for (auto const& node: _ast.nodes()) if (ImportDirective const* import = dynamic_cast(node.get())) { - string const& importPath = *import->annotation().absolutePath; + std::string const& importPath = *import->annotation().absolutePath; if (m_sources.count(importPath) || newSources.count(importPath)) continue; - ReadCallback::Result result{false, string("File not supplied initially.")}; + ReadCallback::Result result{false, std::string("File not supplied initially.")}; if (m_readFile) result = m_readFile(ReadCallback::kindString(ReadCallback::Kind::ReadFile), importPath); @@ -1187,7 +1187,7 @@ StringMap CompilerStack::loadMissingSources(SourceUnit const& _ast) m_errorReporter.parserError( 6275_error, import->location(), - string("Source \"" + importPath + "\" not found: " + result.responseOrErrorMessage) + std::string("Source \"" + importPath + "\" not found: " + result.responseOrErrorMessage) ); continue; } @@ -1200,7 +1200,7 @@ StringMap CompilerStack::loadMissingSources(SourceUnit const& _ast) return newSources; } -string CompilerStack::applyRemapping(string const& _path, string const& _context) +std::string CompilerStack::applyRemapping(std::string const& _path, std::string const& _context) { solAssert(m_stackState < ParsedAndImported, ""); return m_importRemapper.apply(_path, _context); @@ -1211,10 +1211,10 @@ bool CompilerStack::resolveImports() solAssert(m_stackState == ParsedAndImported, ""); // topological sorting (depth first search) of the import graph, cutting potential cycles - vector sourceOrder; - set sourcesSeen; + std::vector sourceOrder; + std::set sourcesSeen; - function toposort = [&](Source const* _source) + std::function toposort = [&](Source const* _source) { if (sourcesSeen.count(_source)) return; @@ -1223,7 +1223,7 @@ bool CompilerStack::resolveImports() for (ASTPointer const& node: _source->ast->nodes()) if (ImportDirective const* import = dynamic_cast(node.get())) { - string const& path = *import->annotation().absolutePath; + std::string const& path = *import->annotation().absolutePath; solAssert(m_sources.count(path), ""); import->annotation().sourceUnit = m_sources[path].ast.get(); toposort(&m_sources[path]); @@ -1231,7 +1231,7 @@ bool CompilerStack::resolveImports() sourceOrder.push_back(_source); }; - vector experimentalPragmaDirectives; + std::vector experimentalPragmaDirectives; for (auto const& sourcePair: m_sources) { if (isRequestedSource(sourcePair.first)) @@ -1270,7 +1270,7 @@ void CompilerStack::storeContractDefinitions() ASTNode::filteredNodes(pair.second.ast->nodes()) ) { - string fullyQualifiedName = *pair.second.ast->annotation().path + ":" + contract->name(); + std::string fullyQualifiedName = *pair.second.ast->annotation().path + ":" + contract->name(); // Note that we now reference contracts by their fully qualified names, and // thus contracts can only conflict if declared in the same source file. This // should already cause a double-declaration error elsewhere. @@ -1293,7 +1293,7 @@ void CompilerStack::annotateInternalFunctionIDs() if (auto const* deployTimeInternalDispatch = util::valueOrNullptr((*annotation.deployedCallGraph)->edges, CallGraph::SpecialNode::InternalDispatch)) for (auto const& node: *deployTimeInternalDispatch) - if (auto const* callable = get_if(&node)) + if (auto const* callable = std::get_if(&node)) if (auto const* function = dynamic_cast(*callable)) { solAssert(contract->annotation().internalFunctionIDs.count(function) == 0); @@ -1301,7 +1301,7 @@ void CompilerStack::annotateInternalFunctionIDs() } if (auto const* creationTimeInternalDispatch = util::valueOrNullptr((*annotation.creationCallGraph)->edges, CallGraph::SpecialNode::InternalDispatch)) for (auto const& node: *creationTimeInternalDispatch) - if (auto const* callable = get_if(&node)) + if (auto const* callable = std::get_if(&node)) if (auto const* function = dynamic_cast(*callable)) // Make sure the function already got an ID since it also occurs in the deploy-time internal dispatch. solAssert(contract->annotation().internalFunctionIDs.count(function) != 0); @@ -1311,7 +1311,7 @@ void CompilerStack::annotateInternalFunctionIDs() namespace { -bool onlySafeExperimentalFeaturesActivated(set const& features) +bool onlySafeExperimentalFeaturesActivated(std::set const& features) { for (auto const feature: features) if (!ExperimentalFeatureWithoutWarning.count(feature)) @@ -1322,8 +1322,8 @@ bool onlySafeExperimentalFeaturesActivated(set const& featu void CompilerStack::assembleYul( ContractDefinition const& _contract, - shared_ptr _assembly, - shared_ptr _runtimeAssembly + std::shared_ptr _assembly, + std::shared_ptr _runtimeAssembly ) { solAssert(m_stackState >= AnalysisPerformed, ""); @@ -1367,7 +1367,7 @@ void CompilerStack::assembleYul( 5574_error, _contract.location(), "Contract code size is "s + - to_string(compiledContract.runtimeObject.bytecode.size()) + + std::to_string(compiledContract.runtimeObject.bytecode.size()) + " bytes and exceeds 24576 bytes (a limit introduced in Spurious Dragon). " "This contract may not be deployable on Mainnet. " "Consider enabling the optimizer (with a low \"runs\" value!), " @@ -1385,7 +1385,7 @@ void CompilerStack::assembleYul( 3860_error, _contract.location(), "Contract initcode size is "s + - to_string(compiledContract.object.bytecode.size()) + + std::to_string(compiledContract.object.bytecode.size()) + " bytes and exceeds 49152 bytes (a limit introduced in Shanghai). " "This contract may not be deployable on Mainnet. " "Consider enabling the optimizer (with a low \"runs\" value!), " @@ -1395,7 +1395,7 @@ void CompilerStack::assembleYul( void CompilerStack::compileContract( ContractDefinition const& _contract, - map>& _otherCompilers + std::map>& _otherCompilers ) { solAssert(!m_viaIR, ""); @@ -1415,7 +1415,7 @@ void CompilerStack::compileContract( Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName()); - shared_ptr compiler = make_shared(m_evmVersion, m_revertStrings, m_optimiserSettings); + std::shared_ptr compiler = std::make_shared(m_evmVersion, m_revertStrings, m_optimiserSettings); compiledContract.compiler = compiler; solAssert(!m_viaIR, ""); @@ -1454,14 +1454,14 @@ void CompilerStack::generateIR(ContractDefinition const& _contract) "Using ABI coder v2 instead." ); - string dependenciesSource; + std::string dependenciesSource; for (auto const& [dependency, referencee]: _contract.annotation().contractDependencies) generateIR(*dependency); if (!_contract.canBeDeployed()) return; - map otherYulSources; + std::map otherYulSources; for (auto const& pair: m_contracts) otherYulSources.emplace(pair.second.contract, pair.second.yulIR); @@ -1527,13 +1527,13 @@ void CompilerStack::generateEVMFromIR(ContractDefinition const& _contract) //cout << yul::AsmPrinter{}(*stack.parserResult()->code) << endl; - string deployedName = IRNames::deployedObject(_contract); + std::string deployedName = IRNames::deployedObject(_contract); solAssert(!deployedName.empty(), ""); tie(compiledContract.evmAssembly, compiledContract.evmRuntimeAssembly) = stack.assembleEVMWithDeployed(deployedName); assembleYul(_contract, compiledContract.evmAssembly, compiledContract.evmRuntimeAssembly); } -CompilerStack::Contract const& CompilerStack::contract(string const& _contractName) const +CompilerStack::Contract const& CompilerStack::contract(std::string const& _contractName) const { solAssert(m_stackState >= AnalysisPerformed, ""); @@ -1544,15 +1544,15 @@ CompilerStack::Contract const& CompilerStack::contract(string const& _contractNa // To provide a measure of backward-compatibility, if a contract is not located by its // fully-qualified name, a lookup will be attempted purely on the contract's name to see // if anything will satisfy. - if (_contractName.find(':') == string::npos) + if (_contractName.find(':') == std::string::npos) { for (auto const& contractEntry: m_contracts) { - stringstream ss; + std::stringstream ss; ss.str(contractEntry.first); // All entries are : - string source; - string foundName; + std::string source; + std::string foundName; getline(ss, source, ':'); getline(ss, foundName, ':'); if (foundName == _contractName) @@ -1564,7 +1564,7 @@ CompilerStack::Contract const& CompilerStack::contract(string const& _contractNa solThrow(CompilerError, "Contract \"" + _contractName + "\" not found."); } -CompilerStack::Source const& CompilerStack::source(string const& _sourceName) const +CompilerStack::Source const& CompilerStack::source(std::string const& _sourceName) const { auto it = m_sources.find(_sourceName); if (it == m_sources.end()) @@ -1573,11 +1573,11 @@ CompilerStack::Source const& CompilerStack::source(string const& _sourceName) co return it->second; } -string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) const +std::string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) const { Json::Value meta{Json::objectValue}; meta["version"] = 1; - string sourceType; + std::string sourceType; switch (m_compilationSourceType) { case CompilationSourceType::Solidity: @@ -1591,7 +1591,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con meta["compiler"]["version"] = VersionStringStrict; /// All the source files (including self), which should be included in the metadata. - set referencedSources; + std::set referencedSources; referencedSources.insert(*_contract.contract->sourceUnit().annotation().path); for (auto const sourceUnit: _contract.contract->sourceUnit().referencedSourceUnits(true)) referencedSources.insert(*sourceUnit->annotation().path); @@ -1604,7 +1604,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con solAssert(s.second.charStream, "Character stream not available"); meta["sources"][s.first]["keccak256"] = "0x" + util::toHex(s.second.keccak256().asBytes()); - if (optional licenseString = s.second.ast->licenseString()) + if (std::optional licenseString = s.second.ast->licenseString()) meta["sources"][s.first]["license"] = *licenseString; if (m_metadataLiteralSources) meta["sources"][s.first]["content"] = s.second.charStream->source(); @@ -1617,7 +1617,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con } static_assert(sizeof(m_optimiserSettings.expectedExecutionsPerDeployment) <= sizeof(Json::LargestUInt), "Invalid word size."); - solAssert(static_cast(m_optimiserSettings.expectedExecutionsPerDeployment) < numeric_limits::max(), ""); + solAssert(static_cast(m_optimiserSettings.expectedExecutionsPerDeployment) < std::numeric_limits::max(), ""); meta["settings"]["optimizer"]["runs"] = Json::Value(Json::LargestUInt(m_optimiserSettings.expectedExecutionsPerDeployment)); /// Backwards compatibility: If set to one of the default settings, do not provide details. @@ -1659,7 +1659,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con if (m_metadataLiteralSources) meta["settings"]["metadata"]["useLiteralContent"] = true; - static vector hashes{"ipfs", "bzzr1", "none"}; + static std::vector hashes{"ipfs", "bzzr1", "none"}; meta["settings"]["metadata"]["bytecodeHash"] = hashes.at(unsigned(m_metadataHash)); if (_forIR) @@ -1671,7 +1671,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con *_contract.contract->annotation().canonicalName; meta["settings"]["remappings"] = Json::arrayValue; - set remappings; + std::set remappings; for (auto const& r: m_importRemapper.remappings()) remappings.insert(r.context + ":" + r.prefix + "=" + r.target); for (auto const& r: remappings) @@ -1691,21 +1691,21 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con class MetadataCBOREncoder { public: - void pushBytes(string const& key, bytes const& value) + void pushBytes(std::string const& key, bytes const& value) { m_entryCount++; pushTextString(key); pushByteString(value); } - void pushString(string const& key, string const& value) + void pushString(std::string const& key, std::string const& value) { m_entryCount++; pushTextString(key); pushTextString(value); } - void pushBool(string const& key, bool value) + void pushBool(std::string const& key, bool value) { m_entryCount++; pushTextString(key); @@ -1728,7 +1728,7 @@ public: } private: - void pushTextString(string const& key) + void pushTextString(std::string const& key) { size_t length = key.size(); if (length < 24) @@ -1742,7 +1742,7 @@ private: m_data += key; } else - solAssert(false, "Text string too large."); + solAssert(false, "Text std::string too large."); } void pushByteString(bytes const& key) { @@ -1758,7 +1758,7 @@ private: m_data += key; } else - solAssert(false, "Byte string too large."); + solAssert(false, "Byte std::string too large."); } void pushBool(bool value) { @@ -1780,7 +1780,7 @@ bytes CompilerStack::createCBORMetadata(Contract const& _contract, bool _forIR) _contract.contract->sourceUnit().annotation().experimentalFeatures ); - string meta = (_forIR == m_viaIR ? metadata(_contract) : createMetadata(_contract, _forIR)); + std::string meta = (_forIR == m_viaIR ? metadata(_contract) : createMetadata(_contract, _forIR)); MetadataCBOREncoder encoder; @@ -1819,7 +1819,7 @@ Json::Value gasToJson(GasEstimator::GasConsumption const& _gas) } -Json::Value CompilerStack::gasEstimates(string const& _contractName) const +Json::Value CompilerStack::gasEstimates(std::string const& _contractName) const { if (m_stackState != CompilationSuccessful) solThrow(CompilerError, "Compilation was not successful."); @@ -1852,14 +1852,14 @@ Json::Value CompilerStack::gasEstimates(string const& _contractName) const Json::Value externalFunctions(Json::objectValue); for (auto it: contract.interfaceFunctions()) { - string sig = it.second->externalSignature(); + std::string sig = it.second->externalSignature(); externalFunctions[sig] = gasToJson(gasEstimator.functionalEstimation(*items, sig)); } if (contract.fallbackFunction()) /// This needs to be set to an invalid signature in order to trigger the fallback, /// without the shortcut (of CALLDATSIZE == 0), and therefore to receive the upper bound. - /// An empty string ("") would work to trigger the shortcut only. + /// An empty std::string ("") would work to trigger the shortcut only. externalFunctions[""] = gasToJson(gasEstimator.functionalEstimation(*items, "INVALID")); if (!externalFunctions.empty()) @@ -1880,7 +1880,7 @@ Json::Value CompilerStack::gasEstimates(string const& _contractName) const /// TODO: This could move into a method shared with externalSignature() FunctionType type(*it); - string sig = it->name() + "("; + std::string sig = it->name() + "("; auto paramTypes = type.parameterTypes(); for (auto it = paramTypes.begin(); it != paramTypes.end(); ++it) sig += (*it)->toString() + (it + 1 == paramTypes.end() ? "" : ","); diff --git a/libsolidity/interface/FileReader.cpp b/libsolidity/interface/FileReader.cpp index 8300feb57..7eda87081 100644 --- a/libsolidity/interface/FileReader.cpp +++ b/libsolidity/interface/FileReader.cpp @@ -35,17 +35,13 @@ using solidity::langutil::InternalCompilerError; using solidity::util::errinfo_comment; using solidity::util::readFileAsString; using solidity::util::joinHumanReadable; -using std::map; -using std::reference_wrapper; -using std::string; -using std::vector; namespace solidity::frontend { FileReader::FileReader( boost::filesystem::path _basePath, - vector const& _includePaths, + std::vector const& _includePaths, FileSystemPathSet _allowedDirectories ): m_allowedDirectories(std::move(_allowedDirectories)), @@ -99,19 +95,19 @@ void FileReader::setSourceUnits(StringMap _sources) m_sourceCodes = std::move(_sources); } -ReadCallback::Result FileReader::readFile(string const& _kind, string const& _sourceUnitName) +ReadCallback::Result FileReader::readFile(std::string const& _kind, std::string const& _sourceUnitName) { try { if (_kind != ReadCallback::kindString(ReadCallback::Kind::ReadFile)) solAssert(false, "ReadFile callback used as callback kind " + _kind); - string strippedSourceUnitName = _sourceUnitName; + std::string strippedSourceUnitName = _sourceUnitName; if (strippedSourceUnitName.find("file://") == 0) strippedSourceUnitName.erase(0, 7); - vector candidates; - vector> prefixes = {m_basePath}; - prefixes += (m_includePaths | ranges::to>>); + std::vector candidates; + std::vector> prefixes = {m_basePath}; + prefixes += (m_includePaths | ranges::to>>); for (auto const& prefix: prefixes) { @@ -183,9 +179,9 @@ ReadCallback::Result FileReader::readFile(string const& _kind, string const& _so } } -string FileReader::cliPathToSourceUnitName(boost::filesystem::path const& _cliPath) const +std::string FileReader::cliPathToSourceUnitName(boost::filesystem::path const& _cliPath) const { - vector prefixes = {m_basePath.empty() ? normalizeCLIPathForVFS(".") : m_basePath}; + std::vector prefixes = {m_basePath.empty() ? normalizeCLIPathForVFS(".") : m_basePath}; prefixes += m_includePaths; boost::filesystem::path normalizedPath = normalizeCLIPathForVFS(_cliPath); @@ -200,17 +196,17 @@ string FileReader::cliPathToSourceUnitName(boost::filesystem::path const& _cliPa return normalizedPath.generic_string(); } -map FileReader::detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const +std::map FileReader::detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const { - map nameToPaths; + std::map nameToPaths; for (boost::filesystem::path const& cliPath: _cliPaths) { - string sourceUnitName = cliPathToSourceUnitName(cliPath); + std::string sourceUnitName = cliPathToSourceUnitName(cliPath); boost::filesystem::path normalizedPath = normalizeCLIPathForVFS(cliPath); nameToPaths[sourceUnitName].insert(normalizedPath); } - map collisions; + std::map collisions; for (auto&& [sourceUnitName, cliPaths]: nameToPaths) if (cliPaths.size() >= 2) collisions[sourceUnitName] = std::move(cliPaths); @@ -377,7 +373,7 @@ bool FileReader::hasDotDotSegments(boost::filesystem::path const& _path) bool FileReader::isUNCPath(boost::filesystem::path const& _path) { - string rootName = _path.root_name().string(); + std::string rootName = _path.root_name().string(); return ( rootName.size() == 2 || diff --git a/libsolidity/interface/GasEstimator.cpp b/libsolidity/interface/GasEstimator.cpp index 512f91bee..fd3fbbc02 100644 --- a/libsolidity/interface/GasEstimator.cpp +++ b/libsolidity/interface/GasEstimator.cpp @@ -37,7 +37,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::frontend; @@ -45,16 +44,16 @@ using namespace solidity::langutil; GasEstimator::GasConsumption GasEstimator::functionalEstimation( AssemblyItems const& _items, - string const& _signature + std::string const& _signature ) const { - auto state = make_shared(); + auto state = std::make_shared(); if (!_signature.empty()) { ExpressionClasses& classes = state->expressionClasses(); using Id = ExpressionClasses::Id; - using Ids = vector; + using Ids = std::vector; Id hashValue = classes.find(u256(util::selectorFromSignatureU32(_signature))); Id calldata = classes.find(Instruction::CALLDATALOAD, Ids{classes.find(u256(0))}); if (!m_evmVersion.hasBitwiseShifting()) @@ -88,7 +87,7 @@ GasEstimator::GasConsumption GasEstimator::functionalEstimation( FunctionDefinition const& _function ) const { - auto state = make_shared(); + auto state = std::make_shared(); unsigned parametersSize = CompilerUtils::sizeOnStack(_function.parameters()); if (parametersSize > 16) @@ -104,13 +103,13 @@ GasEstimator::GasConsumption GasEstimator::functionalEstimation( return PathGasMeter::estimateMax(_items, m_evmVersion, _offset, state); } -set GasEstimator::finestNodesAtLocation( - vector const& _roots +std::set GasEstimator::finestNodesAtLocation( + std::vector const& _roots ) { - map locations; - set nodes; - SimpleASTVisitor visitor(function(), [&](ASTNode const& _n) + std::map locations; + std::set nodes; + SimpleASTVisitor visitor(std::function(), [&](ASTNode const& _n) { if (!locations.count(_n.location())) { diff --git a/libsolidity/interface/ImportRemapper.cpp b/libsolidity/interface/ImportRemapper.cpp index 4d4fa42d4..6b870875e 100644 --- a/libsolidity/interface/ImportRemapper.cpp +++ b/libsolidity/interface/ImportRemapper.cpp @@ -19,29 +19,20 @@ #include #include -using std::equal; -using std::find; -using std::move; -using std::nullopt; -using std::optional; -using std::string; -using std::string_view; -using std::vector; - namespace solidity::frontend { -void ImportRemapper::setRemappings(vector _remappings) +void ImportRemapper::setRemappings(std::vector _remappings) { for (auto const& remapping: _remappings) solAssert(!remapping.prefix.empty(), ""); m_remappings = std::move(_remappings); } -SourceUnitName ImportRemapper::apply(ImportPath const& _path, string const& _context) const +SourceUnitName ImportRemapper::apply(ImportPath const& _path, std::string const& _context) const { // Try to find the longest prefix match in all remappings that are active in the current context. - auto isPrefixOf = [](string const& _a, string const& _b) + auto isPrefixOf = [](std::string const& _a, std::string const& _b) { if (_a.length() > _b.length()) return false; @@ -50,12 +41,12 @@ SourceUnitName ImportRemapper::apply(ImportPath const& _path, string const& _con size_t longestPrefix = 0; size_t longestContext = 0; - string bestMatchTarget; + std::string bestMatchTarget; for (auto const& redir: m_remappings) { - string context = util::sanitizePath(redir.context); - string prefix = util::sanitizePath(redir.prefix); + std::string context = util::sanitizePath(redir.context); + std::string prefix = util::sanitizePath(redir.prefix); // Skip if current context is closer if (context.length() < longestContext) @@ -74,32 +65,32 @@ SourceUnitName ImportRemapper::apply(ImportPath const& _path, string const& _con longestPrefix = prefix.length(); bestMatchTarget = util::sanitizePath(redir.target); } - string path = bestMatchTarget; - path.append(_path.begin() + static_cast(longestPrefix), _path.end()); + std::string path = bestMatchTarget; + path.append(_path.begin() + static_cast(longestPrefix), _path.end()); return path; } -bool ImportRemapper::isRemapping(string_view _input) +bool ImportRemapper::isRemapping(std::string_view _input) { - return _input.find("=") != string::npos; + return _input.find("=") != std::string::npos; } -optional ImportRemapper::parseRemapping(string_view _input) + std::optional ImportRemapper::parseRemapping(std::string_view _input) { - auto equals = find(_input.cbegin(), _input.cend(), '='); + auto equals = std::find(_input.cbegin(), _input.cend(), '='); if (equals == _input.end()) - return nullopt; + return std::nullopt; - auto const colon = find(_input.cbegin(), equals, ':'); + auto const colon = std::find(_input.cbegin(), equals, ':'); Remapping remapping{ - (colon == equals ? "" : string(_input.cbegin(), colon)), - (colon == equals ? string(_input.cbegin(), equals) : string(colon + 1, equals)), - string(equals + 1, _input.cend()), + (colon == equals ? "" : std::string(_input.cbegin(), colon)), + (colon == equals ? std::string(_input.cbegin(), equals) : std::string(colon + 1, equals)), + std::string(equals + 1, _input.cend()), }; if (remapping.prefix.empty()) - return nullopt; + return std::nullopt; return remapping; } diff --git a/libsolidity/interface/Natspec.cpp b/libsolidity/interface/Natspec.cpp index 5733d3063..539a3573f 100644 --- a/libsolidity/interface/Natspec.cpp +++ b/libsolidity/interface/Natspec.cpp @@ -30,8 +30,6 @@ #include - -using namespace std; using namespace solidity; using namespace solidity::frontend; @@ -46,7 +44,7 @@ Json::Value Natspec::userDocumentation(ContractDefinition const& _contractDef) auto constructorDefinition(_contractDef.constructor()); if (constructorDefinition) { - string const value = extractDoc(constructorDefinition->annotation().docTags, "notice"); + std::string const value = extractDoc(constructorDefinition->annotation().docTags, "notice"); if (!value.empty()) { // add the constructor, only if we have any documentation to add @@ -56,14 +54,14 @@ Json::Value Natspec::userDocumentation(ContractDefinition const& _contractDef) } } - string notice = extractDoc(_contractDef.annotation().docTags, "notice"); + std::string notice = extractDoc(_contractDef.annotation().docTags, "notice"); if (!notice.empty()) doc["notice"] = Json::Value(notice); for (auto const& it: _contractDef.interfaceFunctions()) if (it.second->hasDeclaration()) { - string value; + std::string value; if (auto const* f = dynamic_cast(&it.second->declaration())) value = extractDoc(f->annotation().docTags, "notice"); @@ -80,14 +78,14 @@ Json::Value Natspec::userDocumentation(ContractDefinition const& _contractDef) for (auto const& event: uniqueInterfaceEvents(_contractDef)) { - string value = extractDoc(event->annotation().docTags, "notice"); + std::string value = extractDoc(event->annotation().docTags, "notice"); if (!value.empty()) doc["events"][event->functionType(true)->externalSignature()]["notice"] = value; } for (auto const& error: _contractDef.interfaceErrors()) { - string value = extractDoc(error->annotation().docTags, "notice"); + std::string value = extractDoc(error->annotation().docTags, "notice"); if (!value.empty()) { Json::Value errorDoc{Json::objectValue}; @@ -152,7 +150,7 @@ Json::Value Natspec::devDocumentation(ContractDefinition const& _contractDef) if (auto devDoc = devDocumentation(varDecl->annotation().docTags); !devDoc.empty()) doc["stateVariables"][varDecl->name()] = devDoc; - auto const assignIfNotEmpty = [&](string const& _name, Json::Value const& _content) + auto const assignIfNotEmpty = [&](std::string const& _name, Json::Value const& _content) { if (!_content.empty()) doc["stateVariables"][varDecl->name()][_name] = _content; @@ -178,7 +176,7 @@ Json::Value Natspec::devDocumentation(ContractDefinition const& _contractDef) return doc; } -Json::Value Natspec::extractReturnParameterDocs(std::multimap const& _tags, vector const& _returnParameterNames) +Json::Value Natspec::extractReturnParameterDocs(std::multimap const& _tags, std::vector const& _returnParameterNames) { Json::Value jsonReturn{Json::objectValue}; auto returnDocs = _tags.equal_range("return"); @@ -188,8 +186,8 @@ Json::Value Natspec::extractReturnParameterDocs(std::multimapsecond.content; + std::string paramName = _returnParameterNames.at(n); + std::string content = i->second.content; if (paramName.empty()) paramName = "_" + std::to_string(n); @@ -209,18 +207,18 @@ Json::Value Natspec::extractReturnParameterDocs(std::multimap const& _tags, string const& _name) +std::string Natspec::extractDoc(std::multimap const& _tags, std::string const& _name) { - string value; + std::string value; auto range = _tags.equal_range(_name); for (auto i = range.first; i != range.second; i++) value += i->second.content; return value; } -Json::Value Natspec::extractCustomDoc(multimap const& _tags) +Json::Value Natspec::extractCustomDoc(std::multimap const& _tags) { - std::map concatenated; + std::map concatenated; for (auto const& [tag, value]: _tags) if (boost::starts_with(tag, "custom")) concatenated[tag] += value.content; @@ -255,9 +253,9 @@ Json::Value Natspec::devDocumentation(std::multimap const& return json; } -vector Natspec::uniqueInterfaceEvents(ContractDefinition const& _contract) +std::vector Natspec::uniqueInterfaceEvents(ContractDefinition const& _contract) { - auto eventSignature = [](EventDefinition const* _event) -> string { + auto eventSignature = [](EventDefinition const* _event) -> std::string { FunctionType const* functionType = _event->functionType(true); solAssert(functionType, ""); return functionType->externalSignature(); @@ -267,13 +265,13 @@ vector Natspec::uniqueInterfaceEvents(ContractDefinitio return eventSignature(_lhs) < eventSignature(_rhs); }; - set uniqueEvents{compareBySignature}; + std::set uniqueEvents{compareBySignature}; // Insert events defined in the contract first so that in case of a conflict // they're the ones that get selected. uniqueEvents += _contract.definedInterfaceEvents(); - set filteredUsedEvents{compareBySignature}; - set usedSignatures; + std::set filteredUsedEvents{compareBySignature}; + std::set usedSignatures; for (EventDefinition const* event: _contract.usedInterfaceEvents()) { auto&& [eventIt, eventInserted] = filteredUsedEvents.insert(event); @@ -283,5 +281,5 @@ vector Natspec::uniqueInterfaceEvents(ContractDefinitio } uniqueEvents += filteredUsedEvents; - return util::convertContainer>(std::move(uniqueEvents)); + return util::convertContainer>(std::move(uniqueEvents)); } diff --git a/libsolidity/interface/SMTSolverCommand.cpp b/libsolidity/interface/SMTSolverCommand.cpp index 1896da3c6..92e0485b8 100644 --- a/libsolidity/interface/SMTSolverCommand.cpp +++ b/libsolidity/interface/SMTSolverCommand.cpp @@ -33,14 +33,13 @@ using solidity::langutil::InternalCompilerError; using solidity::util::errinfo_comment; -using namespace std; namespace solidity::frontend { -SMTSolverCommand::SMTSolverCommand(string _solverCmd) : m_solverCmd(_solverCmd) {} +SMTSolverCommand::SMTSolverCommand(std::string _solverCmd) : m_solverCmd(_solverCmd) {} -ReadCallback::Result SMTSolverCommand::solve(string const& _kind, string const& _query) +ReadCallback::Result SMTSolverCommand::solve(std::string const& _kind, std::string const& _query) { try { @@ -66,8 +65,8 @@ ReadCallback::Result SMTSolverCommand::solve(string const& _kind, string const& boost::process::std_out > pipe ); - vector data; - string line; + std::vector data; + std::string line; while (eld.running() && std::getline(pipe, line)) if (!line.empty()) data.push_back(line); diff --git a/libsolidity/interface/StandardCompiler.cpp b/libsolidity/interface/StandardCompiler.cpp index 32d6cf8e8..e90d25e21 100644 --- a/libsolidity/interface/StandardCompiler.cpp +++ b/libsolidity/interface/StandardCompiler.cpp @@ -44,20 +44,20 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::frontend; using namespace solidity::langutil; +using namespace std::string_literals; namespace { Json::Value formatError( Error::Type _type, - string const& _component, - string const& _message, - string const& _formattedMessage = "", + std::string const& _component, + std::string const& _message, + std::string const& _formattedMessage = "", Json::Value const& _sourceLocation = Json::Value(), Json::Value const& _secondarySourceLocation = Json::Value() ) @@ -75,7 +75,7 @@ Json::Value formatError( return error; } -Json::Value formatFatalError(Error::Type _type, string const& _message) +Json::Value formatFatalError(Error::Type _type, std::string const& _message) { Json::Value output{Json::objectValue}; output["errors"] = Json::arrayValue; @@ -114,21 +114,21 @@ Json::Value formatErrorWithException( CharStreamProvider const& _charStreamProvider, util::Exception const& _exception, Error::Type _type, - string const& _component, - string const& _message, - optional _errorId = nullopt + std::string const& _component, + std::string const& _message, + std::optional _errorId = std::nullopt ) { - string message; + std::string message; // TODO: consider enabling color - string formattedMessage = SourceReferenceFormatter::formatExceptionInformation( + std::string formattedMessage = SourceReferenceFormatter::formatExceptionInformation( _exception, _type, _charStreamProvider, false // colored ); - if (string const* description = _exception.comment()) + if (std::string const* description = _exception.comment()) message = ((_message.length() > 0) ? (_message + ":") : "") + *description; else message = _message; @@ -143,20 +143,20 @@ Json::Value formatErrorWithException( ); if (_errorId) - error["errorCode"] = to_string(_errorId.value().error); + error["errorCode"] = std::to_string(_errorId.value().error); return error; } -map> requestedContractNames(Json::Value const& _outputSelection) +std::map> requestedContractNames(Json::Value const& _outputSelection) { - map> contracts; + std::map> contracts; for (auto const& sourceName: _outputSelection.getMemberNames()) { - string key = (sourceName == "*") ? "" : sourceName; + std::string key = (sourceName == "*") ? "" : sourceName; for (auto const& contractName: _outputSelection[sourceName].getMemberNames()) { - string value = (contractName == "*") ? "" : contractName; + std::string value = (contractName == "*") ? "" : contractName; contracts[key].insert(value); } } @@ -164,7 +164,7 @@ map> requestedContractNames(Json::Value const& _outputSelect } /// Returns true iff @a _hash (hex with 0x prefix) is the Keccak256 hash of the binary data in @a _content. -bool hashMatchesContent(string const& _hash, string const& _content) +bool hashMatchesContent(std::string const& _hash, std::string const& _content) { try { @@ -176,12 +176,12 @@ bool hashMatchesContent(string const& _hash, string const& _content) } } -bool isArtifactRequested(Json::Value const& _outputSelection, string const& _artifact, bool _wildcardMatchesExperimental) +bool isArtifactRequested(Json::Value const& _outputSelection, std::string const& _artifact, bool _wildcardMatchesExperimental) { - static set experimental{"ir", "irAst", "irOptimized", "irOptimizedAst"}; + static std::set experimental{"ir", "irAst", "irOptimized", "irOptimizedAst"}; for (auto const& selectedArtifactJson: _outputSelection) { - string const& selectedArtifact = selectedArtifactJson.asString(); + std::string const& selectedArtifact = selectedArtifactJson.asString(); if ( _artifact == selectedArtifact || boost::algorithm::starts_with(_artifact, selectedArtifact + ".") @@ -210,17 +210,17 @@ bool isArtifactRequested(Json::Value const& _outputSelection, string const& _art /// /// @TODO optimise this. Perhaps flatten the structure upfront. /// -bool isArtifactRequested(Json::Value const& _outputSelection, string const& _file, string const& _contract, string const& _artifact, bool _wildcardMatchesExperimental) +bool isArtifactRequested(Json::Value const& _outputSelection, std::string const& _file, std::string const& _contract, std::string const& _artifact, bool _wildcardMatchesExperimental) { if (!_outputSelection.isObject()) return false; - for (auto const& file: { _file, string("*") }) + for (auto const& file: { _file, std::string("*") }) if (_outputSelection.isMember(file) && _outputSelection[file].isObject()) { /// For SourceUnit-level targets (such as AST) only allow empty name, otherwise /// for Contract-level targets try both contract name and wildcard - vector contracts{ _contract }; + std::vector contracts{ _contract }; if (!_contract.empty()) contracts.emplace_back("*"); for (auto const& contract: contracts) @@ -235,7 +235,7 @@ bool isArtifactRequested(Json::Value const& _outputSelection, string const& _fil return false; } -bool isArtifactRequested(Json::Value const& _outputSelection, string const& _file, string const& _contract, vector const& _artifacts, bool _wildcardMatchesExperimental) +bool isArtifactRequested(Json::Value const& _outputSelection, std::string const& _file, std::string const& _contract, std::vector const& _artifacts, bool _wildcardMatchesExperimental) { for (auto const& artifact: _artifacts) if (isArtifactRequested(_outputSelection, _file, _contract, artifact, _wildcardMatchesExperimental)) @@ -244,10 +244,10 @@ bool isArtifactRequested(Json::Value const& _outputSelection, string const& _fil } /// @returns all artifact names of the EVM object, either for creation or deploy time. -vector evmObjectComponents(string const& _objectKind) +std::vector evmObjectComponents(std::string const& _objectKind) { solAssert(_objectKind == "bytecode" || _objectKind == "deployedBytecode", ""); - vector components{"", ".object", ".opcodes", ".sourceMap", ".functionDebugData", ".generatedSources", ".linkReferences"}; + std::vector components{"", ".object", ".opcodes", ".sourceMap", ".functionDebugData", ".generatedSources", ".linkReferences"}; if (_objectKind == "deployedBytecode") components.push_back(".immutableReferences"); return util::applyMap(components, [&](auto const& _s) { return "evm." + _objectKind + _s; }); @@ -260,7 +260,7 @@ bool isBinaryRequested(Json::Value const& _outputSelection) return false; // This does not include "evm.methodIdentifiers" on purpose! - static vector const outputsThatRequireBinaries = vector{ + static std::vector const outputsThatRequireBinaries = std::vector{ "*", "ir", "irAst", "irOptimized", "irOptimizedAst", "evm.gasEstimates", "evm.legacyAssembly", "evm.assembly" @@ -280,7 +280,7 @@ bool isEvmBytecodeRequested(Json::Value const& _outputSelection) if (!_outputSelection.isObject()) return false; - static vector const outputsThatRequireEvmBinaries = vector{ + static std::vector const outputsThatRequireEvmBinaries = std::vector{ "*", "evm.gasEstimates", "evm.legacyAssembly", "evm.assembly" } + evmObjectComponents("bytecode") + evmObjectComponents("deployedBytecode"); @@ -320,13 +320,13 @@ Json::Value formatLinkReferences(std::map const& linkRefere for (auto const& ref: linkReferences) { - string const& fullname = ref.second; + std::string const& fullname = ref.second; // If the link reference does not contain a colon, assume that the file name is missing and - // the whole string represents the library name. + // the whole std::string represents the library name. size_t colon = fullname.rfind(':'); - string file = (colon != string::npos ? fullname.substr(0, colon) : ""); - string name = (colon != string::npos ? fullname.substr(colon + 1) : fullname); + std::string file = (colon != std::string::npos ? fullname.substr(0, colon) : ""); + std::string name = (colon != std::string::npos ? fullname.substr(colon + 1) : fullname); Json::Value fileObject = ret.get(file, Json::objectValue); Json::Value libraryArray = fileObject.get(name, Json::arrayValue); @@ -343,7 +343,7 @@ Json::Value formatLinkReferences(std::map const& linkRefere return ret; } -Json::Value formatImmutableReferences(map>> const& _immutableReferences) +Json::Value formatImmutableReferences(std::map>> const& _immutableReferences) { Json::Value ret{Json::objectValue}; @@ -367,10 +367,10 @@ Json::Value formatImmutableReferences(map>> co Json::Value collectEVMObject( langutil::EVMVersion _evmVersion, evmasm::LinkerObject const& _object, - string const* _sourceMap, + std::string const* _sourceMap, Json::Value _generatedSources, bool _runtimeObject, - function const& _artifactRequested + std::function const& _artifactRequested ) { Json::Value output{Json::objectValue}; @@ -391,7 +391,7 @@ Json::Value collectEVMObject( return output; } -std::optional checkKeys(Json::Value const& _input, set const& _keys, string const& _name) +std::optional checkKeys(Json::Value const& _input, std::set const& _keys, std::string const& _name) { if (!!_input && !_input.isObject()) return formatFatalError(Error::Type::JSONError, "\"" + _name + "\" must be an object"); @@ -405,43 +405,43 @@ std::optional checkKeys(Json::Value const& _input, set cons std::optional checkRootKeys(Json::Value const& _input) { - static set keys{"auxiliaryInput", "language", "settings", "sources"}; + static std::set keys{"auxiliaryInput", "language", "settings", "sources"}; return checkKeys(_input, keys, "root"); } -std::optional checkSourceKeys(Json::Value const& _input, string const& _name) +std::optional checkSourceKeys(Json::Value const& _input, std::string const& _name) { - static set keys{"content", "keccak256", "urls"}; + static std::set keys{"content", "keccak256", "urls"}; return checkKeys(_input, keys, "sources." + _name); } std::optional checkAuxiliaryInputKeys(Json::Value const& _input) { - static set keys{"smtlib2responses"}; + static std::set keys{"smtlib2responses"}; return checkKeys(_input, keys, "auxiliaryInput"); } std::optional checkSettingsKeys(Json::Value const& _input) { - static set keys{"parserErrorRecovery", "debug", "evmVersion", "libraries", "metadata", "modelChecker", "optimizer", "outputSelection", "remappings", "stopAfter", "viaIR"}; + static std::set keys{"parserErrorRecovery", "debug", "evmVersion", "libraries", "metadata", "modelChecker", "optimizer", "outputSelection", "remappings", "stopAfter", "viaIR"}; return checkKeys(_input, keys, "settings"); } std::optional checkModelCheckerSettingsKeys(Json::Value const& _input) { - static set keys{"bmcLoopIterations", "contracts", "divModNoSlacks", "engine", "extCalls", "invariants", "printQuery", "showProvedSafe", "showUnproved", "showUnsupported", "solvers", "targets", "timeout"}; + static std::set keys{"bmcLoopIterations", "contracts", "divModNoSlacks", "engine", "extCalls", "invariants", "printQuery", "showProvedSafe", "showUnproved", "showUnsupported", "solvers", "targets", "timeout"}; return checkKeys(_input, keys, "modelChecker"); } std::optional checkOptimizerKeys(Json::Value const& _input) { - static set keys{"details", "enabled", "runs"}; + static std::set keys{"details", "enabled", "runs"}; return checkKeys(_input, keys, "settings.optimizer"); } std::optional checkOptimizerDetailsKeys(Json::Value const& _input) { - static set keys{"peephole", "inliner", "jumpdestRemover", "orderLiterals", "deduplicate", "cse", "constantOptimizer", "yul", "yulDetails"}; + static std::set keys{"peephole", "inliner", "jumpdestRemover", "orderLiterals", "deduplicate", "cse", "constantOptimizer", "yul", "yulDetails"}; return checkKeys(_input, keys, "settings.optimizer.details"); } @@ -456,7 +456,7 @@ std::optional checkOptimizerDetail(Json::Value const& _details, std return {}; } -std::optional checkOptimizerDetailSteps(Json::Value const& _details, std::string const& _name, string& _optimiserSetting, string& _cleanupSetting) +std::optional checkOptimizerDetailSteps(Json::Value const& _details, std::string const& _name, std::string& _optimiserSetting, std::string& _cleanupSetting) { if (_details.isMember(_name)) { @@ -474,11 +474,11 @@ std::optional checkOptimizerDetailSteps(Json::Value const& _details ); } - string const fullSequence = _details[_name].asString(); + std::string const fullSequence = _details[_name].asString(); auto const delimiterPos = fullSequence.find(":"); _optimiserSetting = fullSequence.substr(0, delimiterPos); - if (delimiterPos != string::npos) + if (delimiterPos != std::string::npos) _cleanupSetting = fullSequence.substr(delimiterPos + 1); else solAssert(_cleanupSetting == OptimiserSettings::DefaultYulOptimiserCleanupSteps); @@ -499,11 +499,11 @@ std::optional checkMetadataKeys(Json::Value const& _input) if (_input.isMember("useLiteralContent") && !_input["useLiteralContent"].isBool()) return formatFatalError(Error::Type::JSONError, "\"settings.metadata.useLiteralContent\" must be Boolean"); - static set hashes{"ipfs", "bzzr1", "none"}; + static std::set hashes{"ipfs", "bzzr1", "none"}; if (_input.isMember("bytecodeHash") && !hashes.count(_input["bytecodeHash"].asString())) return formatFatalError(Error::Type::JSONError, "\"settings.metadata.bytecodeHash\" must be \"ipfs\", \"bzzr1\" or \"none\""); } - static set keys{"appendCBOR", "useLiteralContent", "bytecodeHash"}; + static std::set keys{"appendCBOR", "useLiteralContent", "bytecodeHash"}; return checkKeys(_input, keys, "settings.metadata"); } @@ -645,7 +645,7 @@ std::variant StandardCompiler: { for (auto const& sourceName: sources.getMemberNames()) { - string hash; + std::string hash; if (auto result = checkSourceKeys(sources[sourceName], sourceName)) return *result; @@ -655,7 +655,7 @@ std::variant StandardCompiler: if (sources[sourceName]["content"].isString()) { - string content = sources[sourceName]["content"].asString(); + std::string content = sources[sourceName]["content"].asString(); if (!hash.empty() && !hashMatchesContent(hash, content)) ret.errors.append(formatError( Error::Type::IOError, @@ -672,7 +672,7 @@ std::variant StandardCompiler: Error::Type::JSONError, "No import callback supplied, but URL is requested." ); - vector failures; + std::vector failures; bool found = false; for (auto const& url: sources[sourceName]["urls"]) @@ -832,11 +832,11 @@ std::variant StandardCompiler: if (!settings["debug"]["debugInfo"].isArray()) return formatFatalError(Error::Type::JSONError, "settings.debug.debugInfo must be an array."); - vector components; + std::vector components; for (Json::Value const& arrayValue: settings["debug"]["debugInfo"]) components.push_back(arrayValue.asString()); - optional debugInfoSelection = DebugInfoSelection::fromComponents( + std::optional debugInfoSelection = DebugInfoSelection::fromComponents( components, true /* _acceptWildcards */ ); @@ -887,7 +887,7 @@ std::variant StandardCompiler: { if (!jsonSourceName[library].isString()) return formatFatalError(Error::Type::JSONError, "Library address must be a string."); - string address = jsonSourceName[library].asString(); + std::string address = jsonSourceName[library].asString(); if (!boost::starts_with(address, "0x")) return formatFatalError( @@ -969,7 +969,7 @@ std::variant StandardCompiler: if (!sources.isObject() && !sources.isNull()) return formatFatalError(Error::Type::JSONError, "settings.modelChecker.contracts is not a JSON object."); - map> sourceContracts; + std::map> sourceContracts; for (auto const& source: sources.getMemberNames()) { if (source.empty()) @@ -1138,14 +1138,14 @@ std::variant StandardCompiler: return {std::move(ret)}; } -map StandardCompiler::parseAstFromInput(StringMap const& _sources) +std::map StandardCompiler::parseAstFromInput(StringMap const& _sources) { - map sourceJsons; + std::map sourceJsons; for (auto const& [sourceName, sourceCode]: _sources) { Json::Value ast; astAssert(util::jsonParseStrict(sourceCode, ast), "Input file could not be parsed to JSON"); - string astKey = ast.isMember("ast") ? "ast" : "AST"; + std::string astKey = ast.isMember("ast") ? "ast" : "AST"; astAssert(ast.isMember(astKey), "astkey is not member"); astAssert(ast[astKey]["nodeType"].asString() == "SourceUnit", "Top-level node should be a 'SourceUnit'"); @@ -1341,7 +1341,7 @@ Json::Value StandardCompiler::compileSolidity(StandardCompiler::InputsAndSetting output["errors"] = std::move(errors); if (!compilerStack.unhandledSMTLib2Queries().empty()) - for (string const& query: compilerStack.unhandledSMTLib2Queries()) + for (std::string const& query: compilerStack.unhandledSMTLib2Queries()) output["auxiliaryInputRequested"]["smtlib2queries"]["0x" + util::keccak256(query).hex()] = query; bool const wildcardMatchesExperimental = false; @@ -1349,7 +1349,7 @@ Json::Value StandardCompiler::compileSolidity(StandardCompiler::InputsAndSetting output["sources"] = Json::objectValue; unsigned sourceIndex = 0; if (parsingSuccess && !analysisFailed && (!compilerStack.hasError() || _inputsAndSettings.parserErrorRecovery)) - for (string const& sourceName: compilerStack.sourceNames()) + for (std::string const& sourceName: compilerStack.sourceNames()) { Json::Value sourceResult = Json::objectValue; sourceResult["id"] = sourceIndex++; @@ -1359,12 +1359,12 @@ Json::Value StandardCompiler::compileSolidity(StandardCompiler::InputsAndSetting } Json::Value contractsOutput = Json::objectValue; - for (string const& contractName: analysisPerformed ? compilerStack.contractNames() : vector()) + for (std::string const& contractName: analysisPerformed ? compilerStack.contractNames() : std::vector()) { size_t colon = contractName.rfind(':'); - solAssert(colon != string::npos, ""); - string file = contractName.substr(0, colon); - string name = contractName.substr(colon + 1); + solAssert(colon != std::string::npos, ""); + std::string file = contractName.substr(0, colon); + std::string name = contractName.substr(colon + 1); // ABI, storage layout, documentation and metadata Json::Value contractData(Json::objectValue); @@ -1413,7 +1413,7 @@ Json::Value StandardCompiler::compileSolidity(StandardCompiler::InputsAndSetting compilerStack.sourceMapping(contractName), compilerStack.generatedSources(contractName), false, - [&](string const& _element) { return isArtifactRequested( + [&](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, file, name, @@ -1435,7 +1435,7 @@ Json::Value StandardCompiler::compileSolidity(StandardCompiler::InputsAndSetting compilerStack.runtimeSourceMapping(contractName), compilerStack.generatedSources(contractName, true), true, - [&](string const& _element) { return isArtifactRequested( + [&](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, file, name, @@ -1512,8 +1512,8 @@ Json::Value StandardCompiler::compileYul(InputsAndSettings _inputsAndSettings) _inputsAndSettings.debugInfoSelection.value() : DebugInfoSelection::Default() ); - string const& sourceName = _inputsAndSettings.sources.begin()->first; - string const& sourceContents = _inputsAndSettings.sources.begin()->second; + std::string const& sourceName = _inputsAndSettings.sources.begin()->first; + std::string const& sourceContents = _inputsAndSettings.sources.begin()->second; // Inconsistent state - stop here to receive error reports from users if (!stack.parseAndAnalyze(sourceName, sourceContents) && stack.errors().empty()) @@ -1530,7 +1530,7 @@ Json::Value StandardCompiler::compileYul(InputsAndSettings _inputsAndSettings) { for (auto const& error: stack.errors()) { - auto err = dynamic_pointer_cast(error); + auto err = std::dynamic_pointer_cast(error); output["errors"].append(formatErrorWithException( stack, @@ -1543,7 +1543,7 @@ Json::Value StandardCompiler::compileYul(InputsAndSettings _inputsAndSettings) return output; } - string contractName = stack.parserResult()->name.str(); + std::string contractName = stack.parserResult()->name.str(); bool const wildcardMatchesExperimental = true; if (isArtifactRequested(_inputsAndSettings.outputSelection, sourceName, contractName, "ir", wildcardMatchesExperimental)) @@ -1560,7 +1560,7 @@ Json::Value StandardCompiler::compileYul(InputsAndSettings _inputsAndSettings) MachineAssemblyObject object; MachineAssemblyObject deployedObject; - tie(object, deployedObject) = stack.assembleWithDeployed(); + std::tie(object, deployedObject) = stack.assembleWithDeployed(); if (object.bytecode) object.bytecode->link(_inputsAndSettings.libraries); @@ -1585,7 +1585,7 @@ Json::Value StandardCompiler::compileYul(InputsAndSettings _inputsAndSettings) o.sourceMappings.get(), Json::arrayValue, isDeployed, - [&, kind = kind](string const& _element) { return isArtifactRequested( + [&, kind = kind](std::string const& _element) { return isArtifactRequested( _inputsAndSettings.outputSelection, sourceName, contractName, @@ -1625,11 +1625,11 @@ Json::Value StandardCompiler::compile(Json::Value const& _input) noexcept } catch (Json::LogicError const& _exception) { - return formatFatalError(Error::Type::InternalCompilerError, string("JSON logic exception: ") + _exception.what()); + return formatFatalError(Error::Type::InternalCompilerError, std::string("JSON logic exception: ") + _exception.what()); } catch (Json::RuntimeError const& _exception) { - return formatFatalError(Error::Type::InternalCompilerError, string("JSON runtime exception: ") + _exception.what()); + return formatFatalError(Error::Type::InternalCompilerError, std::string("JSON runtime exception: ") + _exception.what()); } catch (util::Exception const& _exception) { @@ -1641,10 +1641,10 @@ Json::Value StandardCompiler::compile(Json::Value const& _input) noexcept } } -string StandardCompiler::compile(string const& _input) noexcept +std::string StandardCompiler::compile(std::string const& _input) noexcept { Json::Value input; - string errors; + std::string errors; try { if (!util::jsonParseStrict(_input, input, &errors)) @@ -1670,7 +1670,7 @@ string StandardCompiler::compile(string const& _input) noexcept } Json::Value StandardCompiler::formatFunctionDebugData( - map const& _debugInfo + std::map const& _debugInfo ) { Json::Value ret(Json::objectValue); diff --git a/libsolidity/interface/StorageLayout.cpp b/libsolidity/interface/StorageLayout.cpp index 76c840db5..8e1d0eed1 100644 --- a/libsolidity/interface/StorageLayout.cpp +++ b/libsolidity/interface/StorageLayout.cpp @@ -20,7 +20,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::frontend; @@ -112,7 +111,7 @@ void StorageLayout::generate(Type const* _type) solAssert(typeInfo.isMember("encoding"), ""); } -string StorageLayout::typeKeyName(Type const* _type) +std::string StorageLayout::typeKeyName(Type const* _type) { if (auto refType = dynamic_cast(_type)) return TypeProvider::withLocationIfReference(refType->location(), _type)->richIdentifier(); diff --git a/libsolidity/interface/Version.cpp b/libsolidity/interface/Version.cpp index 0017b6de1..565ff2a60 100644 --- a/libsolidity/interface/Version.cpp +++ b/libsolidity/interface/Version.cpp @@ -25,19 +25,17 @@ #include -using namespace std; - char const* solidity::frontend::VersionNumber = ETH_PROJECT_VERSION; -string const solidity::frontend::VersionString = - string(solidity::frontend::VersionNumber) + - (string(SOL_VERSION_PRERELEASE).empty() ? "" : "-" + string(SOL_VERSION_PRERELEASE)) + - (string(SOL_VERSION_BUILDINFO).empty() ? "" : "+" + string(SOL_VERSION_BUILDINFO)); +std::string const solidity::frontend::VersionString = + std::string(solidity::frontend::VersionNumber) + + (std::string(SOL_VERSION_PRERELEASE).empty() ? "" : "-" + std::string(SOL_VERSION_PRERELEASE)) + + (std::string(SOL_VERSION_BUILDINFO).empty() ? "" : "+" + std::string(SOL_VERSION_BUILDINFO)); -string const solidity::frontend::VersionStringStrict = - string(solidity::frontend::VersionNumber) + - (string(SOL_VERSION_PRERELEASE).empty() ? "" : "-" + string(SOL_VERSION_PRERELEASE)) + - (string(SOL_VERSION_COMMIT).empty() ? "" : "+" + string(SOL_VERSION_COMMIT)); +std::string const solidity::frontend::VersionStringStrict = + std::string(solidity::frontend::VersionNumber) + + (std::string(SOL_VERSION_PRERELEASE).empty() ? "" : "-" + std::string(SOL_VERSION_PRERELEASE)) + + (std::string(SOL_VERSION_COMMIT).empty() ? "" : "+" + std::string(SOL_VERSION_COMMIT)); solidity::bytes const solidity::frontend::VersionCompactBytes = { ETH_PROJECT_VERSION_MAJOR, @@ -45,4 +43,4 @@ solidity::bytes const solidity::frontend::VersionCompactBytes = { ETH_PROJECT_VERSION_PATCH }; -bool const solidity::frontend::VersionIsRelease = string(SOL_VERSION_PRERELEASE).empty(); +bool const solidity::frontend::VersionIsRelease = std::string(SOL_VERSION_PRERELEASE).empty(); diff --git a/scripts/check_style.sh b/scripts/check_style.sh index cfc9def7a..7c85e6719 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -30,6 +30,7 @@ NAMESPACE_STD_FREE_FILES=( libsolidity/codegen/ir/* libsolidity/codegen/* libsolidity/formal/* + libsolidity/interface/* ) (