Merge pull request #14492 from ethereum/purge-using-namespace-from-libsolidity-interface

Purge using namespace std from libsolidity/interface
This commit is contained in:
Nikola Matić 2023-08-16 17:05:16 +02:00 committed by GitHub
commit 310794089a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 276 additions and 296 deletions

View File

@ -23,7 +23,6 @@
#include <libsolidity/ast/AST.h>
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<Json::Value, decltype(compare)> abi(compare);
std::multiset<Json::Value, decltype(compare)> abi(compare);
for (auto it: _contractDef.interfaceFunctions())
{
@ -144,9 +143,9 @@ Json::Value ABI::generate(ContractDefinition const& _contractDef)
}
Json::Value ABI::formatTypeList(
vector<string> const& _names,
vector<Type const*> const& _encodingTypes,
vector<Type const*> const& _solidityTypes,
std::vector<std::string> const& _names,
std::vector<Type const*> const& _encodingTypes,
std::vector<Type const*> 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<ArrayType const*>(&_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(
"",

View File

@ -94,11 +94,11 @@
#include <limits>
#include <string>
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<CallGraph>(
annotation.creationCallGraph = std::make_unique<CallGraph>(
FunctionCallGraphBuilder::buildCreationGraph(*contract)
);
annotation.deployedCallGraph = make_unique<CallGraph>(
annotation.deployedCallGraph = std::make_unique<CallGraph>(
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<ASTNode const*, ASTNode::CompareByID> foundCycles;
std::set<ASTNode const*, ASTNode::CompareByID> foundCycles;
for (Source const* source: m_sourceOrder)
{
@ -208,7 +208,7 @@ void CompilerStack::findAndReportCyclicContractDependencies()
}
}
void CompilerStack::setRemappings(vector<ImportRemapper::Remapping> _remappings)
void CompilerStack::setRemappings(std::vector<ImportRemapper::Remapping> _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<string, util::h160> const& _libraries)
void CompilerStack::setLibraries(std::map<std::string, util::h160> 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<CharStream>(/*content*/std::move(source.second), /*name*/source.first);
m_sources[source.first].charStream = std::make_unique<CharStream>(/*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<string> sourcesToParse;
std::vector<std::string> 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<CharStream>(content, name);
m_sources[name].charStream = std::make_unique<CharStream>(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<CharStream>(newContents, newPath);
std::string const& newPath = newSource.first;
std::string const& newContents = newSource.second;
m_sources[newPath].charStream = std::make_shared<CharStream>(newContents, newPath);
sourcesToParse.push_back(newPath);
}
}
@ -415,17 +415,17 @@ bool CompilerStack::parse()
return !m_hasError;
}
void CompilerStack::importASTs(map<string, Json::Value> const& _sources)
void CompilerStack::importASTs(std::map<std::string, Json::Value> const& _sources)
{
if (m_stackState != Empty)
solThrow(CompilerError, "Must call importASTs only before the SourcesSet state.");
map<string, ASTPointer<SourceUnit>> reconstructedSources = ASTJsonImporter(m_evmVersion).jsonToSourceUnit(_sources);
std::map<std::string, ASTPointer<SourceUnit>> 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<CharStream>(
source.charStream = std::make_shared<CharStream>(
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<GlobalContext>();
m_globalContext = std::make_shared<GlobalContext>();
// 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<string, SourceUnit const*> sourceUnitsByName;
std::map<std::string, SourceUnit const*> 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<ASTPointer<ASTNode>> ast;
std::vector<ASTPointer<ASTNode>> 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<string>{"", _contract.sourceUnitName()})
for (auto const& key: std::vector<std::string>{"", _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<ContractDefinition const*, shared_ptr<Compiler const>> otherCompilers;
std::map<ContractDefinition const*, std::shared_ptr<Compiler const>> otherCompilers;
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->nodes())
@ -719,7 +719,7 @@ bool CompilerStack::compile(State _stopAfter)
boost::get_error_info<langutil::errinfo_sourceLocation>(_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<string> CompilerStack::contractNames() const
std::vector<std::string> CompilerStack::contractNames() const
{
if (m_stackState < Parsed)
solThrow(CompilerError, "Parsing was not successful.");
vector<string> contractNames;
std::vector<std::string> contractNames;
for (auto const& contract: m_contracts)
contractNames.push_back(contract.first);
return contractNames;
}
string const CompilerStack::lastContractName(optional<string> const& _sourceName) const
std::string const CompilerStack::lastContractName(std::optional<std::string> 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<ContractDefinition>(it.second.ast->nodes()))
@ -774,7 +774,7 @@ string const CompilerStack::lastContractName(optional<string> 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 ? &currentContract.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 ? &currentContract.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<yul::Block> parserResult = yul::Parser{errorReporter, dialect}.parse(charStream);
std::shared_ptr<yul::Block> 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<string> CompilerStack::sourceNames() const
std::vector<std::string> CompilerStack::sourceNames() const
{
return ranges::to<vector>(m_sources | ranges::views::keys);
return ranges::to<std::vector>(m_sources | ranges::views::keys);
}
map<string, unsigned> CompilerStack::sourceIndices() const
std::map<std::string, unsigned> CompilerStack::sourceIndices() const
{
map<string, unsigned> indices;
std::map<std::string, unsigned> indices;
unsigned index = 0;
for (auto const& s: m_sources)
indices[s.first] = index++;
@ -978,7 +978,7 @@ map<string, unsigned> 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<ImportDirective*>(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<Source const*> sourceOrder;
set<Source const*> sourcesSeen;
std::vector<Source const*> sourceOrder;
std::set<Source const*> sourcesSeen;
function<void(Source const*)> toposort = [&](Source const* _source)
std::function<void(Source const*)> toposort = [&](Source const* _source)
{
if (sourcesSeen.count(_source))
return;
@ -1223,7 +1223,7 @@ bool CompilerStack::resolveImports()
for (ASTPointer<ASTNode> const& node: _source->ast->nodes())
if (ImportDirective const* import = dynamic_cast<ImportDirective*>(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<PragmaDirective const*> experimentalPragmaDirectives;
std::vector<PragmaDirective const*> experimentalPragmaDirectives;
for (auto const& sourcePair: m_sources)
{
if (isRequestedSource(sourcePair.first))
@ -1270,7 +1270,7 @@ void CompilerStack::storeContractDefinitions()
ASTNode::filteredNodes<ContractDefinition>(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<CallableDeclaration const*>(&node))
if (auto const* callable = std::get_if<CallableDeclaration const*>(&node))
if (auto const* function = dynamic_cast<FunctionDefinition const*>(*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<CallableDeclaration const*>(&node))
if (auto const* callable = std::get_if<CallableDeclaration const*>(&node))
if (auto const* function = dynamic_cast<FunctionDefinition const*>(*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<ExperimentalFeature> const& features)
bool onlySafeExperimentalFeaturesActivated(std::set<ExperimentalFeature> const& features)
{
for (auto const feature: features)
if (!ExperimentalFeatureWithoutWarning.count(feature))
@ -1322,8 +1322,8 @@ bool onlySafeExperimentalFeaturesActivated(set<ExperimentalFeature> const& featu
void CompilerStack::assembleYul(
ContractDefinition const& _contract,
shared_ptr<evmasm::Assembly> _assembly,
shared_ptr<evmasm::Assembly> _runtimeAssembly
std::shared_ptr<evmasm::Assembly> _assembly,
std::shared_ptr<evmasm::Assembly> _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<ContractDefinition const*, shared_ptr<Compiler const>>& _otherCompilers
std::map<ContractDefinition const*, std::shared_ptr<Compiler const>>& _otherCompilers
)
{
solAssert(!m_viaIR, "");
@ -1415,7 +1415,7 @@ void CompilerStack::compileContract(
Contract& compiledContract = m_contracts.at(_contract.fullyQualifiedName());
shared_ptr<Compiler> compiler = make_shared<Compiler>(m_evmVersion, m_revertStrings, m_optimiserSettings);
std::shared_ptr<Compiler> compiler = std::make_shared<Compiler>(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<ContractDefinition const*, string_view const> otherYulSources;
std::map<ContractDefinition const*, std::string_view const> 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 <source>:<contract>
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<string> referencedSources;
std::set<std::string> 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<string> licenseString = s.second.ast->licenseString())
if (std::optional<std::string> 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<Json::LargestUInt>(m_optimiserSettings.expectedExecutionsPerDeployment) < numeric_limits<Json::LargestUInt>::max(), "");
solAssert(static_cast<Json::LargestUInt>(m_optimiserSettings.expectedExecutionsPerDeployment) < std::numeric_limits<Json::LargestUInt>::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<string> hashes{"ipfs", "bzzr1", "none"};
static std::vector<std::string> 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<string> remappings;
std::set<std::string> 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() ? "" : ",");

View File

@ -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<boost::filesystem::path> const& _includePaths,
std::vector<boost::filesystem::path> 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<boost::filesystem::path> candidates;
vector<reference_wrapper<boost::filesystem::path>> prefixes = {m_basePath};
prefixes += (m_includePaths | ranges::to<vector<reference_wrapper<boost::filesystem::path>>>);
std::vector<boost::filesystem::path> candidates;
std::vector<std::reference_wrapper<boost::filesystem::path>> prefixes = {m_basePath};
prefixes += (m_includePaths | ranges::to<std::vector<std::reference_wrapper<boost::filesystem::path>>>);
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<boost::filesystem::path> prefixes = {m_basePath.empty() ? normalizeCLIPathForVFS(".") : m_basePath};
std::vector<boost::filesystem::path> 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<string, FileReader::FileSystemPathSet> FileReader::detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const
std::map<std::string, FileReader::FileSystemPathSet> FileReader::detectSourceUnitNameCollisions(FileSystemPathSet const& _cliPaths) const
{
map<string, FileReader::FileSystemPathSet> nameToPaths;
std::map<std::string, FileReader::FileSystemPathSet> 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<string, FileReader::FileSystemPathSet> collisions;
std::map<std::string, FileReader::FileSystemPathSet> 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 ||

View File

@ -37,7 +37,6 @@
#include <map>
#include <memory>
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<KnownState>();
auto state = std::make_shared<KnownState>();
if (!_signature.empty())
{
ExpressionClasses& classes = state->expressionClasses();
using Id = ExpressionClasses::Id;
using Ids = vector<Id>;
using Ids = std::vector<Id>;
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<KnownState>();
auto state = std::make_shared<KnownState>();
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<ASTNode const*> GasEstimator::finestNodesAtLocation(
vector<ASTNode const*> const& _roots
std::set<ASTNode const*> GasEstimator::finestNodesAtLocation(
std::vector<ASTNode const*> const& _roots
)
{
map<SourceLocation, ASTNode const*> locations;
set<ASTNode const*> nodes;
SimpleASTVisitor visitor(function<bool(ASTNode const&)>(), [&](ASTNode const& _n)
std::map<SourceLocation, ASTNode const*> locations;
std::set<ASTNode const*> nodes;
SimpleASTVisitor visitor(std::function<bool(ASTNode const&)>(), [&](ASTNode const& _n)
{
if (!locations.count(_n.location()))
{

View File

@ -19,29 +19,20 @@
#include <libsolutil/CommonIO.h>
#include <liblangutil/Exceptions.h>
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<Remapping> _remappings)
void ImportRemapper::setRemappings(std::vector<Remapping> _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<string::difference_type>(longestPrefix), _path.end());
std::string path = bestMatchTarget;
path.append(_path.begin() + static_cast<std::string::difference_type>(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::Remapping> ImportRemapper::parseRemapping(string_view _input)
std::optional<ImportRemapper::Remapping> 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;
}

View File

@ -30,8 +30,6 @@
#include <boost/algorithm/string.hpp>
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<FunctionDefinition const*>(&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<std::string, DocTag> const& _tags, vector<string> const& _returnParameterNames)
Json::Value Natspec::extractReturnParameterDocs(std::multimap<std::string, DocTag> const& _tags, std::vector<std::string> const& _returnParameterNames)
{
Json::Value jsonReturn{Json::objectValue};
auto returnDocs = _tags.equal_range("return");
@ -188,8 +186,8 @@ Json::Value Natspec::extractReturnParameterDocs(std::multimap<std::string, DocTa
size_t n = 0;
for (auto i = returnDocs.first; i != returnDocs.second; i++)
{
string paramName = _returnParameterNames.at(n);
string content = i->second.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<std::string, DocTa
return jsonReturn;
}
string Natspec::extractDoc(multimap<string, DocTag> const& _tags, string const& _name)
std::string Natspec::extractDoc(std::multimap<std::string, DocTag> 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<string, DocTag> const& _tags)
Json::Value Natspec::extractCustomDoc(std::multimap<std::string, DocTag> const& _tags)
{
std::map<string, string> concatenated;
std::map<std::string, std::string> 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<std::string, DocTag> const&
return json;
}
vector<EventDefinition const*> Natspec::uniqueInterfaceEvents(ContractDefinition const& _contract)
std::vector<EventDefinition const*> 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<EventDefinition const*> Natspec::uniqueInterfaceEvents(ContractDefinitio
return eventSignature(_lhs) < eventSignature(_rhs);
};
set<EventDefinition const*, decltype(compareBySignature)> uniqueEvents{compareBySignature};
std::set<EventDefinition const*, decltype(compareBySignature)> 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<EventDefinition const*, decltype(compareBySignature)> filteredUsedEvents{compareBySignature};
set<string> usedSignatures;
std::set<EventDefinition const*, decltype(compareBySignature)> filteredUsedEvents{compareBySignature};
std::set<std::string> usedSignatures;
for (EventDefinition const* event: _contract.usedInterfaceEvents())
{
auto&& [eventIt, eventInserted] = filteredUsedEvents.insert(event);
@ -283,5 +281,5 @@ vector<EventDefinition const*> Natspec::uniqueInterfaceEvents(ContractDefinitio
}
uniqueEvents += filteredUsedEvents;
return util::convertContainer<vector<EventDefinition const*>>(std::move(uniqueEvents));
return util::convertContainer<std::vector<EventDefinition const*>>(std::move(uniqueEvents));
}

View File

@ -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<string> data;
string line;
std::vector<std::string> data;
std::string line;
while (eld.running() && std::getline(pipe, line))
if (!line.empty())
data.push_back(line);

View File

@ -44,20 +44,20 @@
#include <algorithm>
#include <optional>
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> _errorId = nullopt
std::string const& _component,
std::string const& _message,
std::optional<ErrorId> _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<string, set<string>> requestedContractNames(Json::Value const& _outputSelection)
std::map<std::string, std::set<std::string>> requestedContractNames(Json::Value const& _outputSelection)
{
map<string, set<string>> contracts;
std::map<std::string, std::set<std::string>> 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<string, set<string>> 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<string> experimental{"ir", "irAst", "irOptimized", "irOptimizedAst"};
static std::set<std::string> 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<string> contracts{ _contract };
std::vector<std::string> 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<string> const& _artifacts, bool _wildcardMatchesExperimental)
bool isArtifactRequested(Json::Value const& _outputSelection, std::string const& _file, std::string const& _contract, std::vector<std::string> 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<string> evmObjectComponents(string const& _objectKind)
std::vector<std::string> evmObjectComponents(std::string const& _objectKind)
{
solAssert(_objectKind == "bytecode" || _objectKind == "deployedBytecode", "");
vector<string> components{"", ".object", ".opcodes", ".sourceMap", ".functionDebugData", ".generatedSources", ".linkReferences"};
std::vector<std::string> 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<string> const outputsThatRequireBinaries = vector<string>{
static std::vector<std::string> const outputsThatRequireBinaries = std::vector<std::string>{
"*",
"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<string> const outputsThatRequireEvmBinaries = vector<string>{
static std::vector<std::string> const outputsThatRequireEvmBinaries = std::vector<std::string>{
"*",
"evm.gasEstimates", "evm.legacyAssembly", "evm.assembly"
} + evmObjectComponents("bytecode") + evmObjectComponents("deployedBytecode");
@ -320,13 +320,13 @@ Json::Value formatLinkReferences(std::map<size_t, std::string> 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<size_t, std::string> const& linkRefere
return ret;
}
Json::Value formatImmutableReferences(map<u256, pair<string, vector<size_t>>> const& _immutableReferences)
Json::Value formatImmutableReferences(std::map<u256, std::pair<std::string, std::vector<size_t>>> const& _immutableReferences)
{
Json::Value ret{Json::objectValue};
@ -367,10 +367,10 @@ Json::Value formatImmutableReferences(map<u256, pair<string, vector<size_t>>> co
Json::Value collectEVMObject(
langutil::EVMVersion _evmVersion,
evmasm::LinkerObject const& _object,
string const* _sourceMap,
std::string const* _sourceMap,
Json::Value _generatedSources,
bool _runtimeObject,
function<bool(string)> const& _artifactRequested
std::function<bool(std::string)> const& _artifactRequested
)
{
Json::Value output{Json::objectValue};
@ -391,7 +391,7 @@ Json::Value collectEVMObject(
return output;
}
std::optional<Json::Value> checkKeys(Json::Value const& _input, set<string> const& _keys, string const& _name)
std::optional<Json::Value> checkKeys(Json::Value const& _input, std::set<std::string> 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<Json::Value> checkKeys(Json::Value const& _input, set<string> cons
std::optional<Json::Value> checkRootKeys(Json::Value const& _input)
{
static set<string> keys{"auxiliaryInput", "language", "settings", "sources"};
static std::set<std::string> keys{"auxiliaryInput", "language", "settings", "sources"};
return checkKeys(_input, keys, "root");
}
std::optional<Json::Value> checkSourceKeys(Json::Value const& _input, string const& _name)
std::optional<Json::Value> checkSourceKeys(Json::Value const& _input, std::string const& _name)
{
static set<string> keys{"content", "keccak256", "urls"};
static std::set<std::string> keys{"content", "keccak256", "urls"};
return checkKeys(_input, keys, "sources." + _name);
}
std::optional<Json::Value> checkAuxiliaryInputKeys(Json::Value const& _input)
{
static set<string> keys{"smtlib2responses"};
static std::set<std::string> keys{"smtlib2responses"};
return checkKeys(_input, keys, "auxiliaryInput");
}
std::optional<Json::Value> checkSettingsKeys(Json::Value const& _input)
{
static set<string> keys{"parserErrorRecovery", "debug", "evmVersion", "libraries", "metadata", "modelChecker", "optimizer", "outputSelection", "remappings", "stopAfter", "viaIR"};
static std::set<std::string> keys{"parserErrorRecovery", "debug", "evmVersion", "libraries", "metadata", "modelChecker", "optimizer", "outputSelection", "remappings", "stopAfter", "viaIR"};
return checkKeys(_input, keys, "settings");
}
std::optional<Json::Value> checkModelCheckerSettingsKeys(Json::Value const& _input)
{
static set<string> keys{"bmcLoopIterations", "contracts", "divModNoSlacks", "engine", "extCalls", "invariants", "printQuery", "showProvedSafe", "showUnproved", "showUnsupported", "solvers", "targets", "timeout"};
static std::set<std::string> keys{"bmcLoopIterations", "contracts", "divModNoSlacks", "engine", "extCalls", "invariants", "printQuery", "showProvedSafe", "showUnproved", "showUnsupported", "solvers", "targets", "timeout"};
return checkKeys(_input, keys, "modelChecker");
}
std::optional<Json::Value> checkOptimizerKeys(Json::Value const& _input)
{
static set<string> keys{"details", "enabled", "runs"};
static std::set<std::string> keys{"details", "enabled", "runs"};
return checkKeys(_input, keys, "settings.optimizer");
}
std::optional<Json::Value> checkOptimizerDetailsKeys(Json::Value const& _input)
{
static set<string> keys{"peephole", "inliner", "jumpdestRemover", "orderLiterals", "deduplicate", "cse", "constantOptimizer", "yul", "yulDetails"};
static std::set<std::string> keys{"peephole", "inliner", "jumpdestRemover", "orderLiterals", "deduplicate", "cse", "constantOptimizer", "yul", "yulDetails"};
return checkKeys(_input, keys, "settings.optimizer.details");
}
@ -456,7 +456,7 @@ std::optional<Json::Value> checkOptimizerDetail(Json::Value const& _details, std
return {};
}
std::optional<Json::Value> checkOptimizerDetailSteps(Json::Value const& _details, std::string const& _name, string& _optimiserSetting, string& _cleanupSetting)
std::optional<Json::Value> 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<Json::Value> 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<Json::Value> 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<string> hashes{"ipfs", "bzzr1", "none"};
static std::set<std::string> 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<string> keys{"appendCBOR", "useLiteralContent", "bytecodeHash"};
static std::set<std::string> keys{"appendCBOR", "useLiteralContent", "bytecodeHash"};
return checkKeys(_input, keys, "settings.metadata");
}
@ -645,7 +645,7 @@ std::variant<StandardCompiler::InputsAndSettings, Json::Value> 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::InputsAndSettings, Json::Value> 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::InputsAndSettings, Json::Value> StandardCompiler:
Error::Type::JSONError, "No import callback supplied, but URL is requested."
);
vector<string> failures;
std::vector<std::string> failures;
bool found = false;
for (auto const& url: sources[sourceName]["urls"])
@ -832,11 +832,11 @@ std::variant<StandardCompiler::InputsAndSettings, Json::Value> StandardCompiler:
if (!settings["debug"]["debugInfo"].isArray())
return formatFatalError(Error::Type::JSONError, "settings.debug.debugInfo must be an array.");
vector<string> components;
std::vector<std::string> components;
for (Json::Value const& arrayValue: settings["debug"]["debugInfo"])
components.push_back(arrayValue.asString());
optional<DebugInfoSelection> debugInfoSelection = DebugInfoSelection::fromComponents(
std::optional<DebugInfoSelection> debugInfoSelection = DebugInfoSelection::fromComponents(
components,
true /* _acceptWildcards */
);
@ -887,7 +887,7 @@ std::variant<StandardCompiler::InputsAndSettings, Json::Value> 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::InputsAndSettings, Json::Value> StandardCompiler:
if (!sources.isObject() && !sources.isNull())
return formatFatalError(Error::Type::JSONError, "settings.modelChecker.contracts is not a JSON object.");
map<string, set<string>> sourceContracts;
std::map<std::string, std::set<std::string>> sourceContracts;
for (auto const& source: sources.getMemberNames())
{
if (source.empty())
@ -1138,14 +1138,14 @@ std::variant<StandardCompiler::InputsAndSettings, Json::Value> StandardCompiler:
return {std::move(ret)};
}
map<string, Json::Value> StandardCompiler::parseAstFromInput(StringMap const& _sources)
std::map<std::string, Json::Value> StandardCompiler::parseAstFromInput(StringMap const& _sources)
{
map<string, Json::Value> sourceJsons;
std::map<std::string, Json::Value> 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<string>())
for (std::string const& contractName: analysisPerformed ? compilerStack.contractNames() : std::vector<std::string>())
{
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 const>(error);
auto err = std::dynamic_pointer_cast<Error const>(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<string, evmasm::LinkerObject::FunctionDebugData> const& _debugInfo
std::map<std::string, evmasm::LinkerObject::FunctionDebugData> const& _debugInfo
)
{
Json::Value ret(Json::objectValue);

View File

@ -20,7 +20,6 @@
#include <libsolidity/ast/TypeProvider.h>
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<ReferenceType const*>(_type))
return TypeProvider::withLocationIfReference(refType->location(), _type)->richIdentifier();

View File

@ -25,19 +25,17 @@
#include <solidity/BuildInfo.h>
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();

View File

@ -30,6 +30,7 @@ NAMESPACE_STD_FREE_FILES=(
libsolidity/codegen/ir/*
libsolidity/codegen/*
libsolidity/formal/*
libsolidity/interface/*
)
(