Purge using namespace std from solc

Signed-off-by: Jun Zhang <jun@junz.org>
This commit is contained in:
Jun Zhang 2023-08-23 10:51:26 +08:00
parent 60b18a13d2
commit 86ed964c6a
No known key found for this signature in database
GPG Key ID: E19904830B621534
4 changed files with 303 additions and 305 deletions

View File

@ -34,6 +34,7 @@ NAMESPACE_STD_FREE_FILES=(
libsolidity/lsp/* libsolidity/lsp/*
libsolidity/parsing/* libsolidity/parsing/*
libsolutil/* libsolutil/*
solc/*
) )
( (

View File

@ -81,8 +81,7 @@
#define STDERR_FILENO 2 #define STDERR_FILENO 2
#endif #endif
using namespace std::string_literals;
using namespace std;
using namespace solidity; using namespace solidity;
using namespace solidity::util; using namespace solidity::util;
using namespace solidity::langutil; using namespace solidity::langutil;
@ -90,7 +89,7 @@ using namespace solidity::langutil;
namespace namespace
{ {
set<frontend::InputMode> const CompilerInputModes{ std::set<frontend::InputMode> const CompilerInputModes{
frontend::InputMode::Compiler, frontend::InputMode::Compiler,
frontend::InputMode::CompilerWithASTImport, frontend::InputMode::CompilerWithASTImport,
}; };
@ -100,14 +99,14 @@ set<frontend::InputMode> const CompilerInputModes{
namespace solidity::frontend namespace solidity::frontend
{ {
ostream& CommandLineInterface::sout(bool _markAsUsed) std::ostream& CommandLineInterface::sout(bool _markAsUsed)
{ {
if (_markAsUsed) if (_markAsUsed)
m_hasOutput = true; m_hasOutput = true;
return m_sout; return m_sout;
} }
ostream& CommandLineInterface::serr(bool _markAsUsed) std::ostream& CommandLineInterface::serr(bool _markAsUsed)
{ {
if (_markAsUsed) if (_markAsUsed)
m_hasOutput = true; m_hasOutput = true;
@ -118,27 +117,27 @@ ostream& CommandLineInterface::serr(bool _markAsUsed)
#define cout #define cout
#define cerr #define cerr
static string const g_stdinFileName = "<stdin>"; static std::string const g_stdinFileName = "<stdin>";
static string const g_strAbi = "abi"; static std::string const g_strAbi = "abi";
static string const g_strAsm = "asm"; static std::string const g_strAsm = "asm";
static string const g_strAst = "ast"; static std::string const g_strAst = "ast";
static string const g_strBinary = "bin"; static std::string const g_strBinary = "bin";
static string const g_strBinaryRuntime = "bin-runtime"; static std::string const g_strBinaryRuntime = "bin-runtime";
static string const g_strContracts = "contracts"; static std::string const g_strContracts = "contracts";
static string const g_strFunDebug = "function-debug"; static std::string const g_strFunDebug = "function-debug";
static string const g_strFunDebugRuntime = "function-debug-runtime"; static std::string const g_strFunDebugRuntime = "function-debug-runtime";
static string const g_strGeneratedSources = "generated-sources"; static std::string const g_strGeneratedSources = "generated-sources";
static string const g_strGeneratedSourcesRuntime = "generated-sources-runtime"; static std::string const g_strGeneratedSourcesRuntime = "generated-sources-runtime";
static string const g_strNatspecDev = "devdoc"; static std::string const g_strNatspecDev = "devdoc";
static string const g_strNatspecUser = "userdoc"; static std::string const g_strNatspecUser = "userdoc";
static string const g_strOpcodes = "opcodes"; static std::string const g_strOpcodes = "opcodes";
static string const g_strSignatureHashes = "hashes"; static std::string const g_strSignatureHashes = "hashes";
static string const g_strSourceList = "sourceList"; static std::string const g_strSourceList = "sourceList";
static string const g_strSources = "sources"; static std::string const g_strSources = "sources";
static string const g_strSrcMap = "srcmap"; static std::string const g_strSrcMap = "srcmap";
static string const g_strSrcMapRuntime = "srcmap-runtime"; static std::string const g_strSrcMapRuntime = "srcmap-runtime";
static string const g_strStorageLayout = "storage-layout"; static std::string const g_strStorageLayout = "storage-layout";
static string const g_strVersion = "version"; static std::string const g_strVersion = "version";
static bool needsHumanTargetedStdout(CommandLineOptions const& _options) static bool needsHumanTargetedStdout(CommandLineOptions const& _options)
{ {
@ -167,7 +166,7 @@ static bool coloredOutput(CommandLineOptions const& _options)
(_options.formatting.coloredOutput.has_value() && _options.formatting.coloredOutput.value()); (_options.formatting.coloredOutput.has_value() && _options.formatting.coloredOutput.value());
} }
void CommandLineInterface::handleBinary(string const& _contract) void CommandLineInterface::handleBinary(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -177,8 +176,8 @@ void CommandLineInterface::handleBinary(string const& _contract)
createFile(m_compiler->filesystemFriendlyName(_contract) + ".bin", objectWithLinkRefsHex(m_compiler->object(_contract))); createFile(m_compiler->filesystemFriendlyName(_contract) + ".bin", objectWithLinkRefsHex(m_compiler->object(_contract)));
else else
{ {
sout() << "Binary:" << endl; sout() << "Binary:" << std::endl;
sout() << objectWithLinkRefsHex(m_compiler->object(_contract)) << endl; sout() << objectWithLinkRefsHex(m_compiler->object(_contract)) << std::endl;
} }
} }
if (m_options.compiler.outputs.binaryRuntime) if (m_options.compiler.outputs.binaryRuntime)
@ -187,13 +186,13 @@ void CommandLineInterface::handleBinary(string const& _contract)
createFile(m_compiler->filesystemFriendlyName(_contract) + ".bin-runtime", objectWithLinkRefsHex(m_compiler->runtimeObject(_contract))); createFile(m_compiler->filesystemFriendlyName(_contract) + ".bin-runtime", objectWithLinkRefsHex(m_compiler->runtimeObject(_contract)));
else else
{ {
sout() << "Binary of the runtime part:" << endl; sout() << "Binary of the runtime part:" << std::endl;
sout() << objectWithLinkRefsHex(m_compiler->runtimeObject(_contract)) << endl; sout() << objectWithLinkRefsHex(m_compiler->runtimeObject(_contract)) << std::endl;
} }
} }
} }
void CommandLineInterface::handleOpcode(string const& _contract) void CommandLineInterface::handleOpcode(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -201,13 +200,13 @@ void CommandLineInterface::handleOpcode(string const& _contract)
createFile(m_compiler->filesystemFriendlyName(_contract) + ".opcode", evmasm::disassemble(m_compiler->object(_contract).bytecode, m_options.output.evmVersion)); createFile(m_compiler->filesystemFriendlyName(_contract) + ".opcode", evmasm::disassemble(m_compiler->object(_contract).bytecode, m_options.output.evmVersion));
else else
{ {
sout() << "Opcodes:" << endl; sout() << "Opcodes:" << std::endl;
sout() << uppercase << evmasm::disassemble(m_compiler->object(_contract).bytecode, m_options.output.evmVersion); sout() << std::uppercase << evmasm::disassemble(m_compiler->object(_contract).bytecode, m_options.output.evmVersion);
sout() << endl; sout() << std::endl;
} }
} }
void CommandLineInterface::handleIR(string const& _contractName) void CommandLineInterface::handleIR(std::string const& _contractName)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -218,12 +217,12 @@ void CommandLineInterface::handleIR(string const& _contractName)
createFile(m_compiler->filesystemFriendlyName(_contractName) + ".yul", m_compiler->yulIR(_contractName)); createFile(m_compiler->filesystemFriendlyName(_contractName) + ".yul", m_compiler->yulIR(_contractName));
else else
{ {
sout() << "IR:" << endl; sout() << "IR:" << std::endl;
sout() << m_compiler->yulIR(_contractName) << endl; sout() << m_compiler->yulIR(_contractName) << std::endl;
} }
} }
void CommandLineInterface::handleIRAst(string const& _contractName) void CommandLineInterface::handleIRAst(std::string const& _contractName)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -240,15 +239,15 @@ void CommandLineInterface::handleIRAst(string const& _contractName)
); );
else else
{ {
sout() << "IR AST:" << endl; sout() << "IR AST:" << std::endl;
sout() << util::jsonPrint( sout() << util::jsonPrint(
m_compiler->yulIRAst(_contractName), m_compiler->yulIRAst(_contractName),
m_options.formatting.json m_options.formatting.json
) << endl; ) << std::endl;
} }
} }
void CommandLineInterface::handleIROptimized(string const& _contractName) void CommandLineInterface::handleIROptimized(std::string const& _contractName)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -262,12 +261,12 @@ void CommandLineInterface::handleIROptimized(string const& _contractName)
); );
else else
{ {
sout() << "Optimized IR:" << endl; sout() << "Optimized IR:" << std::endl;
sout() << m_compiler->yulIROptimized(_contractName) << endl; sout() << m_compiler->yulIROptimized(_contractName) << std::endl;
} }
} }
void CommandLineInterface::handleIROptimizedAst(string const& _contractName) void CommandLineInterface::handleIROptimizedAst(std::string const& _contractName)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -284,15 +283,15 @@ void CommandLineInterface::handleIROptimizedAst(string const& _contractName)
); );
else else
{ {
sout() << "Optimized IR AST:" << endl; sout() << "Optimized IR AST:" << std::endl;
sout() << util::jsonPrint( sout() << util::jsonPrint(
m_compiler->yulIROptimizedAst(_contractName), m_compiler->yulIROptimizedAst(_contractName),
m_options.formatting.json m_options.formatting.json
) << endl; ) << std::endl;
} }
} }
void CommandLineInterface::handleBytecode(string const& _contract) void CommandLineInterface::handleBytecode(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -302,7 +301,7 @@ void CommandLineInterface::handleBytecode(string const& _contract)
handleBinary(_contract); handleBinary(_contract);
} }
void CommandLineInterface::handleSignatureHashes(string const& _contract) void CommandLineInterface::handleSignatureHashes(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
@ -310,7 +309,7 @@ void CommandLineInterface::handleSignatureHashes(string const& _contract)
return; return;
Json::Value interfaceSymbols = m_compiler->interfaceSymbols(_contract); Json::Value interfaceSymbols = m_compiler->interfaceSymbols(_contract);
string out = "Function signatures:\n"; std::string out = "Function signatures:\n";
for (auto const& name: interfaceSymbols["methods"].getMemberNames()) for (auto const& name: interfaceSymbols["methods"].getMemberNames())
out += interfaceSymbols["methods"][name].asString() + ": " + name + "\n"; out += interfaceSymbols["methods"][name].asString() + ": " + name + "\n";
@ -334,55 +333,55 @@ void CommandLineInterface::handleSignatureHashes(string const& _contract)
sout() << out; sout() << out;
} }
void CommandLineInterface::handleMetadata(string const& _contract) void CommandLineInterface::handleMetadata(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.metadata) if (!m_options.compiler.outputs.metadata)
return; return;
string data = m_compiler->metadata(_contract); std::string data = m_compiler->metadata(_contract);
if (!m_options.output.dir.empty()) if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + "_meta.json", data); createFile(m_compiler->filesystemFriendlyName(_contract) + "_meta.json", data);
else else
sout() << "Metadata:" << endl << data << endl; sout() << "Metadata:" << std::endl << data << std::endl;
} }
void CommandLineInterface::handleABI(string const& _contract) void CommandLineInterface::handleABI(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.abi) if (!m_options.compiler.outputs.abi)
return; return;
string data = jsonPrint(removeNullMembers(m_compiler->contractABI(_contract)), m_options.formatting.json); std::string data = jsonPrint(removeNullMembers(m_compiler->contractABI(_contract)), m_options.formatting.json);
if (!m_options.output.dir.empty()) if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + ".abi", data); createFile(m_compiler->filesystemFriendlyName(_contract) + ".abi", data);
else else
sout() << "Contract JSON ABI" << endl << data << endl; sout() << "Contract JSON ABI" << std::endl << data << std::endl;
} }
void CommandLineInterface::handleStorageLayout(string const& _contract) void CommandLineInterface::handleStorageLayout(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.storageLayout) if (!m_options.compiler.outputs.storageLayout)
return; return;
string data = jsonPrint(removeNullMembers(m_compiler->storageLayout(_contract)), m_options.formatting.json); std::string data = jsonPrint(removeNullMembers(m_compiler->storageLayout(_contract)), m_options.formatting.json);
if (!m_options.output.dir.empty()) if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + "_storage.json", data); createFile(m_compiler->filesystemFriendlyName(_contract) + "_storage.json", data);
else else
sout() << "Contract Storage Layout:" << endl << data << endl; sout() << "Contract Storage Layout:" << std::endl << data << std::endl;
} }
void CommandLineInterface::handleNatspec(bool _natspecDev, string const& _contract) void CommandLineInterface::handleNatspec(bool _natspecDev, std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
bool enabled = false; bool enabled = false;
string suffix; std::string suffix;
string title; std::string title;
if (_natspecDev) if (_natspecDev)
{ {
@ -399,7 +398,7 @@ void CommandLineInterface::handleNatspec(bool _natspecDev, string const& _contra
if (enabled) if (enabled)
{ {
string output = jsonPrint( std::string output = jsonPrint(
removeNullMembers( removeNullMembers(
_natspecDev ? _natspecDev ?
m_compiler->natspecDev(_contract) : m_compiler->natspecDev(_contract) :
@ -412,51 +411,51 @@ void CommandLineInterface::handleNatspec(bool _natspecDev, string const& _contra
createFile(m_compiler->filesystemFriendlyName(_contract) + suffix, output); createFile(m_compiler->filesystemFriendlyName(_contract) + suffix, output);
else else
{ {
sout() << title << endl; sout() << title << std::endl;
sout() << output << endl; sout() << output << std::endl;
} }
} }
} }
void CommandLineInterface::handleGasEstimation(string const& _contract) void CommandLineInterface::handleGasEstimation(std::string const& _contract)
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
Json::Value estimates = m_compiler->gasEstimates(_contract); Json::Value estimates = m_compiler->gasEstimates(_contract);
sout() << "Gas estimation:" << endl; sout() << "Gas estimation:" << std::endl;
if (estimates["creation"].isObject()) if (estimates["creation"].isObject())
{ {
Json::Value creation = estimates["creation"]; Json::Value creation = estimates["creation"];
sout() << "construction:" << endl; sout() << "construction:" << std::endl;
sout() << " " << creation["executionCost"].asString(); sout() << " " << creation["executionCost"].asString();
sout() << " + " << creation["codeDepositCost"].asString(); sout() << " + " << creation["codeDepositCost"].asString();
sout() << " = " << creation["totalCost"].asString() << endl; sout() << " = " << creation["totalCost"].asString() << std::endl;
} }
if (estimates["external"].isObject()) if (estimates["external"].isObject())
{ {
Json::Value externalFunctions = estimates["external"]; Json::Value externalFunctions = estimates["external"];
sout() << "external:" << endl; sout() << "external:" << std::endl;
for (auto const& name: externalFunctions.getMemberNames()) for (auto const& name: externalFunctions.getMemberNames())
{ {
if (name.empty()) if (name.empty())
sout() << " fallback:\t"; sout() << " fallback:\t";
else else
sout() << " " << name << ":\t"; sout() << " " << name << ":\t";
sout() << externalFunctions[name].asString() << endl; sout() << externalFunctions[name].asString() << std::endl;
} }
} }
if (estimates["internal"].isObject()) if (estimates["internal"].isObject())
{ {
Json::Value internalFunctions = estimates["internal"]; Json::Value internalFunctions = estimates["internal"];
sout() << "internal:" << endl; sout() << "internal:" << std::endl;
for (auto const& name: internalFunctions.getMemberNames()) for (auto const& name: internalFunctions.getMemberNames())
{ {
sout() << " " << name << ":\t"; sout() << " " << name << ":\t";
sout() << internalFunctions[name].asString() << endl; sout() << internalFunctions[name].asString() << std::endl;
} }
} }
} }
@ -465,7 +464,7 @@ void CommandLineInterface::readInputFiles()
{ {
solAssert(!m_standardJsonInput.has_value()); solAssert(!m_standardJsonInput.has_value());
static set<frontend::InputMode> const noInputFiles{ static std::set<frontend::InputMode> const noInputFiles{
frontend::InputMode::Help, frontend::InputMode::Help,
frontend::InputMode::License, frontend::InputMode::License,
frontend::InputMode::Version frontend::InputMode::Version
@ -491,13 +490,13 @@ void CommandLineInterface::readInputFiles()
for (boost::filesystem::path const& allowedDirectory: m_options.input.allowedDirectories) for (boost::filesystem::path const& allowedDirectory: m_options.input.allowedDirectories)
m_fileReader.allowDirectory(allowedDirectory); m_fileReader.allowDirectory(allowedDirectory);
map<string, set<boost::filesystem::path>> collisions = std::map<std::string, std::set<boost::filesystem::path>> collisions =
m_fileReader.detectSourceUnitNameCollisions(m_options.input.paths); m_fileReader.detectSourceUnitNameCollisions(m_options.input.paths);
if (!collisions.empty()) if (!collisions.empty())
{ {
auto pathToQuotedString = [](boost::filesystem::path const& _path){ return "\"" + _path.string() + "\""; }; auto pathToQuotedString = [](boost::filesystem::path const& _path){ return "\"" + _path.string() + "\""; };
string message = std::string message =
"Source unit name collision detected. " "Source unit name collision detected. "
"The specified values of base path and/or include paths would result in multiple " "The specified values of base path and/or include paths would result in multiple "
"input files being assigned the same source unit name:\n"; "input files being assigned the same source unit name:\n";
@ -518,7 +517,7 @@ void CommandLineInterface::readInputFiles()
if (!m_options.input.ignoreMissingFiles) if (!m_options.input.ignoreMissingFiles)
solThrow(CommandLineValidationError, '"' + infile.string() + "\" is not found."); solThrow(CommandLineValidationError, '"' + infile.string() + "\" is not found.");
else else
serr() << infile << " is not found. Skipping." << endl; serr() << infile << " is not found. Skipping." << std::endl;
continue; continue;
} }
@ -528,13 +527,13 @@ void CommandLineInterface::readInputFiles()
if (!m_options.input.ignoreMissingFiles) if (!m_options.input.ignoreMissingFiles)
solThrow(CommandLineValidationError, '"' + infile.string() + "\" is not a valid file."); solThrow(CommandLineValidationError, '"' + infile.string() + "\" is not a valid file.");
else else
serr() << infile << " is not a valid file. Skipping." << endl; serr() << infile << " is not a valid file. Skipping." << std::endl;
continue; continue;
} }
// NOTE: we ignore the FileNotFound exception as we manually check above // NOTE: we ignore the FileNotFound exception as we manually check above
string fileContent = readFileAsString(infile); std::string fileContent = readFileAsString(infile);
if (m_options.input.mode == InputMode::StandardJson) if (m_options.input.mode == InputMode::StandardJson)
{ {
solAssert(!m_standardJsonInput.has_value()); solAssert(!m_standardJsonInput.has_value());
@ -566,12 +565,12 @@ void CommandLineInterface::readInputFiles()
solThrow(CommandLineValidationError, "All specified input files either do not exist or are not regular files."); solThrow(CommandLineValidationError, "All specified input files either do not exist or are not regular files.");
} }
map<string, Json::Value> CommandLineInterface::parseAstFromInput() std::map<std::string, Json::Value> CommandLineInterface::parseAstFromInput()
{ {
solAssert(m_options.input.mode == InputMode::CompilerWithASTImport); solAssert(m_options.input.mode == InputMode::CompilerWithASTImport);
map<string, Json::Value> sourceJsons; std::map<std::string, Json::Value> sourceJsons;
map<string, string> tmpSources; std::map<std::string, std::string> tmpSources;
for (SourceCode const& sourceCode: m_fileReader.sourceUnits() | ranges::views::values) for (SourceCode const& sourceCode: m_fileReader.sourceUnits() | ranges::views::values)
{ {
@ -581,7 +580,7 @@ map<string, Json::Value> CommandLineInterface::parseAstFromInput()
for (auto& src: ast["sources"].getMemberNames()) for (auto& src: ast["sources"].getMemberNames())
{ {
string astKey = ast["sources"][src].isMember("ast") ? "ast" : "AST"; std::string astKey = ast["sources"][src].isMember("ast") ? "ast" : "AST";
astAssert(ast["sources"][src].isMember(astKey), "astkey is not member"); astAssert(ast["sources"][src].isMember(astKey), "astkey is not member");
astAssert(ast["sources"][src][astKey]["nodeType"].asString() == "SourceUnit", "Top-level node should be a 'SourceUnit'"); astAssert(ast["sources"][src][astKey]["nodeType"].asString() == "SourceUnit", "Top-level node should be a 'SourceUnit'");
@ -596,7 +595,7 @@ map<string, Json::Value> CommandLineInterface::parseAstFromInput()
return sourceJsons; return sourceJsons;
} }
void CommandLineInterface::createFile(string const& _fileName, string const& _data) void CommandLineInterface::createFile(std::string const& _fileName, std::string const& _data)
{ {
namespace fs = boost::filesystem; namespace fs = boost::filesystem;
@ -607,19 +606,19 @@ void CommandLineInterface::createFile(string const& _fileName, string const& _da
// The simplest workaround is to use an absolute path. // The simplest workaround is to use an absolute path.
fs::create_directories(fs::absolute(m_options.output.dir)); fs::create_directories(fs::absolute(m_options.output.dir));
string pathName = (m_options.output.dir / _fileName).string(); std::string pathName = (m_options.output.dir / _fileName).string();
if (fs::exists(pathName) && !m_options.output.overwriteFiles) if (fs::exists(pathName) && !m_options.output.overwriteFiles)
solThrow(CommandLineOutputError, "Refusing to overwrite existing file \"" + pathName + "\" (use --overwrite to force)."); solThrow(CommandLineOutputError, "Refusing to overwrite existing file \"" + pathName + "\" (use --overwrite to force).");
ofstream outFile(pathName); std::ofstream outFile(pathName);
outFile << _data; outFile << _data;
if (!outFile) if (!outFile)
solThrow(CommandLineOutputError, "Could not write to file \"" + pathName + "\"."); solThrow(CommandLineOutputError, "Could not write to file \"" + pathName + "\".");
} }
void CommandLineInterface::createJson(string const& _fileName, string const& _json) void CommandLineInterface::createJson(std::string const& _fileName, std::string const& _json)
{ {
createFile(boost::filesystem::path(_fileName).stem().string() + string(".json"), _json); createFile(boost::filesystem::path(_fileName).stem().string() + std::string(".json"), _json);
} }
bool CommandLineInterface::run(int _argc, char const* const* _argv) bool CommandLineInterface::run(int _argc, char const* const* _argv)
@ -640,7 +639,7 @@ bool CommandLineInterface::run(int _argc, char const* const* _argv)
// There might be no message in the exception itself if the error output is bulky and has // There might be no message in the exception itself if the error output is bulky and has
// already been printed to stderr (this happens e.g. for compiler errors). // already been printed to stderr (this happens e.g. for compiler errors).
if (_exception.what() != ""s) if (_exception.what() != ""s)
serr() << _exception.what() << endl; serr() << _exception.what() << std::endl;
return false; return false;
} }
@ -683,7 +682,7 @@ void CommandLineInterface::processInput()
solAssert(m_standardJsonInput.has_value()); solAssert(m_standardJsonInput.has_value());
StandardCompiler compiler(m_universalCallback.callback(), m_options.formatting.json); StandardCompiler compiler(m_universalCallback.callback(), m_options.formatting.json);
sout() << compiler.compile(std::move(m_standardJsonInput.value())) << endl; sout() << compiler.compile(std::move(m_standardJsonInput.value())) << std::endl;
m_standardJsonInput.reset(); m_standardJsonInput.reset();
break; break;
} }
@ -707,22 +706,22 @@ void CommandLineInterface::processInput()
void CommandLineInterface::printVersion() void CommandLineInterface::printVersion()
{ {
sout() << "solc, the solidity compiler commandline interface" << endl; sout() << "solc, the solidity compiler commandline interface" << std::endl;
sout() << "Version: " << solidity::frontend::VersionString << endl; sout() << "Version: " << solidity::frontend::VersionString << std::endl;
} }
void CommandLineInterface::printLicense() void CommandLineInterface::printLicense()
{ {
sout() << otherLicenses << endl; sout() << otherLicenses << std::endl;
// This is a static variable generated by cmake from LICENSE.txt // This is a static variable generated by cmake from LICENSE.txt
sout() << licenseText << endl; sout() << licenseText << std::endl;
} }
void CommandLineInterface::compile() void CommandLineInterface::compile()
{ {
solAssert(CompilerInputModes.count(m_options.input.mode) == 1); solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
m_compiler = make_unique<CompilerStack>(m_universalCallback.callback()); m_compiler = std::make_unique<CompilerStack>(m_universalCallback.callback());
SourceReferenceFormatter formatter(serr(false), *m_compiler, coloredOutput(m_options), m_options.formatting.withErrorIds); SourceReferenceFormatter formatter(serr(false), *m_compiler, coloredOutput(m_options), m_options.formatting.withErrorIds);
@ -840,7 +839,7 @@ void CommandLineInterface::handleCombinedJSON()
Json::Value output(Json::objectValue); Json::Value output(Json::objectValue);
output[g_strVersion] = frontend::VersionString; output[g_strVersion] = frontend::VersionString;
vector<string> contracts = m_compiler->contractNames(); std::vector<std::string> contracts = m_compiler->contractNames();
// NOTE: The state checks here are more strict that in Standard JSON. There we allow // NOTE: The state checks here are more strict that in Standard JSON. There we allow
// requesting certain outputs even if compilation fails as long as analysis went ok. // requesting certain outputs even if compilation fails as long as analysis went ok.
@ -848,7 +847,7 @@ void CommandLineInterface::handleCombinedJSON()
if (!contracts.empty()) if (!contracts.empty())
output[g_strContracts] = Json::Value(Json::objectValue); output[g_strContracts] = Json::Value(Json::objectValue);
for (string const& contractName: contracts) for (std::string const& contractName: contracts)
{ {
Json::Value& contractData = output[g_strContracts][contractName] = Json::objectValue; Json::Value& contractData = output[g_strContracts][contractName] = Json::objectValue;
if (m_options.compiler.combinedJsonRequests->abi && compilationSuccess) if (m_options.compiler.combinedJsonRequests->abi && compilationSuccess)
@ -922,11 +921,11 @@ void CommandLineInterface::handleCombinedJSON()
} }
} }
string json = jsonPrint(removeNullMembers(std::move(output)), m_options.formatting.json); std::string json = jsonPrint(removeNullMembers(std::move(output)), m_options.formatting.json);
if (!m_options.output.dir.empty()) if (!m_options.output.dir.empty())
createJson("combined", json); createJson("combined", json);
else else
sout() << json << endl; sout() << json << std::endl;
} }
void CommandLineInterface::handleAst() void CommandLineInterface::handleAst()
@ -936,7 +935,7 @@ void CommandLineInterface::handleAst()
if (!m_options.compiler.outputs.astCompactJson) if (!m_options.compiler.outputs.astCompactJson)
return; return;
vector<ASTNode const*> asts; std::vector<ASTNode const*> asts;
for (auto const& sourceCode: m_fileReader.sourceUnits()) for (auto const& sourceCode: m_fileReader.sourceUnits())
asts.push_back(&m_compiler->ast(sourceCode.first)); asts.push_back(&m_compiler->ast(sourceCode.first));
@ -944,8 +943,8 @@ void CommandLineInterface::handleAst()
{ {
for (auto const& sourceCode: m_fileReader.sourceUnits()) for (auto const& sourceCode: m_fileReader.sourceUnits())
{ {
stringstream data; std::stringstream data;
string postfix = ""; std::string postfix = "";
ASTJsonExporter(m_compiler->state(), m_compiler->sourceIndices()).print(data, m_compiler->ast(sourceCode.first), m_options.formatting.json); ASTJsonExporter(m_compiler->state(), m_compiler->sourceIndices()).print(data, m_compiler->ast(sourceCode.first), m_options.formatting.json);
postfix += "_json"; postfix += "_json";
boost::filesystem::path path(sourceCode.first); boost::filesystem::path path(sourceCode.first);
@ -954,10 +953,10 @@ void CommandLineInterface::handleAst()
} }
else else
{ {
sout() << "JSON AST (compact format):" << endl << endl; sout() << "JSON AST (compact format):" << std::endl << std::endl;
for (auto const& sourceCode: m_fileReader.sourceUnits()) for (auto const& sourceCode: m_fileReader.sourceUnits())
{ {
sout() << endl << "======= " << sourceCode.first << " =======" << endl; sout() << std::endl << "======= " << sourceCode.first << " =======" << std::endl;
ASTJsonExporter(m_compiler->state(), m_compiler->sourceIndices()).print(sout(), m_compiler->ast(sourceCode.first), m_options.formatting.json); ASTJsonExporter(m_compiler->state(), m_compiler->sourceIndices()).print(sout(), m_compiler->ast(sourceCode.first), m_options.formatting.json);
} }
} }
@ -975,11 +974,11 @@ void CommandLineInterface::link()
solAssert(m_options.input.mode == InputMode::Linker); solAssert(m_options.input.mode == InputMode::Linker);
// Map from how the libraries will be named inside the bytecode to their addresses. // Map from how the libraries will be named inside the bytecode to their addresses.
map<string, h160> librariesReplacements; std::map<std::string, h160> librariesReplacements;
int const placeholderSize = 40; // 20 bytes or 40 hex characters int const placeholderSize = 40; // 20 bytes or 40 hex characters
for (auto const& library: m_options.linker.libraries) for (auto const& library: m_options.linker.libraries)
{ {
string const& name = library.first; std::string const& name = library.first;
// Library placeholders are 40 hex digits (20 bytes) that start and end with '__'. // Library placeholders are 40 hex digits (20 bytes) that start and end with '__'.
// This leaves 36 characters for the library identifier. The identifier used to // This leaves 36 characters for the library identifier. The identifier used to
// be just the cropped or '_'-padded library name, but this changed to // be just the cropped or '_'-padded library name, but this changed to
@ -987,7 +986,7 @@ void CommandLineInterface::link()
// We support both ways of linking here. // We support both ways of linking here.
librariesReplacements["__" + evmasm::LinkerObject::libraryPlaceholder(name) + "__"] = library.second; librariesReplacements["__" + evmasm::LinkerObject::libraryPlaceholder(name) + "__"] = library.second;
string replacement = "__"; std::string replacement = "__";
for (size_t i = 0; i < placeholderSize - 4; ++i) for (size_t i = 0; i < placeholderSize - 4; ++i)
replacement.push_back(i < name.size() ? name[i] : '_'); replacement.push_back(i < name.size() ? name[i] : '_');
replacement += "__"; replacement += "__";
@ -1010,18 +1009,18 @@ void CommandLineInterface::link()
) )
solThrow( solThrow(
CommandLineExecutionError, CommandLineExecutionError,
"Error in binary object file " + src.first + " at position " + to_string(it - src.second.begin()) + "\n" + "Error in binary object file " + src.first + " at position " + std::to_string(it - src.second.begin()) + "\n" +
'"' + string(it, it + min(placeholderSize, static_cast<int>(end - it))) + "\" is not a valid link reference." '"' + std::string(it, it + std::min(placeholderSize, static_cast<int>(end - it))) + "\" is not a valid link reference."
); );
string foundPlaceholder(it, it + placeholderSize); std::string foundPlaceholder(it, it + placeholderSize);
if (librariesReplacements.count(foundPlaceholder)) if (librariesReplacements.count(foundPlaceholder))
{ {
string hexStr(util::toHex(librariesReplacements.at(foundPlaceholder).asBytes())); std::string hexStr(util::toHex(librariesReplacements.at(foundPlaceholder).asBytes()));
copy(hexStr.begin(), hexStr.end(), it); copy(hexStr.begin(), hexStr.end(), it);
} }
else else
serr() << "Reference \"" << foundPlaceholder << "\" in file \"" << src.first << "\" still unresolved." << endl; serr() << "Reference \"" << foundPlaceholder << "\" in file \"" << src.first << "\" still unresolved." << std::endl;
it += placeholderSize; it += placeholderSize;
} }
// Remove hints for resolved libraries. // Remove hints for resolved libraries.
@ -1039,25 +1038,25 @@ void CommandLineInterface::writeLinkedFiles()
for (auto const& src: m_fileReader.sourceUnits()) for (auto const& src: m_fileReader.sourceUnits())
if (src.first == g_stdinFileName) if (src.first == g_stdinFileName)
sout() << src.second << endl; sout() << src.second << std::endl;
else else
{ {
ofstream outFile(src.first); std::ofstream outFile(src.first);
outFile << src.second; outFile << src.second;
if (!outFile) if (!outFile)
solThrow(CommandLineOutputError, "Could not write to file " + src.first + ". Aborting."); solThrow(CommandLineOutputError, "Could not write to file " + src.first + ". Aborting.");
} }
sout() << "Linking completed." << endl; sout() << "Linking completed." << std::endl;
} }
string CommandLineInterface::libraryPlaceholderHint(string const& _libraryName) std::string CommandLineInterface::libraryPlaceholderHint(std::string const& _libraryName)
{ {
return "// " + evmasm::LinkerObject::libraryPlaceholder(_libraryName) + " -> " + _libraryName; return "// " + evmasm::LinkerObject::libraryPlaceholder(_libraryName) + " -> " + _libraryName;
} }
string CommandLineInterface::objectWithLinkRefsHex(evmasm::LinkerObject const& _obj) std::string CommandLineInterface::objectWithLinkRefsHex(evmasm::LinkerObject const& _obj)
{ {
string out = _obj.toHex(); std::string out = _obj.toHex();
if (!_obj.linkReferences.empty()) if (!_obj.linkReferences.empty())
{ {
out += "\n"; out += "\n";
@ -1072,7 +1071,7 @@ void CommandLineInterface::assembleYul(yul::YulStack::Language _language, yul::Y
solAssert(m_options.input.mode == InputMode::Assembler); solAssert(m_options.input.mode == InputMode::Assembler);
bool successful = true; bool successful = true;
map<string, yul::YulStack> yulStacks; std::map<std::string, yul::YulStack> yulStacks;
for (auto const& src: m_fileReader.sourceUnits()) for (auto const& src: m_fileReader.sourceUnits())
{ {
auto& stack = yulStacks[src.first] = yul::YulStack( auto& stack = yulStacks[src.first] = yul::YulStack(
@ -1114,8 +1113,8 @@ void CommandLineInterface::assembleYul(yul::YulStack::Language _language, yul::Y
for (auto const& src: m_fileReader.sourceUnits()) for (auto const& src: m_fileReader.sourceUnits())
{ {
solAssert(_targetMachine == yul::YulStack::Machine::EVM); solAssert(_targetMachine == yul::YulStack::Machine::EVM);
string machine = "EVM"; std::string machine = "EVM";
sout() << endl << "======= " << src.first << " (" << machine << ") =======" << endl; sout() << std::endl << "======= " << src.first << " (" << machine << ") =======" << std::endl;
yul::YulStack& stack = yulStacks[src.first]; yul::YulStack& stack = yulStacks[src.first];
@ -1123,8 +1122,8 @@ void CommandLineInterface::assembleYul(yul::YulStack::Language _language, yul::Y
{ {
// NOTE: This actually outputs unoptimized code when the optimizer is disabled but // NOTE: This actually outputs unoptimized code when the optimizer is disabled but
// 'ir' output in StandardCompiler works the same way. // 'ir' output in StandardCompiler works the same way.
sout() << endl << "Pretty printed source:" << endl; sout() << std::endl << "Pretty printed source:" << std::endl;
sout() << stack.print() << endl; sout() << stack.print() << std::endl;
} }
yul::MachineAssemblyObject object; yul::MachineAssemblyObject object;
@ -1133,25 +1132,25 @@ void CommandLineInterface::assembleYul(yul::YulStack::Language _language, yul::Y
if (m_options.compiler.outputs.binary) if (m_options.compiler.outputs.binary)
{ {
sout() << endl << "Binary representation:" << endl; sout() << std::endl << "Binary representation:" << std::endl;
if (object.bytecode) if (object.bytecode)
sout() << object.bytecode->toHex() << endl; sout() << object.bytecode->toHex() << std::endl;
else else
serr() << "No binary representation found." << endl; serr() << "No binary representation found." << std::endl;
} }
if (m_options.compiler.outputs.astCompactJson) if (m_options.compiler.outputs.astCompactJson)
{ {
sout() << "AST:" << endl << endl; sout() << "AST:" << std::endl << std::endl;
sout() << util::jsonPrint(stack.astJson(), m_options.formatting.json) << endl; sout() << util::jsonPrint(stack.astJson(), m_options.formatting.json) << std::endl;
} }
solAssert(_targetMachine == yul::YulStack::Machine::EVM, ""); solAssert(_targetMachine == yul::YulStack::Machine::EVM, "");
if (m_options.compiler.outputs.asm_) if (m_options.compiler.outputs.asm_)
{ {
sout() << endl << "Text representation:" << endl; sout() << std::endl << "Text representation:" << std::endl;
if (!object.assembly.empty()) if (!object.assembly.empty())
sout() << object.assembly << endl; sout() << object.assembly << std::endl;
else else
serr() << "No text representation found." << endl; serr() << "No text representation found." << std::endl;
} }
} }
} }
@ -1173,15 +1172,15 @@ void CommandLineInterface::outputCompilationResults()
// we can safely assume that full compilation was performed and successful. // we can safely assume that full compilation was performed and successful.
solAssert(m_options.output.stopAfter >= CompilerStack::State::CompilationSuccessful); solAssert(m_options.output.stopAfter >= CompilerStack::State::CompilationSuccessful);
for (string const& contract: m_compiler->contractNames()) for (std::string const& contract: m_compiler->contractNames())
{ {
if (needsHumanTargetedStdout(m_options)) if (needsHumanTargetedStdout(m_options))
sout() << endl << "======= " << contract << " =======" << endl; sout() << std::endl << "======= " << contract << " =======" << std::endl;
// do we need EVM assembly? // do we need EVM assembly?
if (m_options.compiler.outputs.asm_ || m_options.compiler.outputs.asmJson) if (m_options.compiler.outputs.asm_ || m_options.compiler.outputs.asmJson)
{ {
string ret; std::string ret;
if (m_options.compiler.outputs.asmJson) if (m_options.compiler.outputs.asmJson)
ret = util::jsonPrint(removeNullMembers(m_compiler->assemblyJSON(contract)), m_options.formatting.json); ret = util::jsonPrint(removeNullMembers(m_compiler->assemblyJSON(contract)), m_options.formatting.json);
else else
@ -1190,7 +1189,7 @@ void CommandLineInterface::outputCompilationResults()
if (!m_options.output.dir.empty()) if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(contract) + (m_options.compiler.outputs.asmJson ? "_evm.json" : ".evm"), ret); createFile(m_compiler->filesystemFriendlyName(contract) + (m_options.compiler.outputs.asmJson ? "_evm.json" : ".evm"), ret);
else else
sout() << "EVM assembly:" << endl << ret << endl; sout() << "EVM assembly:" << std::endl << ret << std::endl;
} }
if (m_options.compiler.estimateGas) if (m_options.compiler.estimateGas)
@ -1213,11 +1212,11 @@ void CommandLineInterface::outputCompilationResults()
if (!m_hasOutput) if (!m_hasOutput)
{ {
if (!m_options.output.dir.empty()) if (!m_options.output.dir.empty())
sout() << "Compiler run successful. Artifact(s) can be found in directory " << m_options.output.dir << "." << endl; sout() << "Compiler run successful. Artifact(s) can be found in directory " << m_options.output.dir << "." << std::endl;
else if (m_compiler->contractNames().empty()) else if (m_compiler->contractNames().empty())
sout() << "Compiler run successful. No contracts to compile." << endl; sout() << "Compiler run successful. No contracts to compile." << std::endl;
else else
sout() << "Compiler run successful. No output generated." << endl; sout() << "Compiler run successful. No output generated." << std::endl;
} }
} }

View File

@ -30,7 +30,6 @@
#include <range/v3/view/filter.hpp> #include <range/v3/view/filter.hpp>
#include <range/v3/range/conversion.hpp> #include <range/v3/range/conversion.hpp>
using namespace std;
using namespace solidity::langutil; using namespace solidity::langutil;
namespace po = boost::program_options; namespace po = boost::program_options;
@ -38,59 +37,59 @@ namespace po = boost::program_options;
namespace solidity::frontend namespace solidity::frontend
{ {
static string const g_strAllowPaths = "allow-paths"; static std::string const g_strAllowPaths = "allow-paths";
static string const g_strBasePath = "base-path"; static std::string const g_strBasePath = "base-path";
static string const g_strIncludePath = "include-path"; static std::string const g_strIncludePath = "include-path";
static string const g_strAssemble = "assemble"; static std::string const g_strAssemble = "assemble";
static string const g_strCombinedJson = "combined-json"; static std::string const g_strCombinedJson = "combined-json";
static string const g_strEVM = "evm"; static std::string const g_strEVM = "evm";
static string const g_strEVMVersion = "evm-version"; static std::string const g_strEVMVersion = "evm-version";
static string const g_strEOFVersion = "experimental-eof-version"; static std::string const g_strEOFVersion = "experimental-eof-version";
static string const g_strViaIR = "via-ir"; static std::string const g_strViaIR = "via-ir";
static string const g_strExperimentalViaIR = "experimental-via-ir"; static std::string const g_strExperimentalViaIR = "experimental-via-ir";
static string const g_strGas = "gas"; static std::string const g_strGas = "gas";
static string const g_strHelp = "help"; static std::string const g_strHelp = "help";
static string const g_strImportAst = "import-ast"; static std::string const g_strImportAst = "import-ast";
static string const g_strInputFile = "input-file"; static std::string const g_strInputFile = "input-file";
static string const g_strYul = "yul"; static std::string const g_strYul = "yul";
static string const g_strYulDialect = "yul-dialect"; static std::string const g_strYulDialect = "yul-dialect";
static string const g_strDebugInfo = "debug-info"; static std::string const g_strDebugInfo = "debug-info";
static string const g_strIPFS = "ipfs"; static std::string const g_strIPFS = "ipfs";
static string const g_strLicense = "license"; static std::string const g_strLicense = "license";
static string const g_strLibraries = "libraries"; static std::string const g_strLibraries = "libraries";
static string const g_strLink = "link"; static std::string const g_strLink = "link";
static string const g_strLSP = "lsp"; static std::string const g_strLSP = "lsp";
static string const g_strMachine = "machine"; static std::string const g_strMachine = "machine";
static string const g_strNoCBORMetadata = "no-cbor-metadata"; static std::string const g_strNoCBORMetadata = "no-cbor-metadata";
static string const g_strMetadataHash = "metadata-hash"; static std::string const g_strMetadataHash = "metadata-hash";
static string const g_strMetadataLiteral = "metadata-literal"; static std::string const g_strMetadataLiteral = "metadata-literal";
static string const g_strModelCheckerContracts = "model-checker-contracts"; static std::string const g_strModelCheckerContracts = "model-checker-contracts";
static string const g_strModelCheckerDivModNoSlacks = "model-checker-div-mod-no-slacks"; static std::string const g_strModelCheckerDivModNoSlacks = "model-checker-div-mod-no-slacks";
static string const g_strModelCheckerEngine = "model-checker-engine"; static std::string const g_strModelCheckerEngine = "model-checker-engine";
static string const g_strModelCheckerExtCalls = "model-checker-ext-calls"; static std::string const g_strModelCheckerExtCalls = "model-checker-ext-calls";
static string const g_strModelCheckerInvariants = "model-checker-invariants"; static std::string const g_strModelCheckerInvariants = "model-checker-invariants";
static string const g_strModelCheckerPrintQuery = "model-checker-print-query"; static std::string const g_strModelCheckerPrintQuery = "model-checker-print-query";
static string const g_strModelCheckerShowProvedSafe = "model-checker-show-proved-safe"; static std::string const g_strModelCheckerShowProvedSafe = "model-checker-show-proved-safe";
static string const g_strModelCheckerShowUnproved = "model-checker-show-unproved"; static std::string const g_strModelCheckerShowUnproved = "model-checker-show-unproved";
static string const g_strModelCheckerShowUnsupported = "model-checker-show-unsupported"; static std::string const g_strModelCheckerShowUnsupported = "model-checker-show-unsupported";
static string const g_strModelCheckerSolvers = "model-checker-solvers"; static std::string const g_strModelCheckerSolvers = "model-checker-solvers";
static string const g_strModelCheckerTargets = "model-checker-targets"; static std::string const g_strModelCheckerTargets = "model-checker-targets";
static string const g_strModelCheckerTimeout = "model-checker-timeout"; static std::string const g_strModelCheckerTimeout = "model-checker-timeout";
static string const g_strModelCheckerBMCLoopIterations = "model-checker-bmc-loop-iterations"; static std::string const g_strModelCheckerBMCLoopIterations = "model-checker-bmc-loop-iterations";
static string const g_strNone = "none"; static std::string const g_strNone = "none";
static string const g_strNoOptimizeYul = "no-optimize-yul"; static std::string const g_strNoOptimizeYul = "no-optimize-yul";
static string const g_strOptimize = "optimize"; static std::string const g_strOptimize = "optimize";
static string const g_strOptimizeRuns = "optimize-runs"; static std::string const g_strOptimizeRuns = "optimize-runs";
static string const g_strOptimizeYul = "optimize-yul"; static std::string const g_strOptimizeYul = "optimize-yul";
static string const g_strYulOptimizations = "yul-optimizations"; static std::string const g_strYulOptimizations = "yul-optimizations";
static string const g_strOutputDir = "output-dir"; static std::string const g_strOutputDir = "output-dir";
static string const g_strOverwrite = "overwrite"; static std::string const g_strOverwrite = "overwrite";
static string const g_strRevertStrings = "revert-strings"; static std::string const g_strRevertStrings = "revert-strings";
static string const g_strStopAfter = "stop-after"; static std::string const g_strStopAfter = "stop-after";
static string const g_strParsing = "parsing"; static std::string const g_strParsing = "parsing";
/// Possible arguments to for --revert-strings /// Possible arguments to for --revert-strings
static set<string> const g_revertStringsArgs static std::set<std::string> const g_revertStringsArgs
{ {
revertStringsToString(RevertStrings::Default), revertStringsToString(RevertStrings::Default),
revertStringsToString(RevertStrings::Strip), revertStringsToString(RevertStrings::Strip),
@ -98,40 +97,40 @@ static set<string> const g_revertStringsArgs
revertStringsToString(RevertStrings::VerboseDebug) revertStringsToString(RevertStrings::VerboseDebug)
}; };
static string const g_strSources = "sources"; static std::string const g_strSources = "sources";
static string const g_strSourceList = "sourceList"; static std::string const g_strSourceList = "sourceList";
static string const g_strStandardJSON = "standard-json"; static std::string const g_strStandardJSON = "standard-json";
static string const g_strStrictAssembly = "strict-assembly"; static std::string const g_strStrictAssembly = "strict-assembly";
static string const g_strSwarm = "swarm"; static std::string const g_strSwarm = "swarm";
static string const g_strPrettyJson = "pretty-json"; static std::string const g_strPrettyJson = "pretty-json";
static string const g_strJsonIndent = "json-indent"; static std::string const g_strJsonIndent = "json-indent";
static string const g_strVersion = "version"; static std::string const g_strVersion = "version";
static string const g_strIgnoreMissingFiles = "ignore-missing"; static std::string const g_strIgnoreMissingFiles = "ignore-missing";
static string const g_strColor = "color"; static std::string const g_strColor = "color";
static string const g_strNoColor = "no-color"; static std::string const g_strNoColor = "no-color";
static string const g_strErrorIds = "error-codes"; static std::string const g_strErrorIds = "error-codes";
/// Possible arguments to for --machine /// Possible arguments to for --machine
static set<string> const g_machineArgs static std::set<std::string> const g_machineArgs
{ {
g_strEVM g_strEVM
}; };
/// Possible arguments to for --yul-dialect /// Possible arguments to for --yul-dialect
static set<string> const g_yulDialectArgs static std::set<std::string> const g_yulDialectArgs
{ {
g_strEVM g_strEVM
}; };
/// Possible arguments to for --metadata-hash /// Possible arguments to for --metadata-hash
static set<string> const g_metadataHashArgs static std::set<std::string> const g_metadataHashArgs
{ {
g_strIPFS, g_strIPFS,
g_strSwarm, g_strSwarm,
g_strNone g_strNone
}; };
static map<InputMode, string> const g_inputModeName = { static std::map<InputMode, std::string> const g_inputModeName = {
{InputMode::Help, "help"}, {InputMode::Help, "help"},
{InputMode::License, "license"}, {InputMode::License, "license"},
{InputMode::Version, "version"}, {InputMode::Version, "version"},
@ -143,7 +142,7 @@ static map<InputMode, string> const g_inputModeName = {
{InputMode::LanguageServer, "language server (LSP)"}, {InputMode::LanguageServer, "language server (LSP)"},
}; };
void CommandLineParser::checkMutuallyExclusive(vector<string> const& _optionNames) void CommandLineParser::checkMutuallyExclusive(std::vector<std::string> const& _optionNames)
{ {
if (countEnabledOptions(_optionNames) > 1) if (countEnabledOptions(_optionNames) > 1)
{ {
@ -163,9 +162,9 @@ bool CompilerOutputs::operator==(CompilerOutputs const& _other) const noexcept
return true; return true;
} }
ostream& operator<<(ostream& _out, CompilerOutputs const& _selection) std::ostream& operator<<(std::ostream& _out, CompilerOutputs const& _selection)
{ {
vector<string> serializedSelection; std::vector<std::string> serializedSelection;
for (auto&& [componentName, component]: CompilerOutputs::componentMap()) for (auto&& [componentName, component]: CompilerOutputs::componentMap())
if (_selection.*component) if (_selection.*component)
serializedSelection.push_back(CompilerOutputs::componentName(component)); serializedSelection.push_back(CompilerOutputs::componentName(component));
@ -173,7 +172,7 @@ ostream& operator<<(ostream& _out, CompilerOutputs const& _selection)
return _out << util::joinHumanReadable(serializedSelection, ","); return _out << util::joinHumanReadable(serializedSelection, ",");
} }
string const& CompilerOutputs::componentName(bool CompilerOutputs::* _component) std::string const& CompilerOutputs::componentName(bool CompilerOutputs::* _component)
{ {
solAssert(_component, ""); solAssert(_component, "");
@ -194,9 +193,9 @@ bool CombinedJsonRequests::operator==(CombinedJsonRequests const& _other) const
} }
ostream& operator<<(ostream& _out, CombinedJsonRequests const& _requests) std::ostream& operator<<(std::ostream& _out, CombinedJsonRequests const& _requests)
{ {
vector<string> serializedRequests; std::vector<std::string> serializedRequests;
for (auto&& [componentName, component]: CombinedJsonRequests::componentMap()) for (auto&& [componentName, component]: CombinedJsonRequests::componentMap())
if (_requests.*component) if (_requests.*component)
serializedRequests.push_back(CombinedJsonRequests::componentName(component)); serializedRequests.push_back(CombinedJsonRequests::componentName(component));
@ -204,7 +203,7 @@ ostream& operator<<(ostream& _out, CombinedJsonRequests const& _requests)
return _out << util::joinHumanReadable(serializedRequests, ","); return _out << util::joinHumanReadable(serializedRequests, ",");
} }
string const& CombinedJsonRequests::componentName(bool CombinedJsonRequests::* _component) std::string const& CombinedJsonRequests::componentName(bool CombinedJsonRequests::* _component)
{ {
solAssert(_component, ""); solAssert(_component, "");
@ -274,11 +273,11 @@ OptimiserSettings CommandLineOptions::optimiserSettings() const
if (optimizer.yulSteps.has_value()) if (optimizer.yulSteps.has_value())
{ {
string const fullSequence = optimizer.yulSteps.value(); std::string const fullSequence = optimizer.yulSteps.value();
auto const delimiterPos = fullSequence.find(":"); auto const delimiterPos = fullSequence.find(":");
settings.yulOptimiserSteps = fullSequence.substr(0, delimiterPos); settings.yulOptimiserSteps = fullSequence.substr(0, delimiterPos);
if (delimiterPos != string::npos) if (delimiterPos != std::string::npos)
settings.yulOptimiserCleanupSteps = fullSequence.substr(delimiterPos + 1); settings.yulOptimiserCleanupSteps = fullSequence.substr(delimiterPos + 1);
else else
solAssert(settings.yulOptimiserCleanupSteps == OptimiserSettings::DefaultYulOptimiserCleanupSteps); solAssert(settings.yulOptimiserCleanupSteps == OptimiserSettings::DefaultYulOptimiserCleanupSteps);
@ -298,11 +297,11 @@ void CommandLineParser::parseInputPathsAndRemappings()
m_options.input.ignoreMissingFiles = (m_args.count(g_strIgnoreMissingFiles) > 0); m_options.input.ignoreMissingFiles = (m_args.count(g_strIgnoreMissingFiles) > 0);
if (m_args.count(g_strInputFile)) if (m_args.count(g_strInputFile))
for (string const& positionalArg: m_args[g_strInputFile].as<vector<string>>()) for (std::string const& positionalArg: m_args[g_strInputFile].as<std::vector<std::string>>())
{ {
if (ImportRemapper::isRemapping(positionalArg)) if (ImportRemapper::isRemapping(positionalArg))
{ {
optional<ImportRemapper::Remapping> remapping = ImportRemapper::parseRemapping(positionalArg); std::optional<ImportRemapper::Remapping> remapping = ImportRemapper::parseRemapping(positionalArg);
if (!remapping.has_value()) if (!remapping.has_value())
solThrow(CommandLineValidationError, "Invalid remapping: \"" + positionalArg + "\"."); solThrow(CommandLineValidationError, "Invalid remapping: \"" + positionalArg + "\".");
@ -353,10 +352,10 @@ void CommandLineParser::parseInputPathsAndRemappings()
); );
} }
void CommandLineParser::parseLibraryOption(string const& _input) void CommandLineParser::parseLibraryOption(std::string const& _input)
{ {
namespace fs = boost::filesystem; namespace fs = boost::filesystem;
string data = _input; std::string data = _input;
try try
{ {
if (fs::is_regular_file(_input)) if (fs::is_regular_file(_input))
@ -375,19 +374,19 @@ void CommandLineParser::parseLibraryOption(string const& _input)
// Should not happen if `fs::is_regular_file` is correct. // Should not happen if `fs::is_regular_file` is correct.
} }
vector<string> libraries; std::vector<std::string> libraries;
boost::split(libraries, data, boost::is_space() || boost::is_any_of(","), boost::token_compress_on); boost::split(libraries, data, boost::is_space() || boost::is_any_of(","), boost::token_compress_on);
for (string const& lib: libraries) for (std::string const& lib: libraries)
if (!lib.empty()) if (!lib.empty())
{ {
//search for equal sign or last colon in string as our binaries output placeholders in the form of file=Name or file:Name //search for equal sign or last colon in string as our binaries output placeholders in the form of file=Name or file:Name
//so we need to search for `=` or `:` in the string //so we need to search for `=` or `:` in the string
auto separator = lib.rfind('='); auto separator = lib.rfind('=');
bool isSeparatorEqualSign = true; bool isSeparatorEqualSign = true;
if (separator == string::npos) if (separator == std::string::npos)
{ {
separator = lib.rfind(':'); separator = lib.rfind(':');
if (separator == string::npos) if (separator == std::string::npos)
solThrow( solThrow(
CommandLineValidationError, CommandLineValidationError,
"Equal sign separator missing in library address specifier \"" + lib + "\"" "Equal sign separator missing in library address specifier \"" + lib + "\""
@ -402,7 +401,7 @@ void CommandLineParser::parseLibraryOption(string const& _input)
"Only one equal sign \"=\" is allowed in the address string \"" + lib + "\"." "Only one equal sign \"=\" is allowed in the address string \"" + lib + "\"."
); );
string libName(lib.begin(), lib.begin() + static_cast<ptrdiff_t>(separator)); std::string libName(lib.begin(), lib.begin() + static_cast<ptrdiff_t>(separator));
boost::trim(libName); boost::trim(libName);
if (m_options.linker.libraries.count(libName)) if (m_options.linker.libraries.count(libName))
solThrow( solThrow(
@ -410,7 +409,7 @@ void CommandLineParser::parseLibraryOption(string const& _input)
"Address specified more than once for library \"" + libName + "\"." "Address specified more than once for library \"" + libName + "\"."
); );
string addrString(lib.begin() + static_cast<ptrdiff_t>(separator) + 1, lib.end()); std::string addrString(lib.begin() + static_cast<ptrdiff_t>(separator) + 1, lib.end());
boost::trim(addrString); boost::trim(addrString);
if (addrString.empty()) if (addrString.empty())
solThrow( solThrow(
@ -433,7 +432,7 @@ void CommandLineParser::parseLibraryOption(string const& _input)
solThrow( solThrow(
CommandLineValidationError, CommandLineValidationError,
"Invalid length for address for library \"" + libName + "\": " + "Invalid length for address for library \"" + libName + "\": " +
to_string(addrString.length()) + " instead of 40 characters." std::to_string(addrString.length()) + " instead of 40 characters."
); );
if (!util::passesAddressChecksum(addrString, false)) if (!util::passesAddressChecksum(addrString, false))
solThrow( solThrow(
@ -454,14 +453,14 @@ void CommandLineParser::parseLibraryOption(string const& _input)
void CommandLineParser::parseOutputSelection() void CommandLineParser::parseOutputSelection()
{ {
static auto outputSupported = [](InputMode _mode, string_view _outputName) static auto outputSupported = [](InputMode _mode, std::string_view _outputName)
{ {
static set<string> const compilerModeOutputs = ( static std::set<std::string> const compilerModeOutputs = (
CompilerOutputs::componentMap() | CompilerOutputs::componentMap() |
ranges::views::keys | ranges::views::keys |
ranges::to<set>() ranges::to<std::set>()
); );
static set<string> const assemblerModeOutputs = { static std::set<std::string> const assemblerModeOutputs = {
CompilerOutputs::componentName(&CompilerOutputs::asm_), CompilerOutputs::componentName(&CompilerOutputs::asm_),
CompilerOutputs::componentName(&CompilerOutputs::binary), CompilerOutputs::componentName(&CompilerOutputs::binary),
CompilerOutputs::componentName(&CompilerOutputs::irOptimized), CompilerOutputs::componentName(&CompilerOutputs::irOptimized),
@ -500,7 +499,7 @@ void CommandLineParser::parseOutputSelection()
m_options.compiler.outputs.irOptimized = true; m_options.compiler.outputs.irOptimized = true;
} }
vector<string> unsupportedOutputs; std::vector<std::string> unsupportedOutputs;
for (auto&& [optionName, outputComponent]: CompilerOutputs::componentMap()) for (auto&& [optionName, outputComponent]: CompilerOutputs::componentMap())
if (m_options.compiler.outputs.*outputComponent && !outputSupported(m_options.input.mode, optionName)) if (m_options.compiler.outputs.*outputComponent && !outputSupported(m_options.input.mode, optionName))
unsupportedOutputs.push_back(optionName); unsupportedOutputs.push_back(optionName);
@ -547,12 +546,12 @@ General Information)").c_str(),
inputOptions.add_options() inputOptions.add_options()
( (
g_strBasePath.c_str(), g_strBasePath.c_str(),
po::value<string>()->value_name("path"), po::value<std::string>()->value_name("path"),
"Use the given path as the root of the source tree instead of the root of the filesystem." "Use the given path as the root of the source tree instead of the root of the filesystem."
) )
( (
g_strIncludePath.c_str(), g_strIncludePath.c_str(),
po::value<vector<string>>()->value_name("path"), po::value<std::vector<std::string>>()->value_name("path"),
"Make an additional source directory available to the default import callback. " "Make an additional source directory available to the default import callback. "
"Use this option if you want to import contracts whose location is not fixed in relation " "Use this option if you want to import contracts whose location is not fixed in relation "
"to your main source tree, e.g. third-party libraries installed using a package manager. " "to your main source tree, e.g. third-party libraries installed using a package manager. "
@ -561,7 +560,7 @@ General Information)").c_str(),
) )
( (
g_strAllowPaths.c_str(), g_strAllowPaths.c_str(),
po::value<string>()->value_name("path(s)"), po::value<std::string>()->value_name("path(s)"),
"Allow a given path for imports. A list of paths can be supplied by separating them with a comma." "Allow a given path for imports. A list of paths can be supplied by separating them with a comma."
) )
( (
@ -575,7 +574,7 @@ General Information)").c_str(),
outputOptions.add_options() outputOptions.add_options()
( (
(g_strOutputDir + ",o").c_str(), (g_strOutputDir + ",o").c_str(),
po::value<string>()->value_name("path"), po::value<std::string>()->value_name("path"),
"If given, creates one file per output component and contract/file at the specified directory." "If given, creates one file per output component and contract/file at the specified directory."
) )
( (
@ -584,7 +583,7 @@ General Information)").c_str(),
) )
( (
g_strEVMVersion.c_str(), g_strEVMVersion.c_str(),
po::value<string>()->value_name("version")->default_value(EVMVersion{}.name()), po::value<std::string>()->value_name("version")->default_value(EVMVersion{}.name()),
"Select desired EVM version. Either homestead, tangerineWhistle, spuriousDragon, " "Select desired EVM version. Either homestead, tangerineWhistle, spuriousDragon, "
"byzantium, constantinople, petersburg, istanbul, berlin, london, paris or shanghai." "byzantium, constantinople, petersburg, istanbul, berlin, london, paris or shanghai."
) )
@ -610,19 +609,19 @@ General Information)").c_str(),
) )
( (
g_strRevertStrings.c_str(), g_strRevertStrings.c_str(),
po::value<string>()->value_name(util::joinHumanReadable(g_revertStringsArgs, ",")), po::value<std::string>()->value_name(util::joinHumanReadable(g_revertStringsArgs, ",")),
"Strip revert (and require) reason strings or add additional debugging information." "Strip revert (and require) reason strings or add additional debugging information."
) )
( (
g_strDebugInfo.c_str(), g_strDebugInfo.c_str(),
po::value<string>()->default_value(util::toString(DebugInfoSelection::Default())), po::value<std::string>()->default_value(util::toString(DebugInfoSelection::Default())),
("Debug info components to be included in the produced EVM assembly and Yul code. " ("Debug info components to be included in the produced EVM assembly and Yul code. "
"Value can be all, none or a comma-separated list containing one or more of the " "Value can be all, none or a comma-separated list containing one or more of the "
"following components: " + util::joinHumanReadable(DebugInfoSelection::componentMap() | ranges::views::keys) + ".").c_str() "following components: " + util::joinHumanReadable(DebugInfoSelection::componentMap() | ranges::views::keys) + ".").c_str()
) )
( (
g_strStopAfter.c_str(), g_strStopAfter.c_str(),
po::value<string>()->value_name("stage"), po::value<std::string>()->value_name("stage"),
"Stop execution after the given compiler stage. Valid options: \"parsing\"." "Stop execution after the given compiler stage. Valid options: \"parsing\"."
) )
; ;
@ -670,12 +669,12 @@ General Information)").c_str(),
assemblyModeOptions.add_options() assemblyModeOptions.add_options()
( (
g_strMachine.c_str(), g_strMachine.c_str(),
po::value<string>()->value_name(util::joinHumanReadable(g_machineArgs, ",")), po::value<std::string>()->value_name(util::joinHumanReadable(g_machineArgs, ",")),
"Target machine in assembly or Yul mode." "Target machine in assembly or Yul mode."
) )
( (
g_strYulDialect.c_str(), g_strYulDialect.c_str(),
po::value<string>()->value_name(util::joinHumanReadable(g_yulDialectArgs, ",")), po::value<std::string>()->value_name(util::joinHumanReadable(g_yulDialectArgs, ",")),
"Input dialect to use in assembly or yul mode." "Input dialect to use in assembly or yul mode."
) )
; ;
@ -685,7 +684,7 @@ General Information)").c_str(),
linkerModeOptions.add_options() linkerModeOptions.add_options()
( (
g_strLibraries.c_str(), g_strLibraries.c_str(),
po::value<vector<string>>()->value_name("libs"), po::value<std::vector<std::string>>()->value_name("libs"),
"Direct string or file containing library addresses. Syntax: " "Direct string or file containing library addresses. Syntax: "
"<libraryName>=<address> [, or whitespace] ...\n" "<libraryName>=<address> [, or whitespace] ...\n"
"Address is interpreted as a hex string prefixed by 0x." "Address is interpreted as a hex string prefixed by 0x."
@ -748,7 +747,7 @@ General Information)").c_str(),
) )
( (
g_strCombinedJson.c_str(), g_strCombinedJson.c_str(),
po::value<string>()->value_name(util::joinHumanReadable(CombinedJsonRequests::componentMap() | ranges::views::keys, ",")), po::value<std::string>()->value_name(util::joinHumanReadable(CombinedJsonRequests::componentMap() | ranges::views::keys, ",")),
"Output a single json document containing the specified information." "Output a single json document containing the specified information."
) )
; ;
@ -762,7 +761,7 @@ General Information)").c_str(),
) )
( (
g_strMetadataHash.c_str(), g_strMetadataHash.c_str(),
po::value<string>()->value_name(util::joinHumanReadable(g_metadataHashArgs, ",")), po::value<std::string>()->value_name(util::joinHumanReadable(g_metadataHashArgs, ",")),
"Choose hash method for the bytecode metadata or disable it." "Choose hash method for the bytecode metadata or disable it."
) )
( (
@ -798,7 +797,7 @@ General Information)").c_str(),
) )
( (
g_strYulOptimizations.c_str(), g_strYulOptimizations.c_str(),
po::value<string>()->value_name("steps"), po::value<std::string>()->value_name("steps"),
"Forces Yul optimizer to use the specified sequence of optimization steps instead of the built-in one." "Forces Yul optimizer to use the specified sequence of optimization steps instead of the built-in one."
) )
; ;
@ -808,7 +807,7 @@ General Information)").c_str(),
smtCheckerOptions.add_options() smtCheckerOptions.add_options()
( (
g_strModelCheckerContracts.c_str(), g_strModelCheckerContracts.c_str(),
po::value<string>()->value_name("default,<source>:<contract>")->default_value("default"), po::value<std::string>()->value_name("default,<source>:<contract>")->default_value("default"),
"Select which contracts should be analyzed using the form <source>:<contract>." "Select which contracts should be analyzed using the form <source>:<contract>."
"Multiple pairs <source>:<contract> can be selected at the same time, separated by a comma " "Multiple pairs <source>:<contract> can be selected at the same time, separated by a comma "
"and no spaces." "and no spaces."
@ -820,18 +819,18 @@ General Information)").c_str(),
) )
( (
g_strModelCheckerEngine.c_str(), g_strModelCheckerEngine.c_str(),
po::value<string>()->value_name("all,bmc,chc,none")->default_value("none"), po::value<std::string>()->value_name("all,bmc,chc,none")->default_value("none"),
"Select model checker engine." "Select model checker engine."
) )
( (
g_strModelCheckerExtCalls.c_str(), g_strModelCheckerExtCalls.c_str(),
po::value<string>()->value_name("untrusted,trusted")->default_value("untrusted"), po::value<std::string>()->value_name("untrusted,trusted")->default_value("untrusted"),
"Select whether to assume (trusted) that external calls always invoke" "Select whether to assume (trusted) that external calls always invoke"
" the code given by the type of the contract, if that code is available." " the code given by the type of the contract, if that code is available."
) )
( (
g_strModelCheckerInvariants.c_str(), g_strModelCheckerInvariants.c_str(),
po::value<string>()->value_name("default,all,contract,reentrancy")->default_value("default"), po::value<std::string>()->value_name("default,all,contract,reentrancy")->default_value("default"),
"Select whether to report inferred contract inductive invariants." "Select whether to report inferred contract inductive invariants."
" Multiple types of invariants can be selected at the same time, separated by a comma and no spaces." " Multiple types of invariants can be selected at the same time, separated by a comma and no spaces."
" By default no invariants are reported." " By default no invariants are reported."
@ -854,12 +853,12 @@ General Information)").c_str(),
) )
( (
g_strModelCheckerSolvers.c_str(), g_strModelCheckerSolvers.c_str(),
po::value<string>()->value_name("cvc4,eld,z3,smtlib2")->default_value("z3"), po::value<std::string>()->value_name("cvc4,eld,z3,smtlib2")->default_value("z3"),
"Select model checker solvers." "Select model checker solvers."
) )
( (
g_strModelCheckerTargets.c_str(), g_strModelCheckerTargets.c_str(),
po::value<string>()->value_name("default,all,constantCondition,underflow,overflow,divByZero,balance,assert,popEmptyArray,outOfBounds")->default_value("default"), po::value<std::string>()->value_name("default,all,constantCondition,underflow,overflow,divByZero,balance,assert,popEmptyArray,outOfBounds")->default_value("default"),
"Select model checker verification targets." "Select model checker verification targets."
"Multiple targets can be selected at the same time, separated by a comma and no spaces." "Multiple targets can be selected at the same time, separated by a comma and no spaces."
" By default all targets except underflow and overflow are selected." " By default all targets except underflow and overflow are selected."
@ -880,7 +879,7 @@ General Information)").c_str(),
; ;
desc.add(smtCheckerOptions); desc.add(smtCheckerOptions);
desc.add_options()(g_strInputFile.c_str(), po::value<vector<string>>(), "input file"); desc.add_options()(g_strInputFile.c_str(), po::value<std::vector<std::string>>(), "input file");
return desc; return desc;
} }
@ -954,7 +953,7 @@ void CommandLineParser::processArgs()
) )
return; return;
map<string, set<InputMode>> validOptionInputModeCombinations = { std::map<std::string, std::set<InputMode>> validOptionInputModeCombinations = {
// TODO: This should eventually contain all options. // TODO: This should eventually contain all options.
{g_strExperimentalViaIR, {InputMode::Compiler, InputMode::CompilerWithASTImport}}, {g_strExperimentalViaIR, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strViaIR, {InputMode::Compiler, InputMode::CompilerWithASTImport}}, {g_strViaIR, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
@ -975,7 +974,7 @@ void CommandLineParser::processArgs()
{g_strModelCheckerContracts, {InputMode::Compiler, InputMode::CompilerWithASTImport}}, {g_strModelCheckerContracts, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerTargets, {InputMode::Compiler, InputMode::CompilerWithASTImport}} {g_strModelCheckerTargets, {InputMode::Compiler, InputMode::CompilerWithASTImport}}
}; };
vector<string> invalidOptionsForCurrentInputMode; std::vector<std::string> invalidOptionsForCurrentInputMode;
for (auto const& [optionName, inputModes]: validOptionInputModeCombinations) for (auto const& [optionName, inputModes]: validOptionInputModeCombinations)
{ {
if ( if (
@ -999,7 +998,7 @@ void CommandLineParser::processArgs()
checkMutuallyExclusive({g_strColor, g_strNoColor}); checkMutuallyExclusive({g_strColor, g_strNoColor});
checkMutuallyExclusive({g_strStopAfter, g_strGas}); checkMutuallyExclusive({g_strStopAfter, g_strGas});
for (string const& option: CompilerOutputs::componentMap() | ranges::views::keys) for (std::string const& option: CompilerOutputs::componentMap() | ranges::views::keys)
if (option != CompilerOutputs::componentName(&CompilerOutputs::astCompactJson)) if (option != CompilerOutputs::componentName(&CompilerOutputs::astCompactJson))
checkMutuallyExclusive({g_strStopAfter, option}); checkMutuallyExclusive({g_strStopAfter, option});
@ -1015,7 +1014,7 @@ void CommandLineParser::processArgs()
"Option --" + g_strOptimizeRuns + " is only valid in compiler and assembler modes." "Option --" + g_strOptimizeRuns + " is only valid in compiler and assembler modes."
); );
for (string const& option: {g_strOptimize, g_strNoOptimizeYul, g_strOptimizeYul, g_strYulOptimizations}) for (std::string const& option: {g_strOptimize, g_strNoOptimizeYul, g_strOptimizeYul, g_strYulOptimizations})
if (m_args.count(option) > 0) if (m_args.count(option) > 0)
solThrow( solThrow(
CommandLineValidationError, CommandLineValidationError,
@ -1038,8 +1037,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strRevertStrings)) if (m_args.count(g_strRevertStrings))
{ {
string revertStringsString = m_args[g_strRevertStrings].as<string>(); std::string revertStringsString = m_args[g_strRevertStrings].as<std::string>();
optional<RevertStrings> revertStrings = revertStringsFromString(revertStringsString); std::optional<RevertStrings> revertStrings = revertStringsFromString(revertStringsString);
if (!revertStrings) if (!revertStrings)
solThrow( solThrow(
CommandLineValidationError, CommandLineValidationError,
@ -1055,7 +1054,7 @@ void CommandLineParser::processArgs()
if (!m_args[g_strDebugInfo].defaulted()) if (!m_args[g_strDebugInfo].defaulted())
{ {
string optionValue = m_args[g_strDebugInfo].as<string>(); std::string optionValue = m_args[g_strDebugInfo].as<std::string>();
m_options.output.debugInfoSelection = DebugInfoSelection::fromString(optionValue); m_options.output.debugInfoSelection = DebugInfoSelection::fromString(optionValue);
if (!m_options.output.debugInfoSelection.has_value()) if (!m_options.output.debugInfoSelection.has_value())
solThrow(CommandLineValidationError, "Invalid value for --" + g_strDebugInfo + " option: " + optionValue); solThrow(CommandLineValidationError, "Invalid value for --" + g_strDebugInfo + " option: " + optionValue);
@ -1067,7 +1066,7 @@ void CommandLineParser::processArgs()
parseCombinedJsonOption(); parseCombinedJsonOption();
if (m_args.count(g_strOutputDir)) if (m_args.count(g_strOutputDir))
m_options.output.dir = m_args.at(g_strOutputDir).as<string>(); m_options.output.dir = m_args.at(g_strOutputDir).as<std::string>();
m_options.output.overwriteFiles = (m_args.count(g_strOverwrite) > 0); m_options.output.overwriteFiles = (m_args.count(g_strOverwrite) > 0);
@ -1086,14 +1085,14 @@ void CommandLineParser::processArgs()
m_options.compiler.estimateGas = (m_args.count(g_strGas) > 0); m_options.compiler.estimateGas = (m_args.count(g_strGas) > 0);
if (m_args.count(g_strBasePath)) if (m_args.count(g_strBasePath))
m_options.input.basePath = m_args[g_strBasePath].as<string>(); m_options.input.basePath = m_args[g_strBasePath].as<std::string>();
if (m_args.count(g_strIncludePath) > 0) if (m_args.count(g_strIncludePath) > 0)
{ {
if (m_options.input.basePath.empty()) if (m_options.input.basePath.empty())
solThrow(CommandLineValidationError, "--" + g_strIncludePath + " option requires a non-empty base path."); solThrow(CommandLineValidationError, "--" + g_strIncludePath + " option requires a non-empty base path.");
for (string const& includePath: m_args[g_strIncludePath].as<vector<string>>()) for (std::string const& includePath: m_args[g_strIncludePath].as<std::vector<std::string>>())
{ {
if (includePath.empty()) if (includePath.empty())
solThrow(CommandLineValidationError, "Empty values are not allowed in --" + g_strIncludePath + "."); solThrow(CommandLineValidationError, "Empty values are not allowed in --" + g_strIncludePath + ".");
@ -1104,15 +1103,15 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strAllowPaths)) if (m_args.count(g_strAllowPaths))
{ {
vector<string> paths; std::vector<std::string> paths;
for (string const& allowedPath: boost::split(paths, m_args[g_strAllowPaths].as<string>(), boost::is_any_of(","))) for (std::string const& allowedPath: boost::split(paths, m_args[g_strAllowPaths].as<std::string>(), boost::is_any_of(",")))
if (!allowedPath.empty()) if (!allowedPath.empty())
m_options.input.allowedDirectories.insert(allowedPath); m_options.input.allowedDirectories.insert(allowedPath);
} }
if (m_args.count(g_strStopAfter)) if (m_args.count(g_strStopAfter))
{ {
if (m_args[g_strStopAfter].as<string>() != "parsing") if (m_args[g_strStopAfter].as<std::string>() != "parsing")
solThrow(CommandLineValidationError, "Valid options for --" + g_strStopAfter + " are: \"parsing\".\n"); solThrow(CommandLineValidationError, "Valid options for --" + g_strStopAfter + " are: \"parsing\".\n");
else else
m_options.output.stopAfter = CompilerStack::State::Parsed; m_options.output.stopAfter = CompilerStack::State::Parsed;
@ -1124,7 +1123,7 @@ void CommandLineParser::processArgs()
return; return;
if (m_args.count(g_strLibraries)) if (m_args.count(g_strLibraries))
for (string const& library: m_args[g_strLibraries].as<vector<string>>()) for (std::string const& library: m_args[g_strLibraries].as<std::vector<std::string>>())
parseLibraryOption(library); parseLibraryOption(library);
if (m_options.input.mode == InputMode::Linker) if (m_options.input.mode == InputMode::Linker)
@ -1132,8 +1131,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strEVMVersion)) if (m_args.count(g_strEVMVersion))
{ {
string versionOptionStr = m_args[g_strEVMVersion].as<string>(); std::string versionOptionStr = m_args[g_strEVMVersion].as<std::string>();
optional<langutil::EVMVersion> versionOption = langutil::EVMVersion::fromString(versionOptionStr); std::optional<langutil::EVMVersion> versionOption = langutil::EVMVersion::fromString(versionOptionStr);
if (!versionOption) if (!versionOption)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strEVMVersion + ": " + versionOptionStr); solThrow(CommandLineValidationError, "Invalid option for --" + g_strEVMVersion + ": " + versionOptionStr);
m_options.output.evmVersion = *versionOption; m_options.output.evmVersion = *versionOption;
@ -1144,7 +1143,7 @@ void CommandLineParser::processArgs()
// Request as uint64_t, since uint8_t will be parsed as character by boost. // Request as uint64_t, since uint8_t will be parsed as character by boost.
uint64_t versionOption = m_args[g_strEOFVersion].as<uint64_t>(); uint64_t versionOption = m_args[g_strEOFVersion].as<uint64_t>();
if (versionOption != 1) if (versionOption != 1)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strEOFVersion + ": " + to_string(versionOption)); solThrow(CommandLineValidationError, "Invalid option for --" + g_strEOFVersion + ": " + std::to_string(versionOption));
m_options.output.eofVersion = 1; m_options.output.eofVersion = 1;
} }
@ -1170,7 +1169,7 @@ void CommandLineParser::processArgs()
try try
{ {
yul::OptimiserSuite::validateSequence(m_args[g_strYulOptimizations].as<string>()); yul::OptimiserSuite::validateSequence(m_args[g_strYulOptimizations].as<std::string>());
} }
catch (yul::OptimizerException const& _exception) catch (yul::OptimizerException const& _exception)
{ {
@ -1180,12 +1179,12 @@ void CommandLineParser::processArgs()
); );
} }
m_options.optimizer.yulSteps = m_args[g_strYulOptimizations].as<string>(); m_options.optimizer.yulSteps = m_args[g_strYulOptimizations].as<std::string>();
} }
if (m_options.input.mode == InputMode::Assembler) if (m_options.input.mode == InputMode::Assembler)
{ {
vector<string> const nonAssemblyModeOptions = { std::vector<std::string> const nonAssemblyModeOptions = {
// TODO: The list is not complete. Add more. // TODO: The list is not complete. Add more.
g_strOutputDir, g_strOutputDir,
g_strGas, g_strGas,
@ -1193,10 +1192,10 @@ void CommandLineParser::processArgs()
}; };
if (countEnabledOptions(nonAssemblyModeOptions) >= 1) if (countEnabledOptions(nonAssemblyModeOptions) >= 1)
{ {
auto optionEnabled = [&](string const& name){ return m_args.count(name) > 0; }; auto optionEnabled = [&](std::string const& name){ return m_args.count(name) > 0; };
auto enabledOptions = nonAssemblyModeOptions | ranges::views::filter(optionEnabled) | ranges::to_vector; auto enabledOptions = nonAssemblyModeOptions | ranges::views::filter(optionEnabled) | ranges::to_vector;
string message = "The following options are invalid in assembly mode: " + joinOptionNames(enabledOptions) + "."; std::string message = "The following options are invalid in assembly mode: " + joinOptionNames(enabledOptions) + ".";
solThrow(CommandLineValidationError, message); solThrow(CommandLineValidationError, message);
} }
@ -1207,7 +1206,7 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strMachine)) if (m_args.count(g_strMachine))
{ {
string machine = m_args[g_strMachine].as<string>(); std::string machine = m_args[g_strMachine].as<std::string>();
if (machine == g_strEVM) if (machine == g_strEVM)
m_options.assembly.targetMachine = Machine::EVM; m_options.assembly.targetMachine = Machine::EVM;
else else
@ -1215,7 +1214,7 @@ void CommandLineParser::processArgs()
} }
if (m_args.count(g_strYulDialect)) if (m_args.count(g_strYulDialect))
{ {
string dialect = m_args[g_strYulDialect].as<string>(); std::string dialect = m_args[g_strYulDialect].as<std::string>();
if (dialect == g_strEVM) if (dialect == g_strEVM)
m_options.assembly.inputLanguage = Input::StrictAssembly; m_options.assembly.inputLanguage = Input::StrictAssembly;
else else
@ -1239,7 +1238,7 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strMetadataHash)) if (m_args.count(g_strMetadataHash))
{ {
string hashStr = m_args[g_strMetadataHash].as<string>(); std::string hashStr = m_args[g_strMetadataHash].as<std::string>();
if (hashStr == g_strIPFS) if (hashStr == g_strIPFS)
m_options.metadata.hash = CompilerStack::MetadataHash::IPFS; m_options.metadata.hash = CompilerStack::MetadataHash::IPFS;
else if (hashStr == g_strSwarm) else if (hashStr == g_strSwarm)
@ -1267,8 +1266,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strModelCheckerContracts)) if (m_args.count(g_strModelCheckerContracts))
{ {
string contractsStr = m_args[g_strModelCheckerContracts].as<string>(); std::string contractsStr = m_args[g_strModelCheckerContracts].as<std::string>();
optional<ModelCheckerContracts> contracts = ModelCheckerContracts::fromString(contractsStr); std::optional<ModelCheckerContracts> contracts = ModelCheckerContracts::fromString(contractsStr);
if (!contracts) if (!contracts)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerContracts + ": " + contractsStr); solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerContracts + ": " + contractsStr);
m_options.modelChecker.settings.contracts = std::move(*contracts); m_options.modelChecker.settings.contracts = std::move(*contracts);
@ -1279,8 +1278,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strModelCheckerEngine)) if (m_args.count(g_strModelCheckerEngine))
{ {
string engineStr = m_args[g_strModelCheckerEngine].as<string>(); std::string engineStr = m_args[g_strModelCheckerEngine].as<std::string>();
optional<ModelCheckerEngine> engine = ModelCheckerEngine::fromString(engineStr); std::optional<ModelCheckerEngine> engine = ModelCheckerEngine::fromString(engineStr);
if (!engine) if (!engine)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerEngine + ": " + engineStr); solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerEngine + ": " + engineStr);
m_options.modelChecker.settings.engine = *engine; m_options.modelChecker.settings.engine = *engine;
@ -1288,8 +1287,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strModelCheckerExtCalls)) if (m_args.count(g_strModelCheckerExtCalls))
{ {
string mode = m_args[g_strModelCheckerExtCalls].as<string>(); std::string mode = m_args[g_strModelCheckerExtCalls].as<std::string>();
optional<ModelCheckerExtCalls> extCallsMode = ModelCheckerExtCalls::fromString(mode); std::optional<ModelCheckerExtCalls> extCallsMode = ModelCheckerExtCalls::fromString(mode);
if (!extCallsMode) if (!extCallsMode)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerExtCalls + ": " + mode); solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerExtCalls + ": " + mode);
m_options.modelChecker.settings.externalCalls = *extCallsMode; m_options.modelChecker.settings.externalCalls = *extCallsMode;
@ -1297,8 +1296,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strModelCheckerInvariants)) if (m_args.count(g_strModelCheckerInvariants))
{ {
string invsStr = m_args[g_strModelCheckerInvariants].as<string>(); std::string invsStr = m_args[g_strModelCheckerInvariants].as<std::string>();
optional<ModelCheckerInvariants> invs = ModelCheckerInvariants::fromString(invsStr); std::optional<ModelCheckerInvariants> invs = ModelCheckerInvariants::fromString(invsStr);
if (!invs) if (!invs)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerInvariants + ": " + invsStr); solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerInvariants + ": " + invsStr);
m_options.modelChecker.settings.invariants = *invs; m_options.modelChecker.settings.invariants = *invs;
@ -1315,8 +1314,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strModelCheckerSolvers)) if (m_args.count(g_strModelCheckerSolvers))
{ {
string solversStr = m_args[g_strModelCheckerSolvers].as<string>(); std::string solversStr = m_args[g_strModelCheckerSolvers].as<std::string>();
optional<smtutil::SMTSolverChoice> solvers = smtutil::SMTSolverChoice::fromString(solversStr); std::optional<smtutil::SMTSolverChoice> solvers = smtutil::SMTSolverChoice::fromString(solversStr);
if (!solvers) if (!solvers)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerSolvers + ": " + solversStr); solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerSolvers + ": " + solversStr);
m_options.modelChecker.settings.solvers = *solvers; m_options.modelChecker.settings.solvers = *solvers;
@ -1331,8 +1330,8 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strModelCheckerTargets)) if (m_args.count(g_strModelCheckerTargets))
{ {
string targetsStr = m_args[g_strModelCheckerTargets].as<string>(); std::string targetsStr = m_args[g_strModelCheckerTargets].as<std::string>();
optional<ModelCheckerTargets> targets = ModelCheckerTargets::fromString(targetsStr); std::optional<ModelCheckerTargets> targets = ModelCheckerTargets::fromString(targetsStr);
if (!targets) if (!targets)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerTargets + ": " + targetsStr); solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerTargets + ": " + targetsStr);
m_options.modelChecker.settings.targets = *targets; m_options.modelChecker.settings.targets = *targets;
@ -1371,8 +1370,8 @@ void CommandLineParser::parseCombinedJsonOption()
if (!m_args.count(g_strCombinedJson)) if (!m_args.count(g_strCombinedJson))
return; return;
set<string> requests; std::set<std::string> requests;
for (string const& item: boost::split(requests, m_args[g_strCombinedJson].as<string>(), boost::is_any_of(","))) for (std::string const& item: boost::split(requests, m_args[g_strCombinedJson].as<std::string>(), boost::is_any_of(",")))
if (CombinedJsonRequests::componentMap().count(item) == 0) if (CombinedJsonRequests::componentMap().count(item) == 0)
solThrow(CommandLineValidationError, "Invalid option to --" + g_strCombinedJson + ": " + item); solThrow(CommandLineValidationError, "Invalid option to --" + g_strCombinedJson + ": " + item);
@ -1381,19 +1380,19 @@ void CommandLineParser::parseCombinedJsonOption()
m_options.compiler.combinedJsonRequests.value().*component = (requests.count(componentName) > 0); m_options.compiler.combinedJsonRequests.value().*component = (requests.count(componentName) > 0);
} }
size_t CommandLineParser::countEnabledOptions(vector<string> const& _optionNames) const size_t CommandLineParser::countEnabledOptions(std::vector<std::string> const& _optionNames) const
{ {
size_t count = 0; size_t count = 0;
for (string const& _option: _optionNames) for (std::string const& _option: _optionNames)
count += m_args.count(_option); count += m_args.count(_option);
return count; return count;
} }
string CommandLineParser::joinOptionNames(vector<string> const& _optionNames, string _separator) std::string CommandLineParser::joinOptionNames(std::vector<std::string> const& _optionNames, std::string _separator)
{ {
return util::joinHumanReadable( return util::joinHumanReadable(
_optionNames | ranges::views::transform([](string const& _option){ return "--" + _option; }), _optionNames | ranges::views::transform([](std::string const& _option){ return "--" + _option; }),
_separator _separator
); );
} }

View File

@ -29,7 +29,6 @@
#include <iostream> #include <iostream>
using namespace std;
using namespace solidity; using namespace solidity;
@ -37,31 +36,31 @@ int main(int argc, char** argv)
{ {
try try
{ {
solidity::frontend::CommandLineInterface cli(cin, cout, cerr); solidity::frontend::CommandLineInterface cli(std::cin, std::cout, std::cerr);
return cli.run(argc, argv) ? 0 : 1; return cli.run(argc, argv) ? 0 : 1;
} }
catch (smtutil::SMTLogicError const& _exception) catch (smtutil::SMTLogicError const& _exception)
{ {
cerr << "SMT logic error:" << endl; std::cerr << "SMT logic error:" << std::endl;
cerr << boost::diagnostic_information(_exception); std::cerr << boost::diagnostic_information(_exception);
return 2; return 2;
} }
catch (langutil::UnimplementedFeatureError const& _exception) catch (langutil::UnimplementedFeatureError const& _exception)
{ {
cerr << "Unimplemented feature:" << endl; std::cerr << "Unimplemented feature:" << std::endl;
cerr << boost::diagnostic_information(_exception); std::cerr << boost::diagnostic_information(_exception);
return 2; return 2;
} }
catch (langutil::InternalCompilerError const& _exception) catch (langutil::InternalCompilerError const& _exception)
{ {
cerr << "Internal compiler error:" << endl; std::cerr << "Internal compiler error:" << std::endl;
cerr << boost::diagnostic_information(_exception); std::cerr << boost::diagnostic_information(_exception);
return 2; return 2;
} }
catch (...) catch (...)
{ {
cerr << "Uncaught exception:" << endl; std::cerr << "Uncaught exception:" << std::endl;
cerr << boost::current_exception_diagnostic_information() << endl; std::cerr << boost::current_exception_diagnostic_information() << std::endl;
return 2; return 2;
} }
} }