From 519e1c9402f83e26bf93186a3facc440dd1b770c Mon Sep 17 00:00:00 2001 From: Tyler Date: Sun, 6 Mar 2022 23:25:35 -0500 Subject: [PATCH] Specify namespaces Fix references into solidity::util --- libsolidity/analysis/ControlFlowAnalyzer.cpp | 2 +- .../analysis/ControlFlowRevertPruner.cpp | 2 +- libsolidity/analysis/FunctionCallGraph.cpp | 2 +- libsolidity/analysis/PostTypeChecker.cpp | 4 +- .../analysis/PostTypeContractLevelChecker.cpp | 2 +- libsolidity/analysis/TypeChecker.cpp | 4 +- libsolidity/ast/AST.cpp | 4 +- libsolidity/ast/ASTJsonConverter.cpp | 2 +- libsolidity/codegen/CompilerContext.cpp | 2 +- libsolidity/codegen/ContractCompiler.cpp | 12 ++--- libsolidity/codegen/ExpressionCompiler.cpp | 8 ++-- libsolidity/codegen/LValue.cpp | 6 +-- libsolidity/codegen/ir/IRGenerator.cpp | 4 +- libsolidity/formal/CHC.cpp | 2 +- libsolidity/formal/Invariants.cpp | 2 +- libsolidity/formal/Predicate.cpp | 8 ++-- libsolidity/formal/SMTEncoder.cpp | 2 +- libsolidity/formal/SymbolicState.cpp | 2 +- libsolidity/formal/SymbolicTypes.cpp | 2 +- libsolidity/interface/CompilerStack.cpp | 14 +++--- libsolidity/lsp/LanguageServer.cpp | 4 +- libsolidity/lsp/Transport.h | 2 +- libsolutil/IpfsHash.cpp | 2 +- libyul/Object.cpp | 4 +- libyul/optimiser/DataFlowAnalyzer.cpp | 2 +- libyul/optimiser/EqualStoreEliminator.cpp | 4 +- solc/CommandLineInterface.cpp | 4 +- solc/CommandLineParser.cpp | 44 +++++++++---------- test/libsolidity/SemanticTest.cpp | 8 ++-- test/libsolidity/SolidityEndToEndTest.cpp | 4 +- .../SolidityExpressionCompiler.cpp | 2 +- test/libsolidity/SolidityOptimizer.cpp | 4 +- .../analysis/FunctionCallGraph.cpp | 1 + test/libsolidity/util/BytesUtils.cpp | 2 +- test/libsolidity/util/TestFunctionCall.cpp | 2 +- test/solc/CommandLineInterface.cpp | 1 + 36 files changed, 89 insertions(+), 87 deletions(-) diff --git a/libsolidity/analysis/ControlFlowAnalyzer.cpp b/libsolidity/analysis/ControlFlowAnalyzer.cpp index 0c64ac3b5b61..e80964acebab 100644 --- a/libsolidity/analysis/ControlFlowAnalyzer.cpp +++ b/libsolidity/analysis/ControlFlowAnalyzer.cpp @@ -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); diff --git a/libsolidity/analysis/ControlFlowRevertPruner.cpp b/libsolidity/analysis/ControlFlowRevertPruner.cpp index 9a44be57af97..ae9c18a13a9e 100644 --- a/libsolidity/analysis/ControlFlowRevertPruner.cpp +++ b/libsolidity/analysis/ControlFlowRevertPruner.cpp @@ -57,7 +57,7 @@ void ControlFlowRevertPruner::run() void ControlFlowRevertPruner::findRevertStates() { - std::set pendingFunctions = keys(m_functions); + std::set 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. diff --git a/libsolidity/analysis/FunctionCallGraph.cpp b/libsolidity/analysis/FunctionCallGraph.cpp index 26523712844f..45da1b4f0d45 100644 --- a/libsolidity/analysis/FunctionCallGraph.cpp +++ b/libsolidity/analysis/FunctionCallGraph.cpp @@ -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 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(dispatchTarget), ""); solAssert(get(dispatchTarget) != nullptr, ""); diff --git a/libsolidity/analysis/PostTypeChecker.cpp b/libsolidity/analysis/PostTypeChecker.cpp index d08ee78b711d..b5b973aa4c15 100644 --- a/libsolidity/analysis/PostTypeChecker.cpp +++ b/libsolidity/analysis/PostTypeChecker.cpp @@ -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." ); } } diff --git a/libsolidity/analysis/PostTypeContractLevelChecker.cpp b/libsolidity/analysis/PostTypeContractLevelChecker.cpp index 32927188fcaa..38a192c22638 100644 --- a/libsolidity/analysis/PostTypeContractLevelChecker.cpp +++ b/libsolidity/analysis/PostTypeContractLevelChecker.cpp @@ -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)) { diff --git a/libsolidity/analysis/TypeChecker.cpp b/libsolidity/analysis/TypeChecker.cpp index 74701bde0f82..00b68b896703 100644 --- a/libsolidity/analysis/TypeChecker.cpp +++ b/libsolidity/analysis/TypeChecker.cpp @@ -659,7 +659,7 @@ void TypeChecker::visitManually( if (auto const* modifierContract = dynamic_cast(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(), @@ -2137,7 +2137,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) diff --git a/libsolidity/ast/AST.cpp b/libsolidity/ast/AST.cpp index 2a7609de858f..be6f2fe9be66 100644 --- a/libsolidity/ast/AST.cpp +++ b/libsolidity/ast/AST.cpp @@ -221,7 +221,7 @@ vector const ContractDefinition::usedInterfaceEvents() c { solAssert(annotation().creationCallGraph.set(), ""); - return convertContainer>( + return util::convertContainer>( (*annotation().creationCallGraph)->emittedEvents + (*annotation().deployedCallGraph)->emittedEvents ); @@ -239,7 +239,7 @@ vector ContractDefinition::interfaceErrors(bool _require result += (*annotation().creationCallGraph)->usedErrors + (*annotation().deployedCallGraph)->usedErrors; - return convertContainer>(move(result)); + return util::convertContainer>(move(result)); } vector, FunctionTypePointer>> const& ContractDefinition::interfaceFunctionList(bool _includeInheritedFunctions) const diff --git a/libsolidity/ast/ASTJsonConverter.cpp b/libsolidity/ast/ASTJsonConverter.cpp index 97417f81c0b5..06807e9dfa81 100644 --- a/libsolidity/ast/ASTJsonConverter.cpp +++ b/libsolidity/ast/ASTJsonConverter.cpp @@ -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)); diff --git a/libsolidity/codegen/CompilerContext.cpp b/libsolidity/codegen/CompilerContext.cpp index 700f53d1f7d8..9bc035806b17 100644 --- a/libsolidity/codegen/CompilerContext.cpp +++ b/libsolidity/codegen/CompilerContext.cpp @@ -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, diff --git a/libsolidity/codegen/ContractCompiler.cpp b/libsolidity/codegen/ContractCompiler.cpp index 5abc646367ae..d2c71e2aff35 100644 --- a/libsolidity/codegen/ContractCompiler.cpp +++ b/libsolidity/codegen/ContractCompiler.cpp @@ -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(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> const& _ca solAssert(m_context.evmVersion().supportsReturndata(), ""); // stack: - 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> const& _ca solAssert(m_context.evmVersion().supportsReturndata(), ""); // stack: - m_context << selectorFromSignature32("Panic(uint256)") << Instruction::EQ; + m_context << util::selectorFromSignature32("Panic(uint256)") << Instruction::EQ; m_context << Instruction::ISZERO; m_context.appendConditionalJumpTo(fallbackTag); diff --git a/libsolidity/codegen/ExpressionCompiler.cpp b/libsolidity/codegen/ExpressionCompiler.cpp index e4ad4cf7e04b..1eefe41b99e0 100644 --- a/libsolidity/codegen/ExpressionCompiler.cpp +++ b/libsolidity/codegen/ExpressionCompiler.cpp @@ -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(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) diff --git a/libsolidity/codegen/LValue.cpp b/libsolidity/codegen/LValue.cpp index bd9252953771..379e9818b661 100644 --- a/libsolidity/codegen/LValue.cpp +++ b/libsolidity/codegen/LValue.cpp @@ -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.")); } } diff --git a/libsolidity/codegen/ir/IRGenerator.cpp b/libsolidity/codegen/ir/IRGenerator.cpp index 6b52010d99b8..84ccef94e491 100644 --- a/libsolidity/codegen/ir/IRGenerator.cpp +++ b/libsolidity/codegen/ir/IRGenerator.cpp @@ -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>> 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; diff --git a/libsolidity/formal/CHC.cpp b/libsolidity/formal/CHC.cpp index 9e31d7fc9c3e..8f7bc5dbcbb4 100644 --- a/libsolidity/formal/CHC.cpp +++ b/libsolidity/formal/CHC.cpp @@ -1497,7 +1497,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; diff --git a/libsolidity/formal/Invariants.cpp b/libsolidity/formal/Invariants.cpp index 9dad0722cd48..10d342ed474a 100644 --- a/libsolidity/formal/Invariants.cpp +++ b/libsolidity/formal/Invariants.cpp @@ -48,7 +48,7 @@ map> collectInvariants( map> equalities; // Collect equalities where one of the sides is a predicate we're interested in. - BreadthFirstSearch{{&_proof}}.run([&](auto&& _expr, auto&& _addChild) { + util::BreadthFirstSearch{{&_proof}}.run([&](auto&& _expr, auto&& _addChild) { if (_expr->name == "=") for (auto const& t: targets) { diff --git a/libsolidity/formal/Predicate.cpp b/libsolidity/formal/Predicate.cpp index 6e0eb4f3b9d1..91513a00c089 100644 --- a/libsolidity/formal/Predicate.cpp +++ b/libsolidity/formal/Predicate.cpp @@ -350,7 +350,7 @@ vector> Predicate::summaryStateValues(vector 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> Predicate::lo auto first = _args.end() - static_cast(localVars.size()); vector outValues(first, _args.end()); - auto mask = applyMap( + auto mask = util::applyMap( localVars, [this](auto _var) { auto varScope = dynamic_cast(_var->scope()); @@ -422,7 +422,7 @@ pair>, vector> 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 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&) { diff --git a/libsolidity/formal/SMTEncoder.cpp b/libsolidity/formal/SMTEncoder.cpp index 76342ba08eb5..e699e28b8dd8 100644 --- a/libsolidity/formal/SMTEncoder.cpp +++ b/libsolidity/formal/SMTEncoder.cpp @@ -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(externalInfo->declaration)) assignedVars.insert(varDecl); } diff --git a/libsolidity/formal/SymbolicState.cpp b/libsolidity/formal/SymbolicState.cpp index 6612723d065f..b1fd7978fa38 100644 --- a/libsolidity/formal/SymbolicState.cpp +++ b/libsolidity/formal/SymbolicState.cpp @@ -211,7 +211,7 @@ void SymbolicState::buildABIFunctions(set 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, diff --git a/libsolidity/formal/SymbolicTypes.cpp b/libsolidity/formal/SymbolicTypes.cpp index b9041c6bd4cb..e40ff924511f 100644 --- a/libsolidity/formal/SymbolicTypes.cpp +++ b/libsolidity/formal/SymbolicTypes.cpp @@ -580,7 +580,7 @@ optional 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; diff --git a/libsolidity/interface/CompilerStack.cpp b/libsolidity/interface/CompilerStack.cpp index 7a8bc4ddbf91..3eb25987db42 100644 --- a/libsolidity/interface/CompilerStack.cpp +++ b/libsolidity/interface/CompilerStack.cpp @@ -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 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); diff --git a/libsolidity/lsp/LanguageServer.cpp b/libsolidity/lsp/LanguageServer.cpp index fb704d819274..bda55b26df9e 100644 --- a/libsolidity/lsp/LanguageServer.cpp +++ b/libsolidity/lsp/LanguageServer.cpp @@ -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); diff --git a/libsolidity/lsp/Transport.h b/libsolidity/lsp/Transport.h index 2d0b49517adf..82fe43909979 100644 --- a/libsolidity/lsp/Transport.h +++ b/libsolidity/lsp/Transport.h @@ -69,7 +69,7 @@ class RequestError: public util::Exception { \ BOOST_THROW_EXCEPTION( \ RequestError(errorCode) << \ - errinfo_comment(errorMessage) \ + util::errinfo_comment(errorMessage) \ ); \ } diff --git a/libsolutil/IpfsHash.cpp b/libsolutil/IpfsHash.cpp index a34ee035bd64..dbf411dc783d 100644 --- a/libsolutil/IpfsHash.cpp +++ b/libsolutil/IpfsHash.cpp @@ -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) { diff --git a/libyul/Object.cpp b/libyul/Object.cpp index ed456ab53d2f..cf68ff765fd1 100644 --- a/libyul/Object.cpp +++ b/libyul/Object.cpp @@ -91,13 +91,13 @@ string Object::toString( set Object::qualifiedDataNames() const { set qualifiedNames = - name.empty() || contains(name.str(), '.') ? + name.empty() || util::contains(name.str(), '.') ? set{} : set{name}; for (shared_ptr 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(subObjectNode.get())) diff --git a/libyul/optimiser/DataFlowAnalyzer.cpp b/libyul/optimiser/DataFlowAnalyzer.cpp index af25cde59214..c1ad2116af04 100644 --- a/libyul/optimiser/DataFlowAnalyzer.cpp +++ b/libyul/optimiser/DataFlowAnalyzer.cpp @@ -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; })); } diff --git a/libyul/optimiser/EqualStoreEliminator.cpp b/libyul/optimiser/EqualStoreEliminator.cpp index dcba98ce4f53..56f9902f891c 100644 --- a/libyul/optimiser/EqualStoreEliminator.cpp +++ b/libyul/optimiser/EqualStoreEliminator.cpp @@ -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); } diff --git a/solc/CommandLineInterface.cpp b/solc/CommandLineInterface.cpp index 24e4ee7dd8a3..03679bd7c57d 100644 --- a/solc/CommandLineInterface.cpp +++ b/solc/CommandLineInterface.cpp @@ -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 diff --git a/solc/CommandLineParser.cpp b/solc/CommandLineParser.cpp index 65c7d7862152..8f6d549f202c 100644 --- a/solc/CommandLineParser.cpp +++ b/solc/CommandLineParser.cpp @@ -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()->value_name(joinHumanReadable(g_revertStringsArgs, ",")), + po::value()->value_name(util::joinHumanReadable(g_revertStringsArgs, ",")), "Strip revert (and require) reason strings or add additional debugging information." ) ( g_strDebugInfo.c_str(), - po::value()->default_value(toString(DebugInfoSelection::Default())), + po::value()->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()->value_name(joinHumanReadable(g_machineArgs, ",")), + po::value()->value_name(util::joinHumanReadable(g_machineArgs, ",")), "Target machine in assembly or Yul mode." ) ( g_strYulDialect.c_str(), - po::value()->value_name(joinHumanReadable(g_yulDialectArgs, ",")), + po::value()->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()->value_name(joinHumanReadable(CombinedJsonRequests::componentMap() | ranges::views::keys, ",")), + po::value()->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()->value_name(joinHumanReadable(g_metadataHashArgs, ",")), + po::value()->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(); } @@ -1289,7 +1289,7 @@ size_t CommandLineParser::countEnabledOptions(vector const& _optionNames string CommandLineParser::joinOptionNames(vector const& _optionNames, string _separator) { - return joinHumanReadable( + return util::joinHumanReadable( _optionNames | ranges::views::transform([](string const& _option){ return "--" + _option; }), _separator ); diff --git a/test/libsolidity/SemanticTest.cpp b/test/libsolidity/SemanticTest.cpp index 1f07f177d477..3c26f5a97e64 100644 --- a/test/libsolidity/SemanticTest.cpp +++ b/test/libsolidity/SemanticTest.cpp @@ -70,10 +70,10 @@ SemanticTest::SemanticTest( static set 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 SemanticTest::makeSideEffectHooks() const { vector result; for (auto const& argument: _call.arguments.parameters) - result.emplace_back(toHex(argument.rawBytes)); + result.emplace_back(util::toHex(argument.rawBytes)); return result; } return {}; diff --git a/test/libsolidity/SolidityEndToEndTest.cpp b/test/libsolidity/SolidityEndToEndTest.cpp index 314d4283e0de..42c455f4c392 100644 --- a/test/libsolidity/SolidityEndToEndTest.cpp +++ b/test/libsolidity/SolidityEndToEndTest.cpp @@ -4074,12 +4074,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()); diff --git a/test/libsolidity/SolidityExpressionCompiler.cpp b/test/libsolidity/SolidityExpressionCompiler.cpp index 5f7b8d4724ef..4fef140e8f89 100644 --- a/test/libsolidity/SolidityExpressionCompiler.cpp +++ b/test/libsolidity/SolidityExpressionCompiler.cpp @@ -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), diff --git a/test/libsolidity/SolidityOptimizer.cpp b/test/libsolidity/SolidityOptimizer.cpp index eb4102b1502d..a1580fb539be 100644 --- a/test/libsolidity/SolidityOptimizer.cpp +++ b/test/libsolidity/SolidityOptimizer.cpp @@ -98,8 +98,8 @@ class OptimizerTestFramework: public SolidityExecutionFramework 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 diff --git a/test/libsolidity/analysis/FunctionCallGraph.cpp b/test/libsolidity/analysis/FunctionCallGraph.cpp index 30477aa2e43c..7b67aeb44eec 100644 --- a/test/libsolidity/analysis/FunctionCallGraph.cpp +++ b/test/libsolidity/analysis/FunctionCallGraph.cpp @@ -47,6 +47,7 @@ #include using namespace std; +using namespace solidity::util; using namespace solidity::langutil; using namespace solidity::frontend; diff --git a/test/libsolidity/util/BytesUtils.cpp b/test/libsolidity/util/BytesUtils.cpp index f74b256d0c61..3c711f022514 100644 --- a/test/libsolidity/util/BytesUtils.cpp +++ b/test/libsolidity/util/BytesUtils.cpp @@ -219,7 +219,7 @@ string BytesUtils::formatString(bytes const& _bytes, size_t _cutOff) if (isprint(v)) os << v; else - os << "\\x" << toHex(v, HexCase::Lower); + os << "\\x" << util::toHex(v, HexCase::Lower); } } os << "\""; diff --git a/test/libsolidity/util/TestFunctionCall.cpp b/test/libsolidity/util/TestFunctionCall.cpp index 43805c8f9934..c51dbec97123 100644 --- a/test/libsolidity/util/TestFunctionCall.cpp +++ b/test/libsolidity/util/TestFunctionCall.cpp @@ -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(c), HexCase::Lower)); + os << (c >= ' ' ? string(1, c) : "\\x" + util::toHex(static_cast(c), HexCase::Lower)); if (¶m != &_params.back()) os << ", "; } diff --git a/test/solc/CommandLineInterface.cpp b/test/solc/CommandLineInterface.cpp index 169437f3c490..d5cb39a83e06 100644 --- a/test/solc/CommandLineInterface.cpp +++ b/test/solc/CommandLineInterface.cpp @@ -43,6 +43,7 @@ using namespace std; using namespace solidity::frontend; using namespace solidity::test; +using namespace solidity::util; using PathSet = set;