Merge pull request #14499 from ethereum/purge-using-namespace-std-from-libsolutil

Purge using namespace std from libsolutil
This commit is contained in:
Kamil Śliwak 2023-08-18 12:56:01 +02:00 committed by GitHub
commit d2f86ffb16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 127 additions and 139 deletions

View File

@ -29,7 +29,6 @@
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace solidity;
using namespace solidity::util;
@ -41,7 +40,7 @@ static char const* lowerHexChars = "0123456789abcdef";
}
string solidity::util::toHex(uint8_t _data, HexCase _case)
std::string solidity::util::toHex(uint8_t _data, HexCase _case)
{
assertThrow(_case != HexCase::Mixed, BadHexCase, "Mixed case can only be used for byte arrays.");
@ -53,7 +52,7 @@ string solidity::util::toHex(uint8_t _data, HexCase _case)
};
}
string solidity::util::toHex(bytes const& _data, HexPrefix _prefix, HexCase _case)
std::string solidity::util::toHex(bytes const& _data, HexPrefix _prefix, HexCase _case)
{
std::string ret(_data.size() * 2 + (_prefix == HexPrefix::Add ? 2 : 0), 0);
@ -90,7 +89,7 @@ int solidity::util::fromHex(char _i, WhenError _throw)
if (_i >= 'A' && _i <= 'F')
return _i - 'A' + 10;
if (_throw == WhenError::Throw)
assertThrow(false, BadHexCharacter, to_string(_i));
assertThrow(false, BadHexCharacter, std::to_string(_i));
else
return -1;
}
@ -125,31 +124,31 @@ bytes solidity::util::fromHex(std::string const& _s, WhenError _throw)
}
bool solidity::util::passesAddressChecksum(string const& _str, bool _strict)
bool solidity::util::passesAddressChecksum(std::string const& _str, bool _strict)
{
string s = _str.substr(0, 2) == "0x" ? _str : "0x" + _str;
std::string s = _str.substr(0, 2) == "0x" ? _str : "0x" + _str;
if (s.length() != 42)
return false;
if (!_strict && (
s.find_first_of("abcdef") == string::npos ||
s.find_first_of("ABCDEF") == string::npos
s.find_first_of("abcdef") == std::string::npos ||
s.find_first_of("ABCDEF") == std::string::npos
))
return true;
return s == solidity::util::getChecksummedAddress(s);
}
string solidity::util::getChecksummedAddress(string const& _addr)
std::string solidity::util::getChecksummedAddress(std::string const& _addr)
{
string s = _addr.substr(0, 2) == "0x" ? _addr.substr(2) : _addr;
std::string s = _addr.substr(0, 2) == "0x" ? _addr.substr(2) : _addr;
assertThrow(s.length() == 40, InvalidAddress, "");
assertThrow(s.find_first_not_of("0123456789abcdefABCDEF") == string::npos, InvalidAddress, "");
assertThrow(s.find_first_not_of("0123456789abcdefABCDEF") == std::string::npos, InvalidAddress, "");
h256 hash = keccak256(boost::algorithm::to_lower_copy(s, std::locale::classic()));
string ret = "0x";
std::string ret = "0x";
for (unsigned i = 0; i < 40; ++i)
{
char addressCharacter = s[i];
@ -162,16 +161,16 @@ string solidity::util::getChecksummedAddress(string const& _addr)
return ret;
}
bool solidity::util::isValidHex(string const& _string)
bool solidity::util::isValidHex(std::string const& _string)
{
if (_string.substr(0, 2) != "0x")
return false;
if (_string.find_first_not_of("0123456789abcdefABCDEF", 2) != string::npos)
if (_string.find_first_not_of("0123456789abcdefABCDEF", 2) != std::string::npos)
return false;
return true;
}
bool solidity::util::isValidDecimal(string const& _string)
bool solidity::util::isValidDecimal(std::string const& _string)
{
if (_string.empty())
return false;
@ -180,12 +179,12 @@ bool solidity::util::isValidDecimal(string const& _string)
// No leading zeros
if (_string.front() == '0')
return false;
if (_string.find_first_not_of("0123456789") != string::npos)
if (_string.find_first_not_of("0123456789") != std::string::npos)
return false;
return true;
}
string solidity::util::formatAsStringOrNumber(string const& _value)
std::string solidity::util::formatAsStringOrNumber(std::string const& _value)
{
assertThrow(_value.length() <= 32, StringTooLong, "String to be formatted longer than 32 bytes.");
@ -197,9 +196,9 @@ string solidity::util::formatAsStringOrNumber(string const& _value)
}
string solidity::util::escapeAndQuoteString(string const& _input)
std::string solidity::util::escapeAndQuoteString(std::string const& _input)
{
string out;
std::string out;
for (char c: _input)
if (c == '\\')
@ -214,8 +213,8 @@ string solidity::util::escapeAndQuoteString(string const& _input)
out += "\\t";
else if (!isPrint(c))
{
ostringstream o;
o << "\\x" << std::hex << setfill('0') << setw(2) << (unsigned)(unsigned char)(c);
std::ostringstream o;
o << "\\x" << std::hex << std::setfill('0') << std::setw(2) << (unsigned)(unsigned char)(c);
out += o.str();
}
else

View File

@ -31,7 +31,6 @@
#include <termios.h>
#endif
using namespace std;
using namespace solidity::util;
namespace
@ -55,35 +54,35 @@ inline T readFile(boost::filesystem::path const& _file)
// get length of file:
is.seekg(0, is.end);
streamoff length = is.tellg();
std::streamoff length = is.tellg();
if (length == 0)
return ret; // do not read empty file (MSVC does not like it)
is.seekg(0, is.beg);
ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<streamsize>(length));
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<std::streamsize>(length));
return ret;
}
}
string solidity::util::readFileAsString(boost::filesystem::path const& _file)
std::string solidity::util::readFileAsString(boost::filesystem::path const& _file)
{
return readFile<string>(_file);
return readFile<std::string>(_file);
}
string solidity::util::readUntilEnd(istream& _stdin)
std::string solidity::util::readUntilEnd(std::istream& _stdin)
{
ostringstream ss;
std::ostringstream ss;
ss << _stdin.rdbuf();
return ss.str();
}
string solidity::util::readBytes(istream& _input, size_t _length)
std::string solidity::util::readBytes(std::istream& _input, size_t _length)
{
string output;
std::string output;
output.resize(_length);
_input.read(output.data(), static_cast<streamsize>(_length));
_input.read(output.data(), static_cast<std::streamsize>(_length));
// If read() reads fewer bytes it sets failbit in addition to eofbit.
if (_input.fail())
output.resize(static_cast<size_t>(_input.gcount()));
@ -135,10 +134,10 @@ private:
int solidity::util::readStandardInputChar()
{
DisableConsoleBuffering disableConsoleBuffering;
return cin.get();
return std::cin.get();
}
string solidity::util::absolutePath(string const& _path, string const& _reference)
std::string solidity::util::absolutePath(std::string const& _path, std::string const& _reference)
{
boost::filesystem::path p(_path);
// Anything that does not start with `.` is an absolute path.
@ -158,6 +157,6 @@ string solidity::util::absolutePath(string const& _path, string const& _referenc
return result.generic_string();
}
string solidity::util::sanitizePath(string const& _path) {
std::string solidity::util::sanitizePath(std::string const& _path) {
return boost::filesystem::path(_path).generic_string();
}

View File

@ -18,13 +18,12 @@
#include <libsolutil/Exceptions.h>
using namespace std;
using namespace solidity::util;
char const* Exception::what() const noexcept
{
// Return the comment if available.
if (string const* cmt = comment())
if (std::string const* cmt = comment())
return cmt->data();
// Fallback to base what().
@ -33,20 +32,20 @@ char const* Exception::what() const noexcept
return std::exception::what();
}
string Exception::lineInfo() const
std::string Exception::lineInfo() const
{
char const* const* file = boost::get_error_info<boost::throw_file>(*this);
int const* line = boost::get_error_info<boost::throw_line>(*this);
string ret;
std::string ret;
if (file)
ret += *file;
ret += ':';
if (line)
ret += to_string(*line);
ret += std::to_string(*line);
return ret;
}
string const* Exception::comment() const noexcept
std::string const* Exception::comment() const noexcept
{
return boost::get_error_info<errinfo_comment>(*this);
}

View File

@ -23,21 +23,20 @@
#include <libsolutil/IndentedWriter.h>
#include <libsolutil/Assertions.h>
using namespace std;
using namespace solidity::util;
string IndentedWriter::format() const
std::string IndentedWriter::format() const
{
string result;
std::string result;
for (auto const& line: m_lines)
result += string(line.indentation * 4, ' ') + line.contents + "\n";
result += std::string(line.indentation * 4, ' ') + line.contents + "\n";
return result;
}
void IndentedWriter::newLine()
{
if (!m_lines.back().contents.empty())
m_lines.emplace_back(Line{string(), m_lines.back().indentation});
m_lines.emplace_back(Line{std::string(), m_lines.back().indentation});
}
void IndentedWriter::indent()
@ -53,12 +52,12 @@ void IndentedWriter::unindent()
m_lines.back().indentation--;
}
void IndentedWriter::add(string const& _str)
void IndentedWriter::add(std::string const& _str)
{
m_lines.back().contents += _str;
}
void IndentedWriter::addLine(string const& _line)
void IndentedWriter::addLine(std::string const& _line)
{
newLine();
add(_line);

View File

@ -23,7 +23,6 @@
#include <libsolutil/CommonData.h>
#include <libsolutil/Numeric.h>
using namespace std;
using namespace solidity;
using namespace solidity::util;
@ -56,11 +55,11 @@ bytes encodeLinkData(bytes const& _data)
return bytes{0x12} + varintEncoding(_data.size()) + _data;
}
string base58Encode(bytes const& _data)
std::string base58Encode(bytes const& _data)
{
static string const alphabet{"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"};
static std::string const alphabet{"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"};
bigint data(util::toHex(_data, HexPrefix::Add));
string output;
std::string output;
while (data)
{
output += alphabet[static_cast<size_t>(data % alphabet.size())];
@ -84,7 +83,7 @@ struct Chunk
size_t blockSize = 0;
};
using Chunks = vector<Chunk>;
using Chunks = std::vector<Chunk>;
Chunk combineLinks(Chunks& _links)
{
@ -153,7 +152,7 @@ bytes groupChunksBottomUp(Chunks _currentLevel)
}
}
bytes solidity::util::ipfsHash(string _data)
bytes solidity::util::ipfsHash(std::string _data)
{
size_t const maxChunkSize = 1024 * 256;
size_t chunkCount = _data.length() / maxChunkSize + (_data.length() % maxChunkSize > 0 ? 1 : 0);
@ -164,7 +163,7 @@ bytes solidity::util::ipfsHash(string _data)
for (size_t chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++)
{
bytes chunkBytes = asBytes(
_data.substr(chunkIndex * maxChunkSize, min(maxChunkSize, _data.length() - chunkIndex * maxChunkSize))
_data.substr(chunkIndex * maxChunkSize, std::min(maxChunkSize, _data.length() - chunkIndex * maxChunkSize))
);
bytes lengthAsVarint = varintEncoding(chunkBytes.size());
@ -197,7 +196,7 @@ bytes solidity::util::ipfsHash(string _data)
return groupChunksBottomUp(std::move(allChunks));
}
string solidity::util::ipfsHashBase58(string _data)
std::string solidity::util::ipfsHashBase58(std::string _data)
{
return base58Encode(ipfsHash(std::move(_data)));
}

View File

@ -30,8 +30,6 @@
#include <map>
#include <memory>
using namespace std;
static_assert(
(JSONCPP_VERSION_MAJOR == 1) && (JSONCPP_VERSION_MINOR == 9) && (JSONCPP_VERSION_PATCH == 3),
"Unexpected jsoncpp version: " JSONCPP_VERSION_STRING ". Expecting 1.9.3."
@ -47,7 +45,7 @@ namespace
class StreamWriterBuilder: public Json::StreamWriterBuilder
{
public:
explicit StreamWriterBuilder(map<string, Json::Value> const& _settings)
explicit StreamWriterBuilder(std::map<std::string, Json::Value> const& _settings)
{
for (auto const& iter: _settings)
this->settings_[iter.first] = iter.second;
@ -68,10 +66,10 @@ public:
/// \param _input JSON input string
/// \param _builder StreamWriterBuilder that is used to create new Json::StreamWriter
/// \return serialized json object
string print(Json::Value const& _input, Json::StreamWriterBuilder const& _builder)
std::string print(Json::Value const& _input, Json::StreamWriterBuilder const& _builder)
{
stringstream stream;
unique_ptr<Json::StreamWriter> writer(_builder.newStreamWriter());
std::stringstream stream;
std::unique_ptr<Json::StreamWriter> writer(_builder.newStreamWriter());
writer->write(_input, &stream);
return stream.str();
}
@ -82,9 +80,9 @@ string print(Json::Value const& _input, Json::StreamWriterBuilder const& _builde
/// \param _json [out] resulting JSON object
/// \param _errs [out] Formatted error messages
/// \return \c true if the document was successfully parsed, \c false if an error occurred.
bool parse(Json::CharReaderBuilder& _builder, string const& _input, Json::Value& _json, string* _errs)
bool parse(Json::CharReaderBuilder& _builder, std::string const& _input, Json::Value& _json, std::string* _errs)
{
unique_ptr<Json::CharReader> reader(_builder.newCharReader());
std::unique_ptr<Json::CharReader> reader(_builder.newCharReader());
return reader->parse(_input.c_str(), _input.c_str() + _input.length(), &_json, _errs);
}
@ -113,34 +111,34 @@ Json::Value removeNullMembers(Json::Value _json)
return _json;
}
string jsonPrettyPrint(Json::Value const& _input)
std::string jsonPrettyPrint(Json::Value const& _input)
{
return jsonPrint(_input, JsonFormat{ JsonFormat::Pretty });
}
string jsonCompactPrint(Json::Value const& _input)
std::string jsonCompactPrint(Json::Value const& _input)
{
return jsonPrint(_input, JsonFormat{ JsonFormat::Compact });
}
string jsonPrint(Json::Value const& _input, JsonFormat const& _format)
std::string jsonPrint(Json::Value const& _input, JsonFormat const& _format)
{
map<string, Json::Value> settings;
std::map<std::string, Json::Value> settings;
if (_format.format == JsonFormat::Pretty)
{
settings["indentation"] = string(_format.indent, ' ');
settings["indentation"] = std::string(_format.indent, ' ');
settings["enableYAMLCompatibility"] = true;
}
else
settings["indentation"] = "";
StreamWriterBuilder writerBuilder(settings);
string result = print(_input, writerBuilder);
std::string result = print(_input, writerBuilder);
if (_format.format == JsonFormat::Pretty)
boost::replace_all(result, " \n", "\n");
return result;
}
bool jsonParseStrict(string const& _input, Json::Value& _json, string* _errs /* = nullptr */)
bool jsonParseStrict(std::string const& _input, Json::Value& _json, std::string* _errs /* = nullptr */)
{
static StrictModeCharReaderBuilder readerBuilder;
return parse(readerBuilder, _input, _json, _errs);

View File

@ -25,8 +25,6 @@
#include <cstdint>
#include <cstring>
using namespace std;
namespace solidity::util
{

View File

@ -26,11 +26,10 @@
#include <string>
#include <vector>
using namespace std;
using namespace solidity;
using namespace solidity::util;
bool solidity::util::stringWithinDistance(string const& _str1, string const& _str2, size_t _maxDistance, size_t _lenThreshold)
bool solidity::util::stringWithinDistance(std::string const& _str1, std::string const& _str2, size_t _maxDistance, size_t _lenThreshold)
{
if (_str1 == _str2)
return true;
@ -47,13 +46,13 @@ bool solidity::util::stringWithinDistance(string const& _str1, string const& _st
return distance <= _maxDistance && distance < n1 && distance < n2;
}
size_t solidity::util::stringDistance(string const& _str1, string const& _str2)
size_t solidity::util::stringDistance(std::string const& _str1, std::string const& _str2)
{
size_t n1 = _str1.size();
size_t n2 = _str2.size();
// Optimize by storing only last 2 rows and current row. So first index is considered modulo 3
// This is a two-dimensional array of size 3 x (n2 + 1).
vector<size_t> dp(3 * (n2 + 1));
std::vector<size_t> dp(3 * (n2 + 1));
// In this dp formulation of DamerauLevenshtein distance we are assuming that the strings are 1-based to make base case storage easier.
// So index accesser to _name1 and _name2 have to be adjusted accordingly
@ -61,25 +60,25 @@ size_t solidity::util::stringDistance(string const& _str1, string const& _str2)
for (size_t i2 = 0; i2 <= n2; ++i2)
{
size_t x = 0;
if (min(i1, i2) == 0) // base case
x = max(i1, i2);
if (std::min(i1, i2) == 0) // base case
x = std::max(i1, i2);
else
{
size_t left = dp[(i1 - 1) % 3 + i2 * 3];
size_t up = dp[(i1 % 3) + (i2 - 1) * 3];
size_t upleft = dp[((i1 - 1) % 3) + (i2 - 1) * 3];
// deletion and insertion
x = min(left + 1, up + 1);
x = std::min(left + 1, up + 1);
if (_str1[i1-1] == _str2[i2-1])
// same chars, can skip
x = min(x, upleft);
x = std::min(x, upleft);
else
// different chars so try substitution
x = min(x, upleft + 1);
x = std::min(x, upleft + 1);
// transposing
if (i1 > 1 && i2 > 1 && _str1[i1 - 1] == _str2[i2 - 2] && _str1[i1 - 2] == _str2[i2 - 1])
x = min(x, dp[((i1 - 2) % 3) + (i2 - 2) * 3] + 1);
x = std::min(x, dp[((i1 - 2) % 3) + (i2 - 2) * 3] + 1);
}
dp[(i1 % 3) + i2 * 3] = x;
}
@ -87,9 +86,9 @@ size_t solidity::util::stringDistance(string const& _str1, string const& _str2)
return dp[(n1 % 3) + n2 * 3];
}
string solidity::util::quotedAlternativesList(vector<string> const& suggestions)
std::string solidity::util::quotedAlternativesList(std::vector<std::string> const& suggestions)
{
vector<string> quotedSuggestions;
std::vector<std::string> quotedSuggestions;
for (auto& suggestion: suggestions)
quotedSuggestions.emplace_back("\"" + suggestion + "\"");
@ -97,20 +96,20 @@ string solidity::util::quotedAlternativesList(vector<string> const& suggestions)
return joinHumanReadable(quotedSuggestions, ", ", " or ");
}
string solidity::util::suffixedVariableNameList(string const& _baseName, size_t _startSuffix, size_t _endSuffix)
std::string solidity::util::suffixedVariableNameList(std::string const& _baseName, size_t _startSuffix, size_t _endSuffix)
{
string result;
std::string result;
if (_startSuffix < _endSuffix)
{
result = _baseName + to_string(_startSuffix++);
result = _baseName + std::to_string(_startSuffix++);
while (_startSuffix < _endSuffix)
result += ", " + _baseName + to_string(_startSuffix++);
result += ", " + _baseName + std::to_string(_startSuffix++);
}
else if (_endSuffix < _startSuffix)
{
result = _baseName + to_string(_endSuffix++);
result = _baseName + std::to_string(_endSuffix++);
while (_endSuffix < _startSuffix)
result = _baseName + to_string(_endSuffix++) + ", " + result;
result = _baseName + std::to_string(_endSuffix++) + ", " + result;
}
return result;
}
@ -119,7 +118,7 @@ namespace
{
/// Try to format as N * 2**x
optional<string> tryFormatPowerOfTwo(bigint const& _value)
std::optional<std::string> tryFormatPowerOfTwo(bigint const& _value)
{
bigint prefix = _value;
@ -128,7 +127,7 @@ optional<string> tryFormatPowerOfTwo(bigint const& _value)
for (; (prefix & 0xff) == 0; prefix >>= 8)
++i;
if (i <= 2)
return nullopt;
return std::nullopt;
// 0x100 yields 2**8 (N is 1 and redundant)
if (prefix == 1)
@ -150,11 +149,11 @@ optional<string> tryFormatPowerOfTwo(bigint const& _value)
}
string solidity::util::formatNumberReadable(bigint const& _value, bool _useTruncation)
std::string solidity::util::formatNumberReadable(bigint const& _value, bool _useTruncation)
{
bool const isNegative = _value < 0;
bigint const absValue = isNegative ? (bigint(-1) * _value) : bigint(_value);
string const sign = isNegative ? "-" : "";
std::string const sign = isNegative ? "-" : "";
// smaller numbers return as decimal
if (absValue <= 0x1000000)
@ -165,7 +164,7 @@ string solidity::util::formatNumberReadable(bigint const& _value, bool _useTrunc
else if (auto result = tryFormatPowerOfTwo(absValue + 1))
return {sign + *result + (isNegative ? " + 1" : " - 1")};
string str = toHex(toCompactBigEndian(absValue), HexPrefix::Add, HexCase::Mixed);
std::string str = toHex(toCompactBigEndian(absValue), HexPrefix::Add, HexCase::Mixed);
if (_useTruncation)
{

View File

@ -22,7 +22,6 @@
#include <libsolutil/Keccak256.h>
using namespace std;
using namespace solidity;
using namespace solidity::util;
@ -42,7 +41,7 @@ h256 swarmHashSimple(bytesConstRef _data, size_t _size)
return keccak256(toLittleEndian(_size) + _data.toBytes());
}
h256 swarmHashIntermediate(string const& _input, size_t _offset, size_t _length)
h256 swarmHashIntermediate(std::string const& _input, size_t _offset, size_t _length)
{
bytesConstRef ref;
bytes innerNodes;
@ -104,7 +103,7 @@ h256 chunkHash(bytesConstRef const _data, bool _forceHigherLevel = false)
}
h256 solidity::util::bzzr0Hash(string const& _input)
h256 solidity::util::bzzr0Hash(std::string const& _input)
{
return swarmHashIntermediate(_input, 0, _input.size());
}

View File

@ -26,7 +26,6 @@
#include <regex>
#include <iostream>
using namespace std;
using namespace solidity;
using namespace solidity::util;
@ -42,8 +41,8 @@ TemporaryDirectory::TemporaryDirectory(std::string const& _prefix):
}
TemporaryDirectory::TemporaryDirectory(
vector<boost::filesystem::path> const& _subdirectories,
string const& _prefix
std::vector<boost::filesystem::path> const& _subdirectories,
std::string const& _prefix
):
TemporaryDirectory(_prefix)
{
@ -71,9 +70,9 @@ TemporaryDirectory::~TemporaryDirectory()
uintmax_t numRemoved = fs::remove_all(m_path, errorCode);
if (errorCode.value() != boost::system::errc::success)
{
cerr << "Failed to completely remove temporary directory '" << m_path << "'. ";
cerr << "Only " << numRemoved << " files were actually removed." << endl;
cerr << "Reason: " << errorCode.message() << endl;
std::cerr << "Failed to completely remove temporary directory '" << m_path << "'. ";
std::cerr << "Only " << numRemoved << " files were actually removed." << std::endl;
std::cerr << "Reason: " << errorCode.message() << std::endl;
}
}

View File

@ -28,16 +28,15 @@
#include <regex>
using namespace std;
using namespace solidity::util;
Whiskers::Whiskers(string _template):
Whiskers::Whiskers(std::string _template):
m_template(std::move(_template))
{
checkTemplateValid();
}
Whiskers& Whiskers::operator()(string _parameter, string _value)
Whiskers& Whiskers::operator()(std::string _parameter, std::string _value)
{
checkParameterValid(_parameter);
checkParameterUnknown(_parameter);
@ -46,7 +45,7 @@ Whiskers& Whiskers::operator()(string _parameter, string _value)
return *this;
}
Whiskers& Whiskers::operator()(string _parameter, bool _value)
Whiskers& Whiskers::operator()(std::string _parameter, bool _value)
{
checkParameterValid(_parameter);
checkParameterUnknown(_parameter);
@ -56,8 +55,8 @@ Whiskers& Whiskers::operator()(string _parameter, bool _value)
}
Whiskers& Whiskers::operator()(
string _listParameter,
vector<map<string, string>> _values
std::string _listParameter,
std::vector<std::map<std::string, std::string>> _values
)
{
checkParameterValid(_listParameter);
@ -70,15 +69,15 @@ Whiskers& Whiskers::operator()(
return *this;
}
string Whiskers::render() const
std::string Whiskers::render() const
{
return replace(m_template, m_parameters, m_conditions, m_listParameters);
}
void Whiskers::checkTemplateValid() const
{
regex validTemplate("<[#?!\\/]\\+{0,1}[a-zA-Z0-9_$-]+(?:[^a-zA-Z0-9_$>-]|$)");
smatch match;
std::regex validTemplate("<[#?!\\/]\\+{0,1}[a-zA-Z0-9_$-]+(?:[^a-zA-Z0-9_$>-]|$)");
std::smatch match;
assertThrow(
!regex_search(m_template, match, validTemplate),
WhiskersError,
@ -86,9 +85,9 @@ void Whiskers::checkTemplateValid() const
);
}
void Whiskers::checkParameterValid(string const& _parameter) const
void Whiskers::checkParameterValid(std::string const& _parameter) const
{
static regex validParam("^" + paramRegex() + "$");
static std::regex validParam("^" + paramRegex() + "$");
assertThrow(
regex_match(_parameter, validParam),
WhiskersError,
@ -96,7 +95,7 @@ void Whiskers::checkParameterValid(string const& _parameter) const
);
}
void Whiskers::checkParameterUnknown(string const& _parameter) const
void Whiskers::checkParameterUnknown(std::string const& _parameter) const
{
assertThrow(
!m_parameters.count(_parameter),
@ -115,13 +114,13 @@ void Whiskers::checkParameterUnknown(string const& _parameter) const
);
}
void Whiskers::checkTemplateContainsTags(string const& _parameter, vector<string> const& _prefixes) const
void Whiskers::checkTemplateContainsTags(std::string const& _parameter, std::vector<std::string> const& _prefixes) const
{
for (auto const& prefix: _prefixes)
{
string tag{"<" + prefix + _parameter + ">"};
std::string tag{"<" + prefix + _parameter + ">"};
assertThrow(
m_template.find(tag) != string::npos,
m_template.find(tag) != std::string::npos,
WhiskersError,
"Tag '" + tag + "' not found in template:\n" + m_template
);
@ -131,17 +130,17 @@ void Whiskers::checkTemplateContainsTags(string const& _parameter, vector<string
namespace
{
template<class ReplaceCallback>
string regex_replace(
string const& _source,
regex const& _pattern,
std::string regex_replace(
std::string const& _source,
std::regex const& _pattern,
ReplaceCallback _replace,
regex_constants::match_flag_type _flags = regex_constants::match_default
std::regex_constants::match_flag_type _flags = std::regex_constants::match_default
)
{
sregex_iterator curMatch(_source.begin(), _source.end(), _pattern, _flags);
sregex_iterator matchEnd;
string::const_iterator lastMatchedPos(_source.cbegin());
string result;
std::sregex_iterator curMatch(_source.begin(), _source.end(), _pattern, _flags);
std::sregex_iterator matchEnd;
std::string::const_iterator lastMatchedPos(_source.cbegin());
std::string result;
while (curMatch != matchEnd)
{
result.append(curMatch->prefix().first, curMatch->prefix().second);
@ -154,23 +153,23 @@ string regex_replace(
}
}
string Whiskers::replace(
string const& _template,
std::string Whiskers::replace(
std::string const& _template,
StringMap const& _parameters,
map<string, bool> const& _conditions,
map<string, vector<StringMap>> const& _listParameters
std::map<std::string, bool> const& _conditions,
std::map<std::string, std::vector<StringMap>> const& _listParameters
)
{
static regex listOrTag(
static std::regex listOrTag(
"<(" + paramRegex() + ")>|"
"<#(" + paramRegex() + ")>((?:.|\\r|\\n)*?)</\\2>|"
"<\\?(\\+?" + paramRegex() + ")>((?:.|\\r|\\n)*?)(<!\\4>((?:.|\\r|\\n)*?))?</\\4>"
);
return regex_replace(_template, listOrTag, [&](match_results<string::const_iterator> _match) -> string
return regex_replace(_template, listOrTag, [&](std::match_results<std::string::const_iterator> _match) -> std::string
{
string tagName(_match[1]);
string listName(_match[2]);
string conditionName(_match[4]);
std::string tagName(_match[1]);
std::string listName(_match[2]);
std::string conditionName(_match[4]);
if (!tagName.empty())
{
assertThrow(
@ -184,12 +183,12 @@ string Whiskers::replace(
}
else if (!listName.empty())
{
string templ(_match[3]);
std::string templ(_match[3]);
assertThrow(
_listParameters.count(listName),
WhiskersError, "List parameter " + listName + " not set."
);
string replacement;
std::string replacement;
for (auto const& parameters: _listParameters.at(listName))
replacement += replace(templ, joinMaps(_parameters, parameters), _conditions);
return replacement;
@ -200,7 +199,7 @@ string Whiskers::replace(
bool conditionValue = false;
if (conditionName[0] == '+')
{
string tag = conditionName.substr(1);
std::string tag = conditionName.substr(1);
if (_parameters.count(tag))
conditionValue = !_parameters.at(tag).empty();

View File

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