Merge pull request #12746 from tfire/fix/remove-namespace-ast-annotations

Remove use of `using namespace` in header file
This commit is contained in:
Daniel Kirchner 2022-03-11 12:49:13 +01:00 committed by GitHub
commit 09f667948b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 123 additions and 121 deletions

View File

@ -129,7 +129,7 @@ void ControlFlowAnalyzer::checkUninitializedAccess(CFGNode const* _entry, CFGNod
// Propagate changes to all exits and queue them for traversal, if needed.
for (auto const& exit: currentNode->exits)
if (
auto exists = valueOrNullptr(nodeInfos, exit);
auto exists = util::valueOrNullptr(nodeInfos, exit);
nodeInfos[exit].propagateFrom(nodeInfo) || !exists
)
nodesToTraverse.insert(exit);

View File

@ -57,7 +57,7 @@ void ControlFlowRevertPruner::run()
void ControlFlowRevertPruner::findRevertStates()
{
std::set<CFG::FunctionContractTuple> pendingFunctions = keys(m_functions);
std::set<CFG::FunctionContractTuple> pendingFunctions = util::keys(m_functions);
// We interrupt the search whenever we encounter a call to a function with (yet) unknown
// revert behaviour. The ``wakeUp`` data structure contains information about which
// searches to restart once we know about the behaviour.

View File

@ -97,7 +97,7 @@ CallGraph FunctionCallGraphBuilder::buildDeployedGraph(
// assigned to state variables and as such may be reachable after deployment as well.
builder.m_currentNode = CallGraph::SpecialNode::InternalDispatch;
set<CallGraph::Node, CallGraph::CompareByID> defaultNode;
for (CallGraph::Node const& dispatchTarget: valueOrDefault(_creationGraph.edges, CallGraph::SpecialNode::InternalDispatch, defaultNode))
for (CallGraph::Node const& dispatchTarget: util::valueOrDefault(_creationGraph.edges, CallGraph::SpecialNode::InternalDispatch, defaultNode))
{
solAssert(!holds_alternative<CallGraph::SpecialNode>(dispatchTarget), "");
solAssert(get<CallableDeclaration const*>(dispatchTarget) != nullptr, "");

View File

@ -411,12 +411,12 @@ struct ReservedErrorSelector: public PostTypeChecker::Checker
);
else
{
uint32_t selector = selectorFromSignature32(_error.functionType(true)->externalSignature());
uint32_t selector = util::selectorFromSignature32(_error.functionType(true)->externalSignature());
if (selector == 0 || ~selector == 0)
m_errorReporter.syntaxError(
2855_error,
_error.location(),
"The selector 0x" + toHex(toCompactBigEndian(selector, 4)) + " is reserved. Please rename the error to avoid the collision."
"The selector 0x" + util::toHex(toCompactBigEndian(selector, 4)) + " is reserved. Please rename the error to avoid the collision."
);
}
}

View File

@ -52,7 +52,7 @@ bool PostTypeContractLevelChecker::check(ContractDefinition const& _contract)
for (ErrorDefinition const* error: _contract.interfaceErrors())
{
string signature = error->functionType(true)->externalSignature();
uint32_t hash = selectorFromSignature32(signature);
uint32_t hash = util::selectorFromSignature32(signature);
// Fail if there is a different signature for the same hash.
if (!errorHashes[hash].empty() && !errorHashes[hash].count(signature))
{

View File

@ -659,7 +659,7 @@ void TypeChecker::visitManually(
if (auto const* modifierContract = dynamic_cast<ContractDefinition const*>(modifierDecl->scope()))
if (m_currentContract)
{
if (!contains(m_currentContract->annotation().linearizedBaseContracts, modifierContract))
if (!util::contains(m_currentContract->annotation().linearizedBaseContracts, modifierContract))
m_errorReporter.typeError(
9428_error,
_modifier.location(),
@ -2143,7 +2143,7 @@ void TypeChecker::typeCheckABIEncodeCallFunction(FunctionCall const& _functionCa
functionPointerType->declaration().scope() == m_currentContract
)
msg += " Did you forget to prefix \"this.\"?";
else if (contains(
else if (util::contains(
m_currentContract->annotation().linearizedBaseContracts,
functionPointerType->declaration().scope()
) && functionPointerType->declaration().scope() != m_currentContract)

View File

@ -221,7 +221,7 @@ vector<EventDefinition const*> const ContractDefinition::usedInterfaceEvents() c
{
solAssert(annotation().creationCallGraph.set(), "");
return convertContainer<std::vector<EventDefinition const*>>(
return util::convertContainer<std::vector<EventDefinition const*>>(
(*annotation().creationCallGraph)->emittedEvents +
(*annotation().deployedCallGraph)->emittedEvents
);
@ -239,7 +239,7 @@ vector<ErrorDefinition const*> ContractDefinition::interfaceErrors(bool _require
result +=
(*annotation().creationCallGraph)->usedErrors +
(*annotation().deployedCallGraph)->usedErrors;
return convertContainer<vector<ErrorDefinition const*>>(move(result));
return util::convertContainer<vector<ErrorDefinition const*>>(move(result));
}
vector<pair<util::FixedHash<4>, FunctionTypePointer>> const& ContractDefinition::interfaceFunctionList(bool _includeInheritedFunctions) const

View File

@ -47,7 +47,6 @@ namespace solidity::frontend
class Type;
class ArrayType;
using namespace util;
struct CallGraph;
@ -91,13 +90,13 @@ struct StructurallyDocumentedAnnotation
struct SourceUnitAnnotation: ASTAnnotation
{
/// The "absolute" (in the compiler sense) path of this source unit.
SetOnce<std::string> path;
util::SetOnce<std::string> path;
/// The exported symbols (all global symbols).
SetOnce<std::map<ASTString, std::vector<Declaration const*>>> exportedSymbols;
util::SetOnce<std::map<ASTString, std::vector<Declaration const*>>> exportedSymbols;
/// Experimental features.
std::set<ExperimentalFeature> experimentalFeatures;
/// Using the new ABI coder. Set to `false` if using ABI coder v1.
SetOnce<bool> useABICoderV2;
util::SetOnce<bool> useABICoderV2;
};
struct ScopableAnnotation
@ -127,7 +126,7 @@ struct DeclarationAnnotation: ASTAnnotation, ScopableAnnotation
struct ImportAnnotation: DeclarationAnnotation
{
/// The absolute path of the source unit to import.
SetOnce<std::string> absolutePath;
util::SetOnce<std::string> absolutePath;
/// The actual source unit.
SourceUnit const* sourceUnit = nullptr;
};
@ -135,7 +134,7 @@ struct ImportAnnotation: DeclarationAnnotation
struct TypeDeclarationAnnotation: DeclarationAnnotation
{
/// The name of this type, prefixed by proper namespaces if globally accessible.
SetOnce<std::string> canonicalName;
util::SetOnce<std::string> canonicalName;
};
struct StructDeclarationAnnotation: TypeDeclarationAnnotation
@ -162,9 +161,9 @@ struct ContractDefinitionAnnotation: TypeDeclarationAnnotation, StructurallyDocu
/// These can either be inheritance specifiers or modifier invocations.
std::map<FunctionDefinition const*, ASTNode const*> baseConstructorArguments;
/// A graph with edges representing calls between functions that may happen during contract construction.
SetOnce<std::shared_ptr<CallGraph const>> creationCallGraph;
util::SetOnce<std::shared_ptr<CallGraph const>> creationCallGraph;
/// A graph with edges representing calls between functions that may happen in a deployed contract.
SetOnce<std::shared_ptr<CallGraph const>> deployedCallGraph;
util::SetOnce<std::shared_ptr<CallGraph const>> deployedCallGraph;
/// List of contracts whose bytecode is referenced by this contract, e.g. through "new".
/// The Value represents the ast node that referenced the contract.
@ -223,7 +222,7 @@ struct InlineAssemblyAnnotation: StatementAnnotation
/// True, if the assembly block was annotated to be memory-safe.
bool markedMemorySafe = false;
/// True, if the assembly block involves any memory opcode or assigns to variables in memory.
SetOnce<bool> hasMemoryEffects;
util::SetOnce<bool> hasMemoryEffects;
};
struct BlockAnnotation: StatementAnnotation, ScopableAnnotation
@ -256,7 +255,7 @@ struct IdentifierPathAnnotation: ASTAnnotation
/// Referenced declaration, set during reference resolution stage.
Declaration const* referencedDeclaration = nullptr;
/// What kind of lookup needs to be done (static, virtual, super) find the declaration.
SetOnce<VirtualLookup> requiredLookup;
util::SetOnce<VirtualLookup> requiredLookup;
};
struct ExpressionAnnotation: ASTAnnotation
@ -264,11 +263,11 @@ struct ExpressionAnnotation: ASTAnnotation
/// Inferred type of the expression.
Type const* type = nullptr;
/// Whether the expression is a constant variable
SetOnce<bool> isConstant;
util::SetOnce<bool> isConstant;
/// Whether the expression is pure, i.e. compile-time constant.
SetOnce<bool> isPure;
util::SetOnce<bool> isPure;
/// Whether it is an LValue (i.e. something that can be assigned to).
SetOnce<bool> isLValue;
util::SetOnce<bool> isLValue;
/// Whether the expression is used in a context where the LValue is actually required.
bool willBeWrittenTo = false;
/// Whether the expression is an lvalue that is only assigned.
@ -295,7 +294,7 @@ struct IdentifierAnnotation: ExpressionAnnotation
/// Referenced declaration, set at latest during overload resolution stage.
Declaration const* referencedDeclaration = nullptr;
/// What kind of lookup needs to be done (static, virtual, super) find the declaration.
SetOnce<VirtualLookup> requiredLookup;
util::SetOnce<VirtualLookup> requiredLookup;
/// List of possible declarations it could refer to (can contain duplicates).
std::vector<Declaration const*> candidateDeclarations;
/// List of possible declarations it could refer to.
@ -307,7 +306,7 @@ struct MemberAccessAnnotation: ExpressionAnnotation
/// Referenced declaration, set at latest during overload resolution stage.
Declaration const* referencedDeclaration = nullptr;
/// What kind of lookup needs to be done (static, virtual, super) find the declaration.
SetOnce<VirtualLookup> requiredLookup;
util::SetOnce<VirtualLookup> requiredLookup;
};
struct BinaryOperationAnnotation: ExpressionAnnotation

View File

@ -505,7 +505,7 @@ bool ASTJsonConverter::visit(EventDefinition const& _node)
_attributes.emplace_back(
make_pair(
"eventSelector",
toHex(u256(h256::Arith(util::keccak256(_node.functionType(true)->externalSignature()))))
toHex(u256(util::h256::Arith(util::keccak256(_node.functionType(true)->externalSignature()))))
));
setJsonNode(_node, "EventDefinition", std::move(_attributes));

View File

@ -403,7 +403,7 @@ void CompilerContext::appendInlineAssembly(
{
if (_insideFunction)
return false;
return contains(_localVariables, _identifier.name.str());
return util::contains(_localVariables, _identifier.name.str());
};
identifierAccess.generateCode = [&](
yul::Identifier const& _identifier,

View File

@ -235,7 +235,7 @@ size_t ContractCompiler::deployLibrary(ContractDefinition const& _contract)
m_context.pushSubroutineOffset(m_context.runtimeSub());
// This code replaces the address added by appendDeployTimeAddress().
m_context.appendInlineAssembly(
Whiskers(R"(
util::Whiskers(R"(
{
// If code starts at 11, an mstore(0) writes to the full PUSH20 plus data
// without the need for a shift.
@ -672,7 +672,7 @@ bool ContractCompiler::visit(FunctionDefinition const& _function)
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_function.location()) <<
errinfo_comment("Stack too deep, try removing local variables.")
util::errinfo_comment("Stack too deep, try removing local variables.")
);
while (!stackLayout.empty() && stackLayout.back() != static_cast<int>(stackLayout.size() - 1))
if (stackLayout.back() < 0)
@ -842,7 +842,7 @@ bool ContractCompiler::visit(InlineAssembly const& _inlineAssembly)
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_inlineAssembly.location()) <<
errinfo_comment("Stack too deep, try removing local variables.")
util::errinfo_comment("Stack too deep, try removing local variables.")
);
_assembly.appendInstruction(dupInstruction(stackDiff));
}
@ -916,7 +916,7 @@ bool ContractCompiler::visit(InlineAssembly const& _inlineAssembly)
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_inlineAssembly.location()) <<
errinfo_comment("Stack too deep(" + to_string(stackDiff) + "), try removing local variables.")
util::errinfo_comment("Stack too deep(" + to_string(stackDiff) + "), try removing local variables.")
);
_assembly.appendInstruction(swapInstruction(stackDiff));
_assembly.appendInstruction(Instruction::POP);
@ -1045,7 +1045,7 @@ void ContractCompiler::handleCatch(vector<ASTPointer<TryCatchClause>> const& _ca
solAssert(m_context.evmVersion().supportsReturndata(), "");
// stack: <selector>
m_context << Instruction::DUP1 << selectorFromSignature32("Error(string)") << Instruction::EQ;
m_context << Instruction::DUP1 << util::selectorFromSignature32("Error(string)") << Instruction::EQ;
m_context << Instruction::ISZERO;
m_context.appendConditionalJumpTo(panicTag);
m_context << Instruction::POP; // remove selector
@ -1077,7 +1077,7 @@ void ContractCompiler::handleCatch(vector<ASTPointer<TryCatchClause>> const& _ca
solAssert(m_context.evmVersion().supportsReturndata(), "");
// stack: <selector>
m_context << selectorFromSignature32("Panic(uint256)") << Instruction::EQ;
m_context << util::selectorFromSignature32("Panic(uint256)") << Instruction::EQ;
m_context << Instruction::ISZERO;
m_context.appendConditionalJumpTo(fallbackTag);

View File

@ -268,7 +268,7 @@ void ExpressionCompiler::appendStateVariableAccessor(VariableDeclaration const&
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_varDecl.location()) <<
errinfo_comment("Stack too deep.")
util::errinfo_comment("Stack too deep.")
);
m_context << dupInstruction(retSizeOnStack + 1);
m_context.appendJump(evmasm::AssemblyItem::JumpType::OutOfFunction);
@ -350,7 +350,7 @@ bool ExpressionCompiler::visit(Assignment const& _assignment)
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_assignment.location()) <<
errinfo_comment("Stack too deep, try removing local variables.")
util::errinfo_comment("Stack too deep, try removing local variables.")
);
// value [lvalue_ref] updated_value
for (unsigned i = 0; i < itemSize; ++i)
@ -1452,7 +1452,7 @@ bool ExpressionCompiler::visit(FunctionCallOptions const& _functionCallOptions)
solAssert(false, "Unexpected option name!");
acceptAndConvert(*_functionCallOptions.options()[i], *requiredType);
solAssert(!contains(presentOptions, newOption), "");
solAssert(!util::contains(presentOptions, newOption), "");
ptrdiff_t insertPos = presentOptions.end() - lower_bound(presentOptions.begin(), presentOptions.end(), newOption);
utils().moveIntoStack(static_cast<unsigned>(insertPos), 1);
@ -2862,7 +2862,7 @@ void ExpressionCompiler::setLValueFromDeclaration(Declaration const& _declaratio
else
BOOST_THROW_EXCEPTION(InternalCompilerError()
<< errinfo_sourceLocation(_expression.location())
<< errinfo_comment("Identifier type not supported or identifier not found."));
<< util::errinfo_comment("Identifier type not supported or identifier not found."));
}
void ExpressionCompiler::setLValueToStorageItem(Expression const& _expression)

View File

@ -50,7 +50,7 @@ void StackVariable::retrieveValue(SourceLocation const& _location, bool) const
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_location) <<
errinfo_comment("Stack too deep, try removing local variables.")
util::errinfo_comment("Stack too deep, try removing local variables.")
);
solAssert(stackPos + 1 >= m_size, "Size and stack pos mismatch.");
for (unsigned i = 0; i < m_size; ++i)
@ -64,7 +64,7 @@ void StackVariable::storeValue(Type const&, SourceLocation const& _location, boo
BOOST_THROW_EXCEPTION(
StackTooDeepError() <<
errinfo_sourceLocation(_location) <<
errinfo_comment("Stack too deep, try removing local variables.")
util::errinfo_comment("Stack too deep, try removing local variables.")
);
else if (stackDiff > 0)
for (unsigned i = 0; i < m_size; ++i)
@ -436,7 +436,7 @@ void StorageItem::storeValue(Type const& _sourceType, SourceLocation const& _loc
BOOST_THROW_EXCEPTION(
InternalCompilerError()
<< errinfo_sourceLocation(_location)
<< errinfo_comment("Invalid non-value type for assignment."));
<< util::errinfo_comment("Invalid non-value type for assignment."));
}
}

View File

@ -234,7 +234,7 @@ string IRGenerator::generate(
t("deployedFunctions", m_context.functionCollector().requestedFunctions());
t("deployedSubObjects", subObjectSources(m_context.subObjectsCreated()));
t("metadataName", yul::Object::metadataName());
t("cborMetadata", toHex(_cborMetadata));
t("cborMetadata", util::toHex(_cborMetadata));
t("useSrcMapDeployed", formatUseSrcMap(m_context));
@ -788,7 +788,7 @@ pair<string, map<ContractDefinition const*, vector<string>>> IRGenerator::evalua
{
bool operator()(ContractDefinition const* _c1, ContractDefinition const* _c2) const
{
solAssert(contains(linearizedBaseContracts, _c1) && contains(linearizedBaseContracts, _c2), "");
solAssert(util::contains(linearizedBaseContracts, _c1) && util::contains(linearizedBaseContracts, _c2), "");
auto it1 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c1);
auto it2 = find(linearizedBaseContracts.begin(), linearizedBaseContracts.end(), _c2);
return it1 < it2;

View File

@ -1498,7 +1498,7 @@ smtutil::Expression CHC::predicate(FunctionCall const& _funCall)
auto const* contract = function->annotation().contract;
auto const& hierarchy = m_currentContract->annotation().linearizedBaseContracts;
solAssert(kind != FunctionType::Kind::Internal || function->isFree() || (contract && contract->isLibrary()) || contains(hierarchy, contract), "");
solAssert(kind != FunctionType::Kind::Internal || function->isFree() || (contract && contract->isLibrary()) || util::contains(hierarchy, contract), "");
bool usesStaticCall = function->stateMutability() == StateMutability::Pure || function->stateMutability() == StateMutability::View;

View File

@ -48,7 +48,7 @@ map<Predicate const*, set<string>> collectInvariants(
map<string, pair<smtutil::Expression, smtutil::Expression>> equalities;
// Collect equalities where one of the sides is a predicate we're interested in.
BreadthFirstSearch<smtutil::Expression const*>{{&_proof}}.run([&](auto&& _expr, auto&& _addChild) {
util::BreadthFirstSearch<smtutil::Expression const*>{{&_proof}}.run([&](auto&& _expr, auto&& _addChild) {
if (_expr->name == "=")
for (auto const& t: targets)
{

View File

@ -350,7 +350,7 @@ vector<optional<string>> Predicate::summaryStateValues(vector<smtutil::Expressio
vector<smtutil::Expression> stateArgs(stateFirst, stateLast);
solAssert(stateArgs.size() == stateVars->size(), "");
auto stateTypes = applyMap(*stateVars, [&](auto const& _var) { return _var->type(); });
auto stateTypes = util::applyMap(*stateVars, [&](auto const& _var) { return _var->type(); });
return formatExpressions(stateArgs, stateTypes);
}
@ -412,7 +412,7 @@ pair<vector<optional<string>>, vector<VariableDeclaration const*>> Predicate::lo
auto first = _args.end() - static_cast<int>(localVars.size());
vector<smtutil::Expression> outValues(first, _args.end());
auto mask = applyMap(
auto mask = util::applyMap(
localVars,
[this](auto _var) {
auto varScope = dynamic_cast<ScopeOpener const*>(_var->scope());
@ -422,7 +422,7 @@ pair<vector<optional<string>>, vector<VariableDeclaration const*>> Predicate::lo
auto localVarsInScope = util::filter(localVars, mask);
auto outValuesInScope = util::filter(outValues, mask);
auto outTypes = applyMap(localVarsInScope, [](auto _var) { return _var->type(); });
auto outTypes = util::applyMap(localVarsInScope, [](auto _var) { return _var->type(); });
return {formatExpressions(outValuesInScope, outTypes), localVarsInScope};
}
@ -496,7 +496,7 @@ optional<string> Predicate::expressionToString(smtutil::Expression const& _expr,
if (_expr.name == "0")
return "0x0";
// For some reason the code below returns "0x" for "0".
return toHex(toCompactBigEndian(bigint(_expr.name)), HexPrefix::Add, HexCase::Lower);
return util::toHex(toCompactBigEndian(bigint(_expr.name)), util::HexPrefix::Add, util::HexCase::Lower);
}
catch (out_of_range const&)
{

View File

@ -313,7 +313,7 @@ bool SMTEncoder::visit(InlineAssembly const& _inlineAsm)
{
auto const& vars = _assignment.variableNames;
for (auto const& identifier: vars)
if (auto externalInfo = valueOrNullptr(externalReferences, &identifier))
if (auto externalInfo = util::valueOrNullptr(externalReferences, &identifier))
if (auto varDecl = dynamic_cast<VariableDeclaration const*>(externalInfo->declaration))
assignedVars.insert(varDecl);
}

View File

@ -211,7 +211,7 @@ void SymbolicState::buildABIFunctions(set<FunctionCall const*> const& _abiFuncti
auto argTypes = [](auto const& _args) {
return applyMap(_args, [](auto arg) { return arg->annotation().type; });
return util::applyMap(_args, [](auto arg) { return arg->annotation().type; });
};
/// Since each abi.* function may have a different number of input/output parameters,

View File

@ -580,7 +580,7 @@ optional<smtutil::Expression> symbolicTypeConversion(frontend::Type const* _from
return smtutil::Expression(size_t(0));
auto bytesVec = util::asBytes(strType->value());
bytesVec.resize(fixedBytesType->numBytes(), 0);
return smtutil::Expression(u256(toHex(bytesVec, util::HexPrefix::Add)));
return smtutil::Expression(u256(util::toHex(bytesVec, util::HexPrefix::Add)));
}
return std::nullopt;

View File

@ -278,7 +278,7 @@ void CompilerStack::setMetadataHash(MetadataHash _metadataHash)
void CompilerStack::selectDebugInfo(DebugInfoSelection _debugInfoSelection)
{
if (m_stackState >= CompilationSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Must select debug info components before compilation."));
BOOST_THROW_EXCEPTION(CompilerError() << util::errinfo_comment("Must select debug info components before compilation."));
m_debugInfoSelection = _debugInfoSelection;
}
@ -573,7 +573,7 @@ bool CompilerStack::analyze()
if (noErrors)
{
ModelChecker modelChecker(m_errorReporter, *this, m_smtlib2Responses, m_modelCheckerSettings, m_readFile);
auto allSources = applyMap(m_sourceOrder, [](Source const* _source) { return _source->ast; });
auto allSources = util::applyMap(m_sourceOrder, [](Source const* _source) { return _source->ast; });
modelChecker.enableAllEnginesIfPragmaPresent(allSources);
modelChecker.checkRequestedSourcesAndContracts(allSources);
for (Source const* source: m_sourceOrder)
@ -1030,7 +1030,7 @@ Json::Value CompilerStack::interfaceSymbols(string const& _contractName) const
for (ErrorDefinition const* error: contractDefinition(_contractName).interfaceErrors())
{
string signature = error->functionType(true)->externalSignature();
interfaceSymbols["errors"][signature] = toHex(toCompactBigEndian(selectorFromSignature32(signature), 4));
interfaceSymbols["errors"][signature] = util::toHex(toCompactBigEndian(util::selectorFromSignature32(signature), 4));
}
for (EventDefinition const* event: ranges::concat_view(
@ -1040,7 +1040,7 @@ Json::Value CompilerStack::interfaceSymbols(string const& _contractName) const
if (!event->isAnonymous())
{
string signature = event->functionType(true)->externalSignature();
interfaceSymbols["events"][signature] = toHex(u256(h256::Arith(keccak256(signature))));
interfaceSymbols["events"][signature] = toHex(u256(h256::Arith(util::keccak256(signature))));
}
return interfaceSymbols;
@ -1494,7 +1494,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con
continue;
solAssert(s.second.charStream, "Character stream not available");
meta["sources"][s.first]["keccak256"] = "0x" + toHex(s.second.keccak256().asBytes());
meta["sources"][s.first]["keccak256"] = "0x" + util::toHex(s.second.keccak256().asBytes());
if (optional<string> licenseString = s.second.ast->licenseString())
meta["sources"][s.first]["license"] = *licenseString;
if (m_metadataLiteralSources)
@ -1502,7 +1502,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con
else
{
meta["sources"][s.first]["urls"] = Json::arrayValue;
meta["sources"][s.first]["urls"].append("bzz-raw://" + toHex(s.second.swarmHash().asBytes()));
meta["sources"][s.first]["urls"].append("bzz-raw://" + util::toHex(s.second.swarmHash().asBytes()));
meta["sources"][s.first]["urls"].append(s.second.ipfsUrl());
}
}
@ -1565,7 +1565,7 @@ string CompilerStack::createMetadata(Contract const& _contract, bool _forIR) con
meta["settings"]["libraries"] = Json::objectValue;
for (auto const& library: m_libraries)
meta["settings"]["libraries"][library.first] = "0x" + toHex(library.second.asBytes());
meta["settings"]["libraries"][library.first] = "0x" + util::toHex(library.second.asBytes());
meta["output"]["abi"] = contractABI(_contract);
meta["output"]["userdoc"] = natspecUser(_contract);

View File

@ -253,7 +253,7 @@ bool LanguageServer::run()
string const methodName = (*jsonMessage)["method"].asString();
id = (*jsonMessage)["id"];
if (auto handler = valueOrDefault(m_handlers, methodName))
if (auto handler = util::valueOrDefault(m_handlers, methodName))
handler(id, (*jsonMessage)["params"]);
else
m_client.error(id, ErrorCode::MethodNotFound, "Unknown method " + methodName);
@ -375,7 +375,7 @@ void LanguageServer::handleTextDocumentDidChange(Json::Value const& _args)
lspAssert(
change && change->hasText(),
ErrorCode::RequestFailed,
"Invalid source range: " + jsonCompactPrint(jsonContentChange["range"])
"Invalid source range: " + util::jsonCompactPrint(jsonContentChange["range"])
);
string buffer = m_fileRepository.sourceUnits().at(sourceUnitName);

View File

@ -69,7 +69,7 @@ private:
{ \
BOOST_THROW_EXCEPTION( \
RequestError(errorCode) << \
errinfo_comment(errorMessage) \
util::errinfo_comment(errorMessage) \
); \
}

View File

@ -59,7 +59,7 @@ bytes encodeLinkData(bytes const& _data)
string base58Encode(bytes const& _data)
{
static string const alphabet{"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"};
bigint data(toHex(_data, HexPrefix::Add));
bigint data(util::toHex(_data, HexPrefix::Add));
string output;
while (data)
{

View File

@ -91,13 +91,13 @@ string Object::toString(
set<YulString> Object::qualifiedDataNames() const
{
set<YulString> qualifiedNames =
name.empty() || contains(name.str(), '.') ?
name.empty() || util::contains(name.str(), '.') ?
set<YulString>{} :
set<YulString>{name};
for (shared_ptr<ObjectNode> const& subObjectNode: subObjects)
{
yulAssert(qualifiedNames.count(subObjectNode->name) == 0, "");
if (contains(subObjectNode->name.str(), '.'))
if (util::contains(subObjectNode->name.str(), '.'))
continue;
qualifiedNames.insert(subObjectNode->name);
if (auto const* subObject = dynamic_cast<Object const*>(subObjectNode.get()))

View File

@ -367,7 +367,7 @@ void DataFlowAnalyzer::joinKnowledgeHelper(
// of m_memory and thus any overlapping write would have cleared the keys
// that are not known to be different inside m_memory already.
cxx20::erase_if(_this, mapTuple([&_older](auto&& key, auto&& currentValue){
YulString const* oldValue = valueOrNullptr(_older, key);
YulString const* oldValue = util::valueOrNullptr(_older, key);
return !oldValue || *oldValue != currentValue;
}));
}

View File

@ -54,13 +54,13 @@ void EqualStoreEliminator::visit(Statement& _statement)
{
if (auto vars = isSimpleStore(StoreLoadLocation::Storage, *expression))
{
if (auto const* currentValue = valueOrNullptr(m_storage, vars->first))
if (auto const* currentValue = util::valueOrNullptr(m_storage, vars->first))
if (*currentValue == vars->second)
m_pendingRemovals.insert(&_statement);
}
else if (auto vars = isSimpleStore(StoreLoadLocation::Memory, *expression))
{
if (auto const* currentValue = valueOrNullptr(m_memory, vars->first))
if (auto const* currentValue = util::valueOrNullptr(m_memory, vars->first))
if (*currentValue == vars->second)
m_pendingRemovals.insert(&_statement);
}

View File

@ -464,7 +464,7 @@ void CommandLineInterface::readInputFiles()
for (auto const& [sourceUnitName, normalizedInputPaths]: collisions)
{
message += sourceUnitName + " matches: ";
message += joinHumanReadable(normalizedInputPaths | ranges::views::transform(pathToQuotedString)) + "\n";
message += util::joinHumanReadable(normalizedInputPaths | ranges::views::transform(pathToQuotedString)) + "\n";
}
solThrow(CommandLineValidationError, message);
@ -963,7 +963,7 @@ void CommandLineInterface::link()
string foundPlaceholder(it, it + placeholderSize);
if (librariesReplacements.count(foundPlaceholder))
{
string hexStr(toHex(librariesReplacements.at(foundPlaceholder).asBytes()));
string hexStr(util::toHex(librariesReplacements.at(foundPlaceholder).asBytes()));
copy(hexStr.begin(), hexStr.end(), it);
}
else

View File

@ -166,7 +166,7 @@ ostream& operator<<(ostream& _out, CompilerOutputs const& _selection)
if (_selection.*component)
serializedSelection.push_back(CompilerOutputs::componentName(component));
return _out << joinHumanReadable(serializedSelection, ",");
return _out << util::joinHumanReadable(serializedSelection, ",");
}
string const& CompilerOutputs::componentName(bool CompilerOutputs::* _component)
@ -197,7 +197,7 @@ ostream& operator<<(ostream& _out, CombinedJsonRequests const& _requests)
if (_requests.*component)
serializedRequests.push_back(CombinedJsonRequests::componentName(component));
return _out << joinHumanReadable(serializedRequests, ",");
return _out << util::joinHumanReadable(serializedRequests, ",");
}
string const& CombinedJsonRequests::componentName(bool CombinedJsonRequests::* _component)
@ -343,17 +343,17 @@ void CommandLineParser::parseLibraryOption(string const& _input)
try
{
if (fs::is_regular_file(_input))
data = readFileAsString(_input);
data = util::readFileAsString(_input);
}
catch (fs::filesystem_error const&)
{
// Thrown e.g. if path is too long.
}
catch (FileNotFound const&)
catch (util::FileNotFound const&)
{
// Should not happen if `fs::is_regular_file` is correct.
}
catch (NotAFile const&)
catch (util::NotAFile const&)
{
// Should not happen if `fs::is_regular_file` is correct.
}
@ -418,15 +418,15 @@ void CommandLineParser::parseLibraryOption(string const& _input)
"Invalid length for address for library \"" + libName + "\": " +
to_string(addrString.length()) + " instead of 40 characters."
);
if (!passesAddressChecksum(addrString, false))
if (!util::passesAddressChecksum(addrString, false))
solThrow(
CommandLineValidationError,
"Invalid checksum on address for library \"" + libName + "\": " + addrString + "\n"
"The correct checksum is " + getChecksummedAddress(addrString)
"The correct checksum is " + util::getChecksummedAddress(addrString)
);
bytes binAddr = fromHex(addrString);
h160 address(binAddr, h160::AlignRight);
if (binAddr.size() > 20 || address == h160())
bytes binAddr = util::fromHex(addrString);
util::h160 address(binAddr, util::h160::AlignRight);
if (binAddr.size() > 20 || address == util::h160())
solThrow(
CommandLineValidationError,
"Invalid address for library \"" + libName + "\": " + addrString
@ -461,9 +461,9 @@ void CommandLineParser::parseOutputSelection()
solAssert(false);
case InputMode::Compiler:
case InputMode::CompilerWithASTImport:
return contains(compilerModeOutputs, _outputName);
return util::contains(compilerModeOutputs, _outputName);
case InputMode::Assembler:
return contains(assemblerModeOutputs, _outputName);
return util::contains(assemblerModeOutputs, _outputName);
case InputMode::StandardJson:
case InputMode::Linker:
return false;
@ -582,15 +582,15 @@ General Information)").c_str(),
)
(
g_strRevertStrings.c_str(),
po::value<string>()->value_name(joinHumanReadable(g_revertStringsArgs, ",")),
po::value<string>()->value_name(util::joinHumanReadable(g_revertStringsArgs, ",")),
"Strip revert (and require) reason strings or add additional debugging information."
)
(
g_strDebugInfo.c_str(),
po::value<string>()->default_value(toString(DebugInfoSelection::Default())),
po::value<string>()->default_value(util::toString(DebugInfoSelection::Default())),
("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 "
"following components: " + joinHumanReadable(DebugInfoSelection::componentMap() | ranges::views::keys) + ".").c_str()
"following components: " + util::joinHumanReadable(DebugInfoSelection::componentMap() | ranges::views::keys) + ".").c_str()
)
(
g_strStopAfter.c_str(),
@ -648,12 +648,12 @@ General Information)").c_str(),
assemblyModeOptions.add_options()
(
g_strMachine.c_str(),
po::value<string>()->value_name(joinHumanReadable(g_machineArgs, ",")),
po::value<string>()->value_name(util::joinHumanReadable(g_machineArgs, ",")),
"Target machine in assembly or Yul mode."
)
(
g_strYulDialect.c_str(),
po::value<string>()->value_name(joinHumanReadable(g_yulDialectArgs, ",")),
po::value<string>()->value_name(util::joinHumanReadable(g_yulDialectArgs, ",")),
"Input dialect to use in assembly or yul mode."
)
;
@ -726,7 +726,7 @@ General Information)").c_str(),
)
(
g_strCombinedJson.c_str(),
po::value<string>()->value_name(joinHumanReadable(CombinedJsonRequests::componentMap() | ranges::views::keys, ",")),
po::value<string>()->value_name(util::joinHumanReadable(CombinedJsonRequests::componentMap() | ranges::views::keys, ",")),
"Output a single json document containing the specified information."
)
;
@ -736,7 +736,7 @@ General Information)").c_str(),
metadataOptions.add_options()
(
g_strMetadataHash.c_str(),
po::value<string>()->value_name(joinHumanReadable(g_metadataHashArgs, ",")),
po::value<string>()->value_name(util::joinHumanReadable(g_metadataHashArgs, ",")),
"Choose hash method for the bytecode metadata or disable it."
)
(
@ -1011,11 +1011,11 @@ void CommandLineParser::processArgs()
if (m_args.count(g_strPrettyJson) > 0)
{
m_options.formatting.json.format = JsonFormat::Pretty;
m_options.formatting.json.format = util::JsonFormat::Pretty;
}
if (!m_args[g_strJsonIndent].defaulted())
{
m_options.formatting.json.format = JsonFormat::Pretty;
m_options.formatting.json.format = util::JsonFormat::Pretty;
m_options.formatting.json.indent = m_args[g_strJsonIndent].as<uint32_t>();
}
@ -1289,7 +1289,7 @@ size_t CommandLineParser::countEnabledOptions(vector<string> const& _optionNames
string CommandLineParser::joinOptionNames(vector<string> const& _optionNames, string _separator)
{
return joinHumanReadable(
return util::joinHumanReadable(
_optionNames | ranges::views::transform([](string const& _option){ return "--" + _option; }),
_separator
);

View File

@ -42,11 +42,10 @@ namespace
int parseUnsignedInteger(string::iterator& _it, string::iterator _end)
{
auto isDigit = [](char _c) -> bool {return isdigit(_c, std::locale::classic());};
if (_it == _end || !isDigit(*_it))
if (_it == _end || !util::isDigit(*_it))
BOOST_THROW_EXCEPTION(runtime_error("Invalid test expectation. Source location expected."));
int result = 0;
while (_it != _end && isDigit(*_it))
while (_it != _end && util::isDigit(*_it))
{
result *= 10;
result += *_it - '0';
@ -84,9 +83,9 @@ TestCase::TestResult CommonSyntaxTest::conclude(ostream& _stream, string const&
void CommonSyntaxTest::printExpectationAndError(ostream& _stream, string const& _linePrefix, bool _formatted)
{
string nextIndentLevel = _linePrefix + " ";
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Expected result:" << endl;
util::AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Expected result:" << endl;
printErrorList(_stream, m_expectations, nextIndentLevel, _formatted);
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Obtained result:" << endl;
util::AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Obtained result:" << endl;
printErrorList(_stream, m_errorList, nextIndentLevel, _formatted);
}
@ -105,8 +104,8 @@ void CommonSyntaxTest::printSource(ostream& _stream, string const& _linePrefix,
continue;
if (outputSourceNames)
_stream << _linePrefix << formatting::CYAN << "==== Source: " << name << " ====" << formatting::RESET << endl;
vector<char const*> sourceFormatting(source.length(), formatting::RESET);
_stream << _linePrefix << util::formatting::CYAN << "==== Source: " << name << " ====" << util::formatting::RESET << endl;
vector<char const*> sourceFormatting(source.length(), util::formatting::RESET);
for (auto const& error: m_errorList)
if (error.sourceName == name && error.locationStart >= 0 && error.locationEnd >= 0)
{
@ -116,11 +115,11 @@ void CommonSyntaxTest::printSource(ostream& _stream, string const& _linePrefix,
for (int i = error.locationStart; i < error.locationEnd; i++)
if (isWarning)
{
if (sourceFormatting[static_cast<size_t>(i)] == formatting::RESET)
sourceFormatting[static_cast<size_t>(i)] = formatting::ORANGE_BACKGROUND_256;
if (sourceFormatting[static_cast<size_t>(i)] == util::formatting::RESET)
sourceFormatting[static_cast<size_t>(i)] = util::formatting::ORANGE_BACKGROUND_256;
}
else
sourceFormatting[static_cast<size_t>(i)] = formatting::RED_BACKGROUND;
sourceFormatting[static_cast<size_t>(i)] = util::formatting::RED_BACKGROUND;
}
_stream << _linePrefix << sourceFormatting.front() << source.front();
@ -132,12 +131,12 @@ void CommonSyntaxTest::printSource(ostream& _stream, string const& _linePrefix,
_stream << source[i];
else
{
_stream << formatting::RESET << endl;
_stream << util::formatting::RESET << endl;
if (i + 1 < source.length())
_stream << _linePrefix << sourceFormatting[i];
}
}
_stream << formatting::RESET;
_stream << util::formatting::RESET;
}
else
{
@ -158,12 +157,12 @@ void CommonSyntaxTest::printErrorList(
)
{
if (_errorList.empty())
AnsiColorized(_stream, _formatted, {BOLD, GREEN}) << _linePrefix << "Success" << endl;
util::AnsiColorized(_stream, _formatted, {BOLD, GREEN}) << _linePrefix << "Success" << endl;
else
for (auto const& error: _errorList)
{
{
AnsiColorized scope(_stream, _formatted, {BOLD, (error.type == "Warning") ? YELLOW : RED});
util::AnsiColorized scope(_stream, _formatted, {BOLD, (error.type == "Warning") ? YELLOW : RED});
_stream << _linePrefix << error.type;
if (error.errorId.has_value())
_stream << ' ' << error.errorId->error;
@ -185,7 +184,7 @@ void CommonSyntaxTest::printErrorList(
}
}
string CommonSyntaxTest::errorMessage(Exception const& _e)
string CommonSyntaxTest::errorMessage(util::Exception const& _e)
{
if (_e.comment() && !_e.comment()->empty())
return boost::replace_all_copy(*_e.comment(), "\n", "\\n");
@ -195,7 +194,6 @@ string CommonSyntaxTest::errorMessage(Exception const& _e)
vector<SyntaxTestError> CommonSyntaxTest::parseExpectations(istream& _stream)
{
auto isDigit = [](char _c) -> bool {return isdigit(_c, std::locale::classic());};
vector<SyntaxTestError> expectations;
string line;
while (getline(_stream, line))
@ -215,7 +213,7 @@ vector<SyntaxTestError> CommonSyntaxTest::parseExpectations(istream& _stream)
skipWhitespace(it, line.end());
optional<ErrorId> errorId;
if (it != line.end() && isDigit(*it))
if (it != line.end() && util::isDigit(*it))
errorId = ErrorId{static_cast<unsigned long long>(parseUnsignedInteger(it, line.end()))};
expect(it, line.end(), ':');
@ -228,7 +226,7 @@ vector<SyntaxTestError> CommonSyntaxTest::parseExpectations(istream& _stream)
if (it != line.end() && *it == '(')
{
++it;
if (it != line.end() && !isDigit(*it))
if (it != line.end() && !util::isDigit(*it))
{
auto sourceNameStart = it;
while (it != line.end() && *it != ':')

View File

@ -70,10 +70,10 @@ SemanticTest::SemanticTest(
static set<string> const legacyRunTriggers{"also", "false", "default"};
string compileViaYul = m_reader.stringSetting("compileViaYul", "default");
if (!contains(compileViaYulAllowedValues, compileViaYul))
if (!util::contains(compileViaYulAllowedValues, compileViaYul))
BOOST_THROW_EXCEPTION(runtime_error("Invalid compileViaYul value: " + compileViaYul + "."));
m_testCaseWantsYulRun = contains(yulRunTriggers, compileViaYul);
m_testCaseWantsLegacyRun = contains(legacyRunTriggers, compileViaYul);
m_testCaseWantsYulRun = util::contains(yulRunTriggers, compileViaYul);
m_testCaseWantsLegacyRun = util::contains(legacyRunTriggers, compileViaYul);
// Do not enforce via yul and ewasm, if via yul was explicitly denied.
if (compileViaYul == "false")
@ -189,7 +189,7 @@ vector<SideEffectHook> SemanticTest::makeSideEffectHooks() const
{
vector<string> result;
for (auto const& argument: _call.arguments.parameters)
result.emplace_back(toHex(argument.rawBytes));
result.emplace_back(util::toHex(argument.rawBytes));
return result;
}
return {};

View File

@ -4102,12 +4102,12 @@ BOOST_AUTO_TEST_CASE(strip_reason_strings)
m_optimiserSettings == OptimiserSettings::none()
)
// check that the reason string IS part of the binary.
BOOST_CHECK(toHex(m_output).find("736f6d6520726561736f6e") != std::string::npos);
BOOST_CHECK(util::toHex(m_output).find("736f6d6520726561736f6e") != std::string::npos);
m_revertStrings = RevertStrings::Strip;
compileAndRun(sourceCode, 0, "C");
// check that the reason string is NOT part of the binary.
BOOST_CHECK(toHex(m_output).find("736f6d6520726561736f6e") == std::string::npos);
BOOST_CHECK(util::toHex(m_output).find("736f6d6520726561736f6e") == std::string::npos);
ABI_CHECK(callContractFunction("f(bool)", true), encodeArgs(7));
ABI_CHECK(callContractFunction("f(bool)", false), encodeArgs());

View File

@ -350,7 +350,7 @@ BOOST_AUTO_TEST_CASE(arithmetic)
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::PUSH32)
} +
fromHex("4E487B7100000000000000000000000000000000000000000000000000000000") +
util::fromHex("4E487B7100000000000000000000000000000000000000000000000000000000") +
bytes{
uint8_t(Instruction::PUSH1), 0x0,
uint8_t(Instruction::MSTORE),

View File

@ -98,8 +98,8 @@ public:
BOOST_CHECK_MESSAGE(!optimizedOutput.empty(), "No optimized output for " + _sig);
BOOST_CHECK_MESSAGE(!nonOptimizedOutput.empty(), "No un-optimized output for " + _sig);
BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match."
"\nNon-Optimized: " + toHex(nonOptimizedOutput) +
"\nOptimized: " + toHex(optimizedOutput));
"\nNon-Optimized: " + util::toHex(nonOptimizedOutput) +
"\nOptimized: " + util::toHex(optimizedOutput));
}
/// @returns the number of instructions in the given bytecode, not taking the metadata hash

View File

@ -47,6 +47,7 @@
#include <vector>
using namespace std;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;

View File

@ -220,7 +220,7 @@ string BytesUtils::formatString(bytes const& _bytes, size_t _cutOff)
if (isPrint(static_cast<char>(v)))
os << v;
else
os << "\\x" << toHex(v, HexCase::Lower);
os << "\\x" << util::toHex(v, HexCase::Lower);
}
}
os << "\"";

View File

@ -16,6 +16,9 @@
*/
// SPDX-License-Identifier: GPL-3.0
#include <libsolutil/StringUtils.h>
#include <test/libsolidity/util/TestFileParser.h>
#include <test/libsolidity/util/BytesUtils.h>
@ -34,6 +37,7 @@
#include <stdexcept>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace std;
@ -763,7 +767,6 @@ string TestFileParser::Scanner::scanString()
char TestFileParser::Scanner::scanHexPart()
{
auto toLower = [](char _c) -> char { return tolower(_c, locale::classic()); };
auto isDigit = [](char _c) -> bool { return isdigit(_c, locale::classic()); };
advance(); // skip 'x'

View File

@ -324,7 +324,7 @@ string TestFunctionCall::formatRawParameters(
for (auto const c: param.rawString)
// NOTE: Even though we have a toHex() overload specifically for uint8_t, the compiler
// chooses the one for bytes if the second argument is omitted.
os << (c >= ' ' ? string(1, c) : "\\x" + toHex(static_cast<uint8_t>(c), HexCase::Lower));
os << (c >= ' ' ? string(1, c) : "\\x" + util::toHex(static_cast<uint8_t>(c), HexCase::Lower));
if (&param != &_params.back())
os << ", ";
}

View File

@ -43,6 +43,7 @@
using namespace std;
using namespace solidity::frontend;
using namespace solidity::test;
using namespace solidity::util;
using PathSet = set<boost::filesystem::path>;