From f344dc164e9d720f604ac5b345df1243587d6942 Mon Sep 17 00:00:00 2001 From: Nikola Matic Date: Tue, 15 Aug 2023 16:21:33 +0200 Subject: [PATCH] Purge using namespace from libsolidity/lsp and parsing --- libsolidity/interface/CompilerStack.cpp | 2 +- libsolidity/interface/StandardCompiler.cpp | 2 +- libsolidity/lsp/DocumentHoverHandler.cpp | 9 +- libsolidity/lsp/FileRepository.cpp | 21 ++- libsolidity/lsp/GotoDefinition.cpp | 5 +- libsolidity/lsp/HandlerBase.cpp | 7 +- libsolidity/lsp/LanguageServer.cpp | 75 +++++---- libsolidity/lsp/RenameSymbol.cpp | 17 +- libsolidity/lsp/SemanticTokensBuilder.cpp | 5 +- libsolidity/lsp/Transport.cpp | 33 ++-- libsolidity/lsp/Utils.cpp | 43 +++--- libsolidity/parsing/DocStringParser.cpp | 37 +++-- libsolidity/parsing/Parser.cpp | 172 ++++++++++----------- scripts/check_style.sh | 2 + 14 files changed, 210 insertions(+), 220 deletions(-) diff --git a/libsolidity/interface/CompilerStack.cpp b/libsolidity/interface/CompilerStack.cpp index 295811fd0678..234ae5d009e3 100644 --- a/libsolidity/interface/CompilerStack.cpp +++ b/libsolidity/interface/CompilerStack.cpp @@ -1859,7 +1859,7 @@ Json::Value CompilerStack::gasEstimates(std::string const& _contractName) const if (contract.fallbackFunction()) /// This needs to be set to an invalid signature in order to trigger the fallback, /// without the shortcut (of CALLDATSIZE == 0), and therefore to receive the upper bound. - /// An empty std::string ("") would work to trigger the shortcut only. + /// An empty string ("") would work to trigger the shortcut only. externalFunctions[""] = gasToJson(gasEstimator.functionalEstimation(*items, "INVALID")); if (!externalFunctions.empty()) diff --git a/libsolidity/interface/StandardCompiler.cpp b/libsolidity/interface/StandardCompiler.cpp index e90d25e21caf..20cec68ae04b 100644 --- a/libsolidity/interface/StandardCompiler.cpp +++ b/libsolidity/interface/StandardCompiler.cpp @@ -323,7 +323,7 @@ Json::Value formatLinkReferences(std::map const& linkRefere std::string const& fullname = ref.second; // If the link reference does not contain a colon, assume that the file name is missing and - // the whole std::string represents the library name. + // the whole string represents the library name. size_t colon = fullname.rfind(':'); std::string file = (colon != std::string::npos ? fullname.substr(0, colon) : ""); std::string name = (colon != std::string::npos ? fullname.substr(colon + 1) : fullname); diff --git a/libsolidity/lsp/DocumentHoverHandler.cpp b/libsolidity/lsp/DocumentHoverHandler.cpp index 77000222892c..39d1d72c331c 100644 --- a/libsolidity/lsp/DocumentHoverHandler.cpp +++ b/libsolidity/lsp/DocumentHoverHandler.cpp @@ -23,9 +23,6 @@ namespace solidity::lsp { - -using namespace std; - using namespace solidity::lsp; using namespace solidity::langutil; using namespace solidity::frontend; @@ -35,16 +32,16 @@ namespace struct MarkdownBuilder { - stringstream result; + std::stringstream result; - MarkdownBuilder& solidityCode(string const& _code) + MarkdownBuilder& solidityCode(std::string const& _code) { auto constexpr SolidityLanguageId = "solidity"; result << "```" << SolidityLanguageId << '\n' << _code << "\n```\n\n"; return *this; } - MarkdownBuilder& paragraph(string const& _text) + MarkdownBuilder& paragraph(std::string const& _text) { if (!_text.empty()) { diff --git a/libsolidity/lsp/FileRepository.cpp b/libsolidity/lsp/FileRepository.cpp index ca40343af3a5..7138cbd86adf 100644 --- a/libsolidity/lsp/FileRepository.cpp +++ b/libsolidity/lsp/FileRepository.cpp @@ -34,7 +34,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::lsp; using namespace solidity::frontend; @@ -54,11 +53,11 @@ void FileRepository::setIncludePaths(std::vector _paths m_includePaths = std::move(_paths); } -string FileRepository::sourceUnitNameToUri(string const& _sourceUnitName) const +std::string FileRepository::sourceUnitNameToUri(std::string const& _sourceUnitName) const { - regex const windowsDriveLetterPath("^[a-zA-Z]:/"); + std::regex const windowsDriveLetterPath("^[a-zA-Z]:/"); - auto const ensurePathIsUnixLike = [&](string inputPath) -> string { + auto const ensurePathIsUnixLike = [&](std::string inputPath) -> std::string { if (!regex_search(inputPath, windowsDriveLetterPath)) return inputPath; else @@ -86,13 +85,13 @@ string FileRepository::sourceUnitNameToUri(string const& _sourceUnitName) const return "file:///" + _sourceUnitName; } -string FileRepository::uriToSourceUnitName(string const& _path) const +std::string FileRepository::uriToSourceUnitName(std::string const& _path) const { lspRequire(boost::algorithm::starts_with(_path, "file://"), ErrorCode::InternalError, "URI must start with file://"); return stripFileUriSchemePrefix(_path); } -void FileRepository::setSourceByUri(string const& _uri, string _source) +void FileRepository::setSourceByUri(std::string const& _uri, std::string _source) { // This is needed for uris outside the base path. It can lead to collisions, // but we need to mostly rewrite this in a future version anyway. @@ -110,9 +109,9 @@ Result FileRepository::tryResolvePath(std::string const ) return boost::filesystem::path(_strippedSourceUnitName); - vector candidates; - vector> prefixes = {m_basePath}; - prefixes += (m_includePaths | ranges::to>>); + std::vector candidates; + std::vector> prefixes = {m_basePath}; + prefixes += (m_includePaths | ranges::to>>); auto const defaultInclude = m_basePath / "node_modules"; if (m_includePaths.empty()) prefixes.emplace_back(defaultInclude); @@ -148,7 +147,7 @@ Result FileRepository::tryResolvePath(std::string const return candidates[0]; } -frontend::ReadCallback::Result FileRepository::readFile(string const& _kind, string const& _sourceUnitName) +frontend::ReadCallback::Result FileRepository::readFile(std::string const& _kind, std::string const& _sourceUnitName) { solAssert( _kind == ReadCallback::kindString(ReadCallback::Kind::ReadFile), @@ -161,7 +160,7 @@ frontend::ReadCallback::Result FileRepository::readFile(string const& _kind, str if (m_sourceCodes.count(_sourceUnitName)) return ReadCallback::Result{true, m_sourceCodes.at(_sourceUnitName)}; - string const strippedSourceUnitName = stripFileUriSchemePrefix(_sourceUnitName); + std::string const strippedSourceUnitName = stripFileUriSchemePrefix(_sourceUnitName); Result const resolvedPath = tryResolvePath(strippedSourceUnitName); if (!resolvedPath.message().empty()) return ReadCallback::Result{false, resolvedPath.message()}; diff --git a/libsolidity/lsp/GotoDefinition.cpp b/libsolidity/lsp/GotoDefinition.cpp index 532792c177e0..136e4d7c391b 100644 --- a/libsolidity/lsp/GotoDefinition.cpp +++ b/libsolidity/lsp/GotoDefinition.cpp @@ -30,7 +30,6 @@ using namespace solidity::frontend; using namespace solidity::langutil; using namespace solidity::lsp; -using namespace std; void GotoDefinition::operator()(MessageID _id, Json::Value const& _args) { @@ -38,7 +37,7 @@ void GotoDefinition::operator()(MessageID _id, Json::Value const& _args) ASTNode const* sourceNode = m_server.astNodeAtSourceLocation(sourceUnitName, lineColumn); - vector locations; + std::vector locations; if (auto const* expression = dynamic_cast(sourceNode)) { // Handles all expressions that can have one or more declaration annotation. @@ -56,7 +55,7 @@ void GotoDefinition::operator()(MessageID _id, Json::Value const& _args) { auto const& path = *importDirective->annotation().absolutePath; if (fileRepository().sourceUnits().count(path)) - locations.emplace_back(SourceLocation{0, 0, make_shared(path)}); + locations.emplace_back(SourceLocation{0, 0, std::make_shared(path)}); } Json::Value reply = Json::arrayValue; diff --git a/libsolidity/lsp/HandlerBase.cpp b/libsolidity/lsp/HandlerBase.cpp index f40f189ab359..a23e43a83ce1 100644 --- a/libsolidity/lsp/HandlerBase.cpp +++ b/libsolidity/lsp/HandlerBase.cpp @@ -29,7 +29,6 @@ using namespace solidity::langutil; using namespace solidity::lsp; using namespace solidity::util; -using namespace std; Json::Value HandlerBase::toRange(SourceLocation const& _location) const { @@ -52,10 +51,10 @@ Json::Value HandlerBase::toJson(SourceLocation const& _location) const return item; } -pair HandlerBase::extractSourceUnitNameAndLineColumn(Json::Value const& _args) const +std::pair HandlerBase::extractSourceUnitNameAndLineColumn(Json::Value const& _args) const { - string const uri = _args["textDocument"]["uri"].asString(); - string const sourceUnitName = fileRepository().uriToSourceUnitName(uri); + std::string const uri = _args["textDocument"]["uri"].asString(); + std::string const sourceUnitName = fileRepository().uriToSourceUnitName(uri); if (!fileRepository().sourceUnits().count(sourceUnitName)) BOOST_THROW_EXCEPTION( RequestError(ErrorCode::RequestFailed) << diff --git a/libsolidity/lsp/LanguageServer.cpp b/libsolidity/lsp/LanguageServer.cpp index aaa63b7f84ff..81b95e05a168 100644 --- a/libsolidity/lsp/LanguageServer.cpp +++ b/libsolidity/lsp/LanguageServer.cpp @@ -46,7 +46,6 @@ #include -using namespace std; using namespace std::string_literals; using namespace std::placeholders; @@ -109,7 +108,7 @@ Json::Value semanticTokensLegend() tokenTypes.append("operator"); tokenTypes.append("parameter"); tokenTypes.append("property"); - tokenTypes.append("string"); + tokenTypes.append("std::string"); tokenTypes.append("struct"); tokenTypes.append("type"); tokenTypes.append("typeParameter"); @@ -137,19 +136,19 @@ LanguageServer::LanguageServer(Transport& _transport): {"$/cancelRequest", [](auto, auto) {/*nothing for now as we are synchronous */}}, {"cancelRequest", [](auto, auto) {/*nothing for now as we are synchronous */}}, {"exit", [this](auto, auto) { m_state = (m_state == State::ShutdownRequested ? State::ExitRequested : State::ExitWithoutShutdown); }}, - {"initialize", bind(&LanguageServer::handleInitialize, this, _1, _2)}, - {"initialized", bind(&LanguageServer::handleInitialized, this, _1, _2)}, + {"initialize", std::bind(&LanguageServer::handleInitialize, this, _1, _2)}, + {"initialized", std::bind(&LanguageServer::handleInitialized, this, _1, _2)}, {"$/setTrace", [this](auto, Json::Value const& args) { setTrace(args["value"]); }}, {"shutdown", [this](auto, auto) { m_state = State::ShutdownRequested; }}, {"textDocument/definition", GotoDefinition(*this) }, - {"textDocument/didOpen", bind(&LanguageServer::handleTextDocumentDidOpen, this, _2)}, - {"textDocument/didChange", bind(&LanguageServer::handleTextDocumentDidChange, this, _2)}, - {"textDocument/didClose", bind(&LanguageServer::handleTextDocumentDidClose, this, _2)}, + {"textDocument/didOpen", std::bind(&LanguageServer::handleTextDocumentDidOpen, this, _2)}, + {"textDocument/didChange", std::bind(&LanguageServer::handleTextDocumentDidChange, this, _2)}, + {"textDocument/didClose", std::bind(&LanguageServer::handleTextDocumentDidClose, this, _2)}, {"textDocument/hover", DocumentHoverHandler(*this) }, {"textDocument/rename", RenameSymbol(*this) }, {"textDocument/implementation", GotoDefinition(*this) }, - {"textDocument/semanticTokens/full", bind(&LanguageServer::semanticTokensFull, this, _1, _2)}, - {"workspace/didChangeConfiguration", bind(&LanguageServer::handleWorkspaceDidChangeConfiguration, this, _2)}, + {"textDocument/semanticTokens/full", std::bind(&LanguageServer::semanticTokensFull, this, _1, _2)}, + {"workspace/didChangeConfiguration", std::bind(&LanguageServer::handleWorkspaceDidChangeConfiguration, this, _2)}, }, m_fileRepository("/" /* basePath */, {} /* no search paths */), m_compilerStack{m_fileRepository.reader()} @@ -196,7 +195,7 @@ void LanguageServer::changeConfiguration(Json::Value const& _settings) int typeFailureCount = 0; if (jsonIncludePaths.isArray()) { - vector includePaths; + std::vector includePaths; for (Json::Value const& jsonPath: jsonIncludePaths) { if (jsonPath.isString()) @@ -214,9 +213,9 @@ void LanguageServer::changeConfiguration(Json::Value const& _settings) } } -vector LanguageServer::allSolidityFilesFromProject() const +std::vector LanguageServer::allSolidityFilesFromProject() const { - vector collectedPaths{}; + std::vector collectedPaths{}; // We explicitly decided against including all files from include paths but leave the possibility // open for a future PR to enable such a feature to be optionally enabled (default disabled). @@ -242,7 +241,7 @@ void LanguageServer::compile() // so we just remove all non-open files. FileRepository oldRepository(m_fileRepository.basePath(), m_fileRepository.includePaths()); - swap(oldRepository, m_fileRepository); + std::swap(oldRepository, m_fileRepository); // Load all solidity files from project. if (m_fileLoadStrategy == FileLoadStrategy::ProjectDirectory) @@ -256,7 +255,7 @@ void LanguageServer::compile() } // Overwrite all files as opened by the client, including the ones which might potentially have changes. - for (string const& fileName: m_openFiles) + for (std::string const& fileName: m_openFiles) m_fileRepository.setSourceByUri( fileName, oldRepository.sourceUnits().at(oldRepository.uriToSourceUnitName(fileName)) @@ -275,13 +274,13 @@ void LanguageServer::compileAndUpdateDiagnostics() // These are the source units we will sent diagnostics to the client for sure, // even if it is just to clear previous diagnostics. - map diagnosticsBySourceUnit; - for (string const& sourceUnitName: m_fileRepository.sourceUnits() | ranges::views::keys) + std::map diagnosticsBySourceUnit; + for (std::string const& sourceUnitName: m_fileRepository.sourceUnits() | ranges::views::keys) diagnosticsBySourceUnit[sourceUnitName] = Json::arrayValue; - for (string const& sourceUnitName: m_nonemptyDiagnostics) + for (std::string const& sourceUnitName: m_nonemptyDiagnostics) diagnosticsBySourceUnit[sourceUnitName] = Json::arrayValue; - for (shared_ptr const& error: m_compilerStack.errors()) + for (std::shared_ptr const& error: m_compilerStack.errors()) { SourceLocation const* location = error->sourceLocation(); if (!location || !location->sourceName) @@ -292,8 +291,8 @@ void LanguageServer::compileAndUpdateDiagnostics() jsonDiag["source"] = "solc"; jsonDiag["severity"] = toDiagnosticSeverity(error->type()); jsonDiag["code"] = Json::UInt64{error->errorId().error}; - string message = Error::formatErrorType(error->type()) + ":"; - if (string const* comment = error->comment()) + std::string message = Error::formatErrorType(error->type()) + ":"; + if (std::string const* comment = error->comment()) message += " " + *comment; jsonDiag["message"] = std::move(message); jsonDiag["range"] = toRange(*location); @@ -314,7 +313,7 @@ void LanguageServer::compileAndUpdateDiagnostics() { Json::Value extra; extra["openFileCount"] = Json::UInt64(diagnosticsBySourceUnit.size()); - m_client.trace("Number of currently open files: " + to_string(diagnosticsBySourceUnit.size()), extra); + m_client.trace("Number of currently open files: " + std::to_string(diagnosticsBySourceUnit.size()), extra); } m_nonemptyDiagnostics.clear(); @@ -336,13 +335,13 @@ bool LanguageServer::run() MessageID id; try { - optional const jsonMessage = m_client.receive(); + std::optional const jsonMessage = m_client.receive(); if (!jsonMessage) continue; if ((*jsonMessage)["method"].isString()) { - string const methodName = (*jsonMessage)["method"].asString(); + std::string const methodName = (*jsonMessage)["method"].asString(); id = (*jsonMessage)["id"]; lspDebug(fmt::format("received method call: {}", methodName)); @@ -391,7 +390,7 @@ void LanguageServer::handleInitialize(MessageID _id, Json::Value const& _args) // The default of FileReader is to use `.`, but the path from where the LSP was started // should not matter. - string rootPath("/"); + std::string rootPath("/"); if (Json::Value uri = _args["rootUri"]) { rootPath = uri.asString(); @@ -414,7 +413,7 @@ void LanguageServer::handleInitialize(MessageID _id, Json::Value const& _args) Json::Value replyArgs; replyArgs["serverInfo"]["name"] = "solc"; - replyArgs["serverInfo"]["version"] = string(VersionNumber); + replyArgs["serverInfo"]["version"] = std::string(VersionNumber); replyArgs["capabilities"]["definitionProvider"] = true; replyArgs["capabilities"]["implementationProvider"] = true; replyArgs["capabilities"]["textDocumentSync"]["change"] = 2; // 0=none, 1=full, 2=incremental @@ -440,7 +439,7 @@ void LanguageServer::semanticTokensFull(MessageID _id, Json::Value const& _args) compile(); - auto const sourceName = m_fileRepository.uriToSourceUnitName(uri.as()); + auto const sourceName = m_fileRepository.uriToSourceUnitName(uri.as()); SourceUnit const& ast = m_compilerStack.ast(sourceName); m_compilerStack.charStream(sourceName); Json::Value data = SemanticTokensBuilder().build(ast, m_compilerStack.charStream(sourceName)); @@ -465,7 +464,7 @@ void LanguageServer::setTrace(Json::Value const& _args) // Simply ignore invalid parameter. return; - string const stringValue = _args.asString(); + std::string const stringValue = _args.asString(); if (stringValue == "off") m_client.setTrace(TraceValue::Off); else if (stringValue == "messages") @@ -484,8 +483,8 @@ void LanguageServer::handleTextDocumentDidOpen(Json::Value const& _args) "Text document parameter missing." ); - string text = _args["textDocument"]["text"].asString(); - string uri = _args["textDocument"]["uri"].asString(); + std::string text = _args["textDocument"]["text"].asString(); + std::string uri = _args["textDocument"]["uri"].asString(); m_openFiles.insert(uri); m_fileRepository.setSourceByUri(uri, std::move(text)); compileAndUpdateDiagnostics(); @@ -495,7 +494,7 @@ void LanguageServer::handleTextDocumentDidChange(Json::Value const& _args) { requireServerInitialized(); - string const uri = _args["textDocument"]["uri"].asString(); + std::string const uri = _args["textDocument"]["uri"].asString(); for (Json::Value jsonContentChange: _args["contentChanges"]) { @@ -505,24 +504,24 @@ void LanguageServer::handleTextDocumentDidChange(Json::Value const& _args) "Invalid content reference." ); - string const sourceUnitName = m_fileRepository.uriToSourceUnitName(uri); + std::string const sourceUnitName = m_fileRepository.uriToSourceUnitName(uri); lspRequire( m_fileRepository.sourceUnits().count(sourceUnitName), ErrorCode::RequestFailed, "Unknown file: " + uri ); - string text = jsonContentChange["text"].asString(); + std::string text = jsonContentChange["text"].asString(); if (jsonContentChange["range"].isObject()) // otherwise full content update { - optional change = parseRange(m_fileRepository, sourceUnitName, jsonContentChange["range"]); + std::optional change = parseRange(m_fileRepository, sourceUnitName, jsonContentChange["range"]); lspRequire( change && change->hasText(), ErrorCode::RequestFailed, "Invalid source range: " + util::jsonCompactPrint(jsonContentChange["range"]) ); - string buffer = m_fileRepository.sourceUnits().at(sourceUnitName); + std::string buffer = m_fileRepository.sourceUnits().at(sourceUnitName); buffer.replace(static_cast(change->start), static_cast(change->end - change->start), std::move(text)); text = std::move(buffer); } @@ -542,7 +541,7 @@ void LanguageServer::handleTextDocumentDidClose(Json::Value const& _args) "Text document parameter missing." ); - string uri = _args["textDocument"]["uri"].asString(); + std::string uri = _args["textDocument"]["uri"].asString(); m_openFiles.erase(uri); compileAndUpdateDiagnostics(); @@ -550,17 +549,17 @@ void LanguageServer::handleTextDocumentDidClose(Json::Value const& _args) ASTNode const* LanguageServer::astNodeAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos) { - return get(astNodeAndOffsetAtSourceLocation(_sourceUnitName, _filePos)); + return std::get(astNodeAndOffsetAtSourceLocation(_sourceUnitName, _filePos)); } -tuple LanguageServer::astNodeAndOffsetAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos) +std::tuple LanguageServer::astNodeAndOffsetAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos) { if (m_compilerStack.state() < CompilerStack::AnalysisPerformed) return {nullptr, -1}; if (!m_fileRepository.sourceUnits().count(_sourceUnitName)) return {nullptr, -1}; - optional sourcePos = m_compilerStack.charStream(_sourceUnitName).translateLineColumnToPosition(_filePos); + std::optional sourcePos = m_compilerStack.charStream(_sourceUnitName).translateLineColumnToPosition(_filePos); if (!sourcePos) return {nullptr, -1}; diff --git a/libsolidity/lsp/RenameSymbol.cpp b/libsolidity/lsp/RenameSymbol.cpp index e205beb73f03..75f032fcca47 100644 --- a/libsolidity/lsp/RenameSymbol.cpp +++ b/libsolidity/lsp/RenameSymbol.cpp @@ -29,7 +29,6 @@ using namespace solidity::frontend; using namespace solidity::langutil; using namespace solidity::lsp; -using namespace std; namespace { @@ -51,8 +50,8 @@ CallableDeclaration const* extractCallableDeclaration(FunctionCall const& _funct void RenameSymbol::operator()(MessageID _id, Json::Value const& _args) { auto const&& [sourceUnitName, lineColumn] = extractSourceUnitNameAndLineColumn(_args); - string const newName = _args["newName"].asString(); - string const uri = _args["textDocument"]["uri"].asString(); + std::string const newName = _args["newName"].asString(); + std::string const uri = _args["textDocument"]["uri"].asString(); ASTNode const* sourceNode = m_server.astNodeAtSourceLocation(sourceUnitName, lineColumn); @@ -61,7 +60,7 @@ void RenameSymbol::operator()(MessageID _id, Json::Value const& _args) m_sourceUnits = { &m_server.compilerStack().ast(sourceUnitName) }; m_locations.clear(); - optional cursorBytePosition = charStreamProvider() + std::optional cursorBytePosition = charStreamProvider() .charStream(sourceUnitName) .translateLineColumnToPosition(lineColumn); solAssert(cursorBytePosition.has_value(), "Expected source pos"); @@ -72,7 +71,7 @@ void RenameSymbol::operator()(MessageID _id, Json::Value const& _args) for (auto const& [name, content]: fileRepository().sourceUnits()) { auto const& sourceUnit = m_server.compilerStack().ast(name); - for (auto const* referencedSourceUnit: sourceUnit.referencedSourceUnits(true, util::convertContainer>(m_sourceUnits))) + for (auto const* referencedSourceUnit: sourceUnit.referencedSourceUnits(true, util::convertContainer>(m_sourceUnits))) if (*referencedSourceUnit->location().sourceName == sourceUnitName) { m_sourceUnits.insert(&sourceUnit); @@ -101,8 +100,8 @@ void RenameSymbol::operator()(MessageID _id, Json::Value const& _args) solAssert(i->isValid()); // Replace in our file repository - string const uri = fileRepository().sourceUnitNameToUri(*i->sourceName); - string buffer = fileRepository().sourceUnits().at(*i->sourceName); + std::string const uri = fileRepository().sourceUnitNameToUri(*i->sourceName); + std::string buffer = fileRepository().sourceUnits().at(*i->sourceName); buffer.replace((size_t)i->start, (size_t)(i->end - i->start), newName); fileRepository().setSourceByUri(uri, std::move(buffer)); @@ -155,7 +154,7 @@ void RenameSymbol::extractNameAndDeclaration(ASTNode const& _node, int _cursorBy else if (auto const* inlineAssembly = dynamic_cast(&_node)) extractNameAndDeclaration(*inlineAssembly, _cursorBytePosition); else - solAssert(false, "Unexpected ASTNODE id: " + to_string(_node.id())); + solAssert(false, "Unexpected ASTNODE id: " + std::to_string(_node.id())); lspDebug(fmt::format("Goal: rename '{}', loc: {}-{}", m_symbolName, m_declarationToRename->nameLocation().start, m_declarationToRename->nameLocation().end)); } @@ -297,7 +296,7 @@ void RenameSymbol::Visitor::endVisit(InlineAssembly const& _node) { for (auto&& [identifier, externalReference]: _node.annotation().externalReferences) { - string identifierName = identifier->name.str(); + std::string identifierName = identifier->name.str(); if (!externalReference.suffix.empty()) identifierName = identifierName.substr(0, identifierName.length() - externalReference.suffix.size() - 1); diff --git a/libsolidity/lsp/SemanticTokensBuilder.cpp b/libsolidity/lsp/SemanticTokensBuilder.cpp index dae48c1b50cf..ac52954738f7 100644 --- a/libsolidity/lsp/SemanticTokensBuilder.cpp +++ b/libsolidity/lsp/SemanticTokensBuilder.cpp @@ -23,7 +23,6 @@ #include -using namespace std; using namespace solidity::langutil; using namespace solidity::frontend; @@ -33,10 +32,10 @@ namespace solidity::lsp namespace { -optional semanticTokenTypeForType(frontend::Type const* _type) +std::optional semanticTokenTypeForType(frontend::Type const* _type) { if (!_type) - return nullopt; + return std::nullopt; switch (_type->category()) { diff --git a/libsolidity/lsp/Transport.cpp b/libsolidity/lsp/Transport.cpp index 5af723128ab6..7f8eb2283488 100644 --- a/libsolidity/lsp/Transport.cpp +++ b/libsolidity/lsp/Transport.cpp @@ -37,34 +37,33 @@ #include #endif -using namespace std; using namespace solidity::lsp; // {{{ Transport -optional Transport::receive() +std::optional Transport::receive() { auto const headers = parseHeaders(); if (!headers) { error({}, ErrorCode::ParseError, "Could not parse RPC headers."); - return nullopt; + return std::nullopt; } if (!headers->count("content-length")) { error({}, ErrorCode::ParseError, "No content-length header found."); - return nullopt; + return std::nullopt; } - string const data = readBytes(stoul(headers->at("content-length"))); + std::string const data = readBytes(stoul(headers->at("content-length"))); Json::Value jsonMessage; - string jsonParsingErrors; + std::string jsonParsingErrors; solidity::util::jsonParseStrict(data, jsonMessage, &jsonParsingErrors); if (!jsonParsingErrors.empty() || !jsonMessage || !jsonMessage.isObject()) { error({}, ErrorCode::ParseError, "Could not parse RPC JSON payload. " + jsonParsingErrors); - return nullopt; + return std::nullopt; } return {std::move(jsonMessage)}; @@ -82,9 +81,9 @@ void Transport::trace(std::string _message, Json::Value _extra) } } -optional> Transport::parseHeaders() +std::optional> Transport::parseHeaders() { - map headers; + std::map headers; while (true) { @@ -93,18 +92,18 @@ optional> Transport::parseHeaders() break; auto const delimiterPos = line.find(':'); - if (delimiterPos == string::npos) - return nullopt; + if (delimiterPos == std::string::npos) + return std::nullopt; auto const name = boost::to_lower_copy(line.substr(0, delimiterPos)); auto const value = line.substr(delimiterPos + 1); if (!headers.emplace(boost::trim_copy(name), boost::trim_copy(value)).second) - return nullopt; + return std::nullopt; } return {std::move(headers)}; } -void Transport::notify(string _method, Json::Value _message) +void Transport::notify(std::string _method, Json::Value _message) { Json::Value json; json["method"] = std::move(_method); @@ -119,7 +118,7 @@ void Transport::reply(MessageID _id, Json::Value _message) send(std::move(json), _id); } -void Transport::error(MessageID _id, ErrorCode _code, string _message) +void Transport::error(MessageID _id, ErrorCode _code, std::string _message) { Json::Value json; json["error"]["code"] = static_cast(_code); @@ -135,7 +134,7 @@ void Transport::send(Json::Value _json, MessageID _id) _json["id"] = _id; // Trailing CRLF only for easier readability. - string const jsonString = solidity::util::jsonCompactPrint(_json); + std::string const jsonString = solidity::util::jsonCompactPrint(_json); writeBytes(fmt::format("Content-Length: {}\r\n\r\n", jsonString.size())); writeBytes(jsonString); @@ -144,7 +143,7 @@ void Transport::send(Json::Value _json, MessageID _id) // }}} // {{{ IOStreamTransport -IOStreamTransport::IOStreamTransport(istream& _in, ostream& _out): +IOStreamTransport::IOStreamTransport(std::istream& _in, std::ostream& _out): m_input{_in}, m_output{_out} { @@ -162,7 +161,7 @@ std::string IOStreamTransport::readBytes(size_t _length) std::string IOStreamTransport::getline() { - string line; + std::string line; std::getline(m_input, line); return line; } diff --git a/libsolidity/lsp/Utils.cpp b/libsolidity/lsp/Utils.cpp index ef19b4c2efb6..85e27a4fda5f 100644 --- a/libsolidity/lsp/Utils.cpp +++ b/libsolidity/lsp/Utils.cpp @@ -30,21 +30,20 @@ namespace solidity::lsp using namespace frontend; using namespace langutil; -using namespace std; -optional parseLineColumn(Json::Value const& _lineColumn) +std::optional parseLineColumn(Json::Value const& _lineColumn) { if (_lineColumn.isObject() && _lineColumn["line"].isInt() && _lineColumn["character"].isInt()) return LineColumn{_lineColumn["line"].asInt(), _lineColumn["character"].asInt()}; else - return nullopt; + return std::nullopt; } Json::Value toJson(LineColumn const& _pos) { Json::Value json = Json::objectValue; - json["line"] = max(_pos.line, 0); - json["character"] = max(_pos.column, 0); + json["line"] = std::max(_pos.line, 0); + json["character"] = std::max(_pos.column, 0); return json; } @@ -70,10 +69,10 @@ Declaration const* referencedDeclaration(Expression const* _expression) return nullptr; } -optional declarationLocation(Declaration const* _declaration) +std::optional declarationLocation(Declaration const* _declaration) { if (!_declaration) - return nullopt; + return std::nullopt; if (_declaration->nameLocation().isValid()) return _declaration->nameLocation(); @@ -81,43 +80,43 @@ optional declarationLocation(Declaration const* _declaration) if (_declaration->location().isValid()) return _declaration->location(); - return nullopt; + return std::nullopt; } -optional parsePosition( +std::optional parsePosition( FileRepository const& _fileRepository, - string const& _sourceUnitName, + std::string const& _sourceUnitName, Json::Value const& _position ) { if (!_fileRepository.sourceUnits().count(_sourceUnitName)) - return nullopt; + return std::nullopt; - if (optional lineColumn = parseLineColumn(_position)) - if (optional const offset = CharStream::translateLineColumnToPosition( + if (std::optional lineColumn = parseLineColumn(_position)) + if (std::optional const offset = CharStream::translateLineColumnToPosition( _fileRepository.sourceUnits().at(_sourceUnitName), *lineColumn )) - return SourceLocation{*offset, *offset, make_shared(_sourceUnitName)}; - return nullopt; + return SourceLocation{*offset, *offset, std::make_shared(_sourceUnitName)}; + return std::nullopt; } -optional parseRange(FileRepository const& _fileRepository, string const& _sourceUnitName, Json::Value const& _range) +std::optional parseRange(FileRepository const& _fileRepository, std::string const& _sourceUnitName, Json::Value const& _range) { if (!_range.isObject()) - return nullopt; - optional start = parsePosition(_fileRepository, _sourceUnitName, _range["start"]); - optional end = parsePosition(_fileRepository, _sourceUnitName, _range["end"]); + return std::nullopt; + std::optional start = parsePosition(_fileRepository, _sourceUnitName, _range["start"]); + std::optional end = parsePosition(_fileRepository, _sourceUnitName, _range["end"]); if (!start || !end) - return nullopt; + return std::nullopt; solAssert(*start->sourceName == *end->sourceName); start->end = end->end; return start; } -string stripFileUriSchemePrefix(string const& _path) +std::string stripFileUriSchemePrefix(std::string const& _path) { - regex const windowsDriveLetterPath("^file:///[a-zA-Z]:/"); + std::regex const windowsDriveLetterPath("^file:///[a-zA-Z]:/"); if (regex_search(_path, windowsDriveLetterPath)) return _path.substr(8); if (_path.find("file://") == 0) diff --git a/libsolidity/parsing/DocStringParser.cpp b/libsolidity/parsing/DocStringParser.cpp index 7e6e158b769e..b9f358e020a0 100644 --- a/libsolidity/parsing/DocStringParser.cpp +++ b/libsolidity/parsing/DocStringParser.cpp @@ -28,7 +28,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::langutil; using namespace solidity::frontend; @@ -36,17 +35,17 @@ using namespace solidity::frontend; namespace { -string::const_iterator skipLineOrEOS( - string::const_iterator _nlPos, - string::const_iterator _end +std::string::const_iterator skipLineOrEOS( + std::string::const_iterator _nlPos, + std::string::const_iterator _end ) { return (_nlPos == _end) ? _end : ++_nlPos; } -string::const_iterator firstNonIdentifier( - string::const_iterator _pos, - string::const_iterator _end +std::string::const_iterator firstNonIdentifier( + std::string::const_iterator _pos, + std::string::const_iterator _end ) { auto currPos = _pos; @@ -58,18 +57,18 @@ string::const_iterator firstNonIdentifier( return currPos; } -string::const_iterator firstWhitespaceOrNewline( - string::const_iterator _pos, - string::const_iterator _end +std::string::const_iterator firstWhitespaceOrNewline( + std::string::const_iterator _pos, + std::string::const_iterator _end ) { return ranges::find_first_of(ranges::make_subrange(_pos, _end), " \t\n"); } -string::const_iterator skipWhitespace( - string::const_iterator _pos, - string::const_iterator _end +std::string::const_iterator skipWhitespace( + std::string::const_iterator _pos, + std::string::const_iterator _end ) { auto isWhitespace = [](char const& c) { return (c == ' ' || c == '\t'); }; @@ -78,7 +77,7 @@ string::const_iterator skipWhitespace( } -multimap DocStringParser::parse() +std::multimap DocStringParser::parse() { m_lastTag = nullptr; m_docTags = {}; @@ -96,7 +95,7 @@ multimap DocStringParser::parse() { // we found a tag iter tagNameEndPos = firstWhitespaceOrNewline(tagPos, end); - string tagName{tagPos + 1, tagNameEndPos}; + std::string tagName{tagPos + 1, tagNameEndPos}; iter tagDataPos = (tagNameEndPos != end) ? tagNameEndPos + 1 : tagNameEndPos; currPos = parseDocTag(tagDataPos, end, tagName); } @@ -141,7 +140,7 @@ DocStringParser::iter DocStringParser::parseDocTagParam(iter _pos, iter _end) return _end; } auto nameEndPos = firstNonIdentifier(nameStartPos, _end); - auto paramName = string(nameStartPos, nameEndPos); + auto paramName = std::string(nameStartPos, nameEndPos); auto descStartPos = skipWhitespace(nameEndPos, _end); auto nlPos = find(descStartPos, _end, '\n'); @@ -152,7 +151,7 @@ DocStringParser::iter DocStringParser::parseDocTagParam(iter _pos, iter _end) return _end; } - auto paramDesc = string(descStartPos, nlPos); + auto paramDesc = std::string(descStartPos, nlPos); newTag("param"); m_lastTag->paramName = paramName; m_lastTag->content = paramDesc; @@ -160,7 +159,7 @@ DocStringParser::iter DocStringParser::parseDocTagParam(iter _pos, iter _end) return skipLineOrEOS(nlPos, _end); } -DocStringParser::iter DocStringParser::parseDocTag(iter _pos, iter _end, string const& _tag) +DocStringParser::iter DocStringParser::parseDocTag(iter _pos, iter _end, std::string const& _tag) { // TODO: need to check for @(start of a tag) between here and the end of line // for all cases. @@ -178,7 +177,7 @@ DocStringParser::iter DocStringParser::parseDocTag(iter _pos, iter _end, string return parseDocTagLine(_pos, _end, true); } -void DocStringParser::newTag(string const& _tagName) +void DocStringParser::newTag(std::string const& _tagName) { m_lastTag = &m_docTags.insert(make_pair(_tagName, DocTag()))->second; } diff --git a/libsolidity/parsing/Parser.cpp b/libsolidity/parsing/Parser.cpp index efbe854482ce..127ff402b4a4 100644 --- a/libsolidity/parsing/Parser.cpp +++ b/libsolidity/parsing/Parser.cpp @@ -43,8 +43,8 @@ #include #include -using namespace std; using namespace solidity::langutil; +using namespace std::string_literals; namespace solidity::frontend { @@ -76,7 +76,7 @@ class Parser::ASTNodeFactory solAssert(m_location.sourceName, ""); if (m_location.end < 0) markEndPosition(); - return make_shared(m_parser.nextID(), m_location, std::forward(_args)...); + return std::make_shared(m_parser.nextID(), m_location, std::forward(_args)...); } SourceLocation const& location() const noexcept { return m_location; } @@ -92,11 +92,11 @@ ASTPointer Parser::parse(CharStream& _charStream) try { m_recursionDepth = 0; - m_scanner = make_shared(_charStream); + m_scanner = std::make_shared(_charStream); ASTNodeFactory nodeFactory(*this); m_experimentalSolidityEnabledInCurrentSourceUnit = false; - vector> nodes; + std::vector> nodes; while (m_scanner->currentToken() == Token::Pragma) nodes.push_back(parsePragmaDirective(false)); @@ -164,13 +164,13 @@ ASTPointer Parser::parse(CharStream& _charStream) } } -void Parser::parsePragmaVersion(SourceLocation const& _location, vector const& _tokens, vector const& _literals) +void Parser::parsePragmaVersion(SourceLocation const& _location, std::vector const& _tokens, std::vector const& _literals) { SemVerMatchExpressionParser parser(_tokens, _literals); try { SemVerMatchExpression matchExpression = parser.parse(); - static SemVerVersion const currentVersion{string(VersionString)}; + static SemVerVersion const currentVersion{std::string(VersionString)}; // FIXME: only match for major version incompatibility if (!matchExpression.matches(currentVersion)) // If m_parserErrorRecovery is true, the same message will appear from SyntaxChecker::visit(), @@ -180,7 +180,7 @@ void Parser::parsePragmaVersion(SourceLocation const& _location, vector c 5333_error, _location, "Source file requires different compiler version (current compiler is " + - string(VersionString) + ") - note that nightly builds are considered to be " + std::string(VersionString) + ") - note that nightly builds are considered to be " "strictly less than the released version" ); } @@ -201,7 +201,7 @@ ASTPointer Parser::parseStructuredDocumentation() ASTNodeFactory nodeFactory{*this}; nodeFactory.setLocation(m_scanner->currentCommentLocation()); return nodeFactory.createNode( - make_shared(m_scanner->currentCommentLiteral()) + std::make_shared(m_scanner->currentCommentLiteral()) ); } return nullptr; @@ -215,8 +215,8 @@ ASTPointer Parser::parsePragmaDirective(bool const _finishedPar // pragma solidity ^0.4.0 || ^0.3.0; ASTNodeFactory nodeFactory(*this); expectToken(Token::Pragma); - vector literals; - vector tokens; + std::vector literals; + std::vector tokens; do { @@ -225,7 +225,7 @@ ASTPointer Parser::parsePragmaDirective(bool const _finishedPar parserError(6281_error, "Token incompatible with Solidity parser as part of pragma directive."); else { - string literal = m_scanner->currentLiteral(); + std::string literal = m_scanner->currentLiteral(); if (literal.empty() && TokenTraits::toString(token)) literal = TokenTraits::toString(token); literals.push_back(literal); @@ -241,8 +241,8 @@ ASTPointer Parser::parsePragmaDirective(bool const _finishedPar { parsePragmaVersion( nodeFactory.location(), - vector(tokens.begin() + 1, tokens.end()), - vector(literals.begin() + 1, literals.end()) + std::vector(tokens.begin() + 1, tokens.end()), + std::vector(literals.begin() + 1, literals.end()) ); } @@ -267,7 +267,7 @@ ASTPointer Parser::parseImportDirective() ASTNodeFactory nodeFactory(*this); expectToken(Token::Import); ASTPointer path; - ASTPointer unitAlias = make_shared(); + ASTPointer unitAlias = std::make_shared(); SourceLocation unitAliasLocation{}; ImportDirective::SymbolAliasList symbolAliases; @@ -361,8 +361,8 @@ ASTPointer Parser::parseContractDefinition() ASTPointer name = nullptr; SourceLocation nameLocation{}; ASTPointer documentation; - vector> baseContracts; - vector> subNodes; + std::vector> baseContracts; + std::vector> subNodes; std::pair contractKind{}; try { @@ -452,11 +452,11 @@ ASTPointer Parser::parseInheritanceSpecifier() RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer name(parseIdentifierPath()); - unique_ptr>> arguments; + std::unique_ptr>> arguments; if (m_scanner->currentToken() == Token::LParen) { advance(); - arguments = make_unique>>(parseFunctionCallListArguments()); + arguments = std::make_unique>>(parseFunctionCallListArguments()); nodeFactory.markEndPosition(); expectToken(Token::RParen); } @@ -642,8 +642,8 @@ ASTPointer Parser::parseFunctionDefinition(bool _freeFunction) {Token::Receive, "receive function"}, }.at(m_scanner->currentToken()); nameLocation = currentLocation(); - name = make_shared(TokenTraits::toString(m_scanner->currentToken())); - string message{ + name = std::make_shared(TokenTraits::toString(m_scanner->currentToken())); + std::string message{ "This function is named \"" + *name + "\" but is not the " + expected + " of the contract. " "If you intend this to be a " + expected + ", use \"" + *name + "(...) { ... }\" without " "the \"function\" keyword to define it." @@ -661,7 +661,7 @@ ASTPointer Parser::parseFunctionDefinition(bool _freeFunction) { solAssert(kind == Token::Constructor || kind == Token::Fallback || kind == Token::Receive, ""); advance(); - name = make_shared(); + name = std::make_shared(); } FunctionHeaderParserResult header = parseFunctionHeader(false); @@ -699,7 +699,7 @@ ASTPointer Parser::parseStructDefinition() ASTPointer documentation = parseStructuredDocumentation(); expectToken(Token::Struct); auto [name, nameLocation] = expectIdentifierWithLocation(); - vector> members; + std::vector> members; expectToken(Token::LBrace); while (m_scanner->currentToken() != Token::RBrace) { @@ -726,7 +726,7 @@ ASTPointer Parser::parseEnumDefinition() ASTPointer documentation = parseStructuredDocumentation(); expectToken(Token::Enum); auto [name, nameLocation] = expectIdentifierWithLocation(); - vector> members; + std::vector> members; expectToken(Token::LBrace); while (m_scanner->currentToken() != Token::RBrace) @@ -815,7 +815,7 @@ ASTPointer Parser::parseVariableDeclaration( if (mutability != VariableDeclaration::Mutability::Mutable) parserError( 3109_error, - string("Mutability already set to ") + + std::string("Mutability already set to ") + (mutability == VariableDeclaration::Mutability::Constant ? "\"constant\"" : "\"immutable\"") ); else if (token == Token::Constant) @@ -853,7 +853,7 @@ ASTPointer Parser::parseVariableDeclaration( } if (_options.allowEmptyName && m_scanner->currentToken() != Token::Identifier) - identifier = make_shared(""); + identifier = std::make_shared(""); else { nodeFactory.markEndPosition(); @@ -940,7 +940,7 @@ ASTPointer Parser::parseModifierDefinition() return nodeFactory.createNode(name, nameLocation, documentation, parameters, isVirtual, overrides, block); } -pair, SourceLocation> Parser::expectIdentifierWithLocation() +std::pair, SourceLocation> Parser::expectIdentifierWithLocation() { SourceLocation nameLocation = currentLocation(); ASTPointer name = expectIdentifierToken(); @@ -994,8 +994,8 @@ ASTPointer Parser::parseUsingDirective() expectToken(Token::Using); - vector> functions; - vector> operators; + std::vector> functions; + std::vector> operators; bool const usesBraces = m_scanner->currentToken() == Token::LBrace; if (usesBraces) { @@ -1009,18 +1009,18 @@ ASTPointer Parser::parseUsingDirective() Token operator_ = m_scanner->currentToken(); if (!util::contains(userDefinableOperators, operator_)) { - string operatorName; + std::string operatorName; if (!m_scanner->currentLiteral().empty()) operatorName = m_scanner->currentLiteral(); else if (char const* tokenString = TokenTraits::toString(operator_)) - operatorName = string(tokenString); + operatorName = std::string(tokenString); parserError( 4403_error, fmt::format( "Not a user-definable operator: {}. Only the following operators can be user-defined: {}", operatorName, - util::joinHumanReadable(userDefinableOperators | ranges::views::transform([](Token _t) { return string{TokenTraits::toString(_t)}; })) + util::joinHumanReadable(userDefinableOperators | ranges::views::transform([](Token _t) { return std::string{TokenTraits::toString(_t)}; })) ) ); } @@ -1028,7 +1028,7 @@ ASTPointer Parser::parseUsingDirective() advance(); } else - operators.emplace_back(nullopt); + operators.emplace_back(std::nullopt); } while (m_scanner->currentToken() == Token::Comma); expectToken(Token::RBrace); @@ -1036,7 +1036,7 @@ ASTPointer Parser::parseUsingDirective() else { functions.emplace_back(parseIdentifierPath()); - operators.emplace_back(nullopt); + operators.emplace_back(std::nullopt); } ASTPointer typeName; @@ -1061,11 +1061,11 @@ ASTPointer Parser::parseModifierInvocation() RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); ASTPointer name(parseIdentifierPath()); - unique_ptr>> arguments; + std::unique_ptr>> arguments; if (m_scanner->currentToken() == Token::LParen) { advance(); - arguments = make_unique>>(parseFunctionCallListArguments()); + arguments = std::make_unique>>(parseFunctionCallListArguments()); nodeFactory.markEndPosition(); expectToken(Token::RParen); } @@ -1122,8 +1122,8 @@ ASTPointer Parser::parseIdentifierPath() auto [name, nameLocation] = expectIdentifierWithLocation(); - vector identifierPath{*name}; - vector identifierPathLocations{nameLocation}; + std::vector identifierPath{*name}; + std::vector identifierPathLocations{nameLocation}; while (m_scanner->currentToken() == Token::Period) { @@ -1165,14 +1165,14 @@ ASTPointer Parser::parseTypeName() { unsigned firstSize; unsigned secondSize; - tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); + std::tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); ElementaryTypeNameToken elemTypeName(token, firstSize, secondSize); ASTNodeFactory nodeFactory(*this); nodeFactory.markEndPosition(); advance(); auto stateMutability = elemTypeName.token() == Token::Address - ? optional{StateMutability::NonPayable} - : nullopt; + ? std::optional{StateMutability::NonPayable} + : std::nullopt; if (TokenTraits::isStateMutabilitySpecifier(m_scanner->currentToken())) { if (elemTypeName.token() == Token::Address) @@ -1228,7 +1228,7 @@ ASTPointer Parser::parseMapping() Token token = m_scanner->currentToken(); unsigned firstSize; unsigned secondSize; - tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); + std::tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); if (token == Token::Identifier) keyType = parseUserDefinedTypeName(); else if (TokenTraits::isElementaryTypeName(token)) @@ -1240,13 +1240,13 @@ ASTPointer Parser::parseMapping() } else fatalParserError(1005_error, "Expected elementary type name or identifier for mapping key type"); - ASTPointer keyName = make_shared(""); + ASTPointer keyName = std::make_shared(""); SourceLocation keyNameLocation{}; if (m_scanner->currentToken() == Token::Identifier) tie(keyName, keyNameLocation) = expectIdentifierWithLocation(); expectToken(Token::DoubleArrow); ASTPointer valueType = parseTypeName(); - ASTPointer valueName = make_shared(""); + ASTPointer valueName = std::make_shared(""); SourceLocation valueNameLocation{}; if (m_scanner->currentToken() == Token::Identifier) tie(valueName, valueNameLocation) = expectIdentifierWithLocation(); @@ -1262,7 +1262,7 @@ ASTPointer Parser::parseParameterList( { RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); - vector> parameters; + std::vector> parameters; VarDeclParserOptions options(_options); options.allowEmptyName = true; expectToken(Token::LParen); @@ -1294,7 +1294,7 @@ ASTPointer Parser::parseBlock(bool _allowUnchecked, ASTPointer advance(); } expectToken(Token::LBrace); - vector> statements; + std::vector> statements; try { while (m_scanner->currentToken() != Token::RBrace) @@ -1326,7 +1326,7 @@ ASTPointer Parser::parseStatement(bool _allowUnchecked) try { if (m_scanner->currentCommentLiteral() != "") - docString = make_shared(m_scanner->currentCommentLiteral()); + docString = std::make_shared(m_scanner->currentCommentLiteral()); switch (m_scanner->currentToken()) { case Token::If: @@ -1421,15 +1421,15 @@ ASTPointer Parser::parseInlineAssembly(ASTPointer con advance(); } - ASTPointer>> flags; + ASTPointer>> flags; if (m_scanner->currentToken() == Token::LParen) { - flags = make_shared>>(); + flags = std::make_shared>>(); do { advance(); expectToken(Token::StringLiteral, false); - flags->emplace_back(make_shared(m_scanner->currentLiteral())); + flags->emplace_back(std::make_shared(m_scanner->currentLiteral())); advance(); } while (m_scanner->currentToken() == Token::Comma); @@ -1437,12 +1437,12 @@ ASTPointer Parser::parseInlineAssembly(ASTPointer con } yul::Parser asmParser(m_errorReporter, dialect); - shared_ptr block = asmParser.parseInline(m_scanner); + std::shared_ptr block = asmParser.parseInline(m_scanner); if (block == nullptr) BOOST_THROW_EXCEPTION(FatalError()); location.end = nativeLocationOf(*block).end; - return make_shared(nextID(), location, _docString, dialect, std::move(flags), block); + return std::make_shared(nextID(), location, _docString, dialect, std::move(flags), block); } ASTPointer Parser::parseIfStatement(ASTPointer const& _docString) @@ -1472,7 +1472,7 @@ ASTPointer Parser::parseTryStatement(ASTPointer const& ASTNodeFactory nodeFactory(*this); expectToken(Token::Try); ASTPointer externalCall = parseExpression(); - vector> clauses; + std::vector> clauses; ASTNodeFactory successClauseFactory(*this); ASTPointer returnsParameters; @@ -1487,7 +1487,7 @@ ASTPointer Parser::parseTryStatement(ASTPointer const& ASTPointer successBlock = parseBlock(); successClauseFactory.setEndPositionFromNode(successBlock); clauses.emplace_back(successClauseFactory.createNode( - make_shared(), returnsParameters, successBlock + std::make_shared(), returnsParameters, successBlock )); do @@ -1506,7 +1506,7 @@ ASTPointer Parser::parseCatchClause() RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); expectToken(Token::Catch); - ASTPointer errorName = make_shared(); + ASTPointer errorName = std::make_shared(); ASTPointer errorParameters; if (m_scanner->currentToken() != Token::LBrace) { @@ -1674,17 +1674,17 @@ ASTPointer Parser::parseSimpleStatement(ASTPointer const& } // Now see whether we have a variable declaration or an expression. - tie(statementType, iap) = tryParseIndexAccessedPath(); + std::tie(statementType, iap) = tryParseIndexAccessedPath(); switch (statementType) { case LookAheadInfo::VariableDeclaration: { - vector> variables; + std::vector> variables; ASTPointer value; // We have already parsed something like `(,,,,a.b.c[2][3]` VarDeclParserOptions options; options.allowLocationSpecifier = true; - variables = vector>(emptyComponents, nullptr); + variables = std::vector>(emptyComponents, nullptr); variables.push_back(parseVariableDeclaration(options, typeNameFromIndexAccessStructure(iap))); while (m_scanner->currentToken() != Token::RParen) @@ -1704,7 +1704,7 @@ ASTPointer Parser::parseSimpleStatement(ASTPointer const& case LookAheadInfo::Expression: { // Complete parsing the expression in the current component. - vector> components(emptyComponents, nullptr); + std::vector> components(emptyComponents, nullptr); components.push_back(parseExpression(expressionFromIndexAccessStructure(iap))); while (m_scanner->currentToken() != Token::RParen) { @@ -1724,7 +1724,7 @@ ASTPointer Parser::parseSimpleStatement(ASTPointer const& } else { - tie(statementType, iap) = tryParseIndexAccessedPath(); + std::tie(statementType, iap) = tryParseIndexAccessedPath(); switch (statementType) { case LookAheadInfo::VariableDeclaration: @@ -1749,7 +1749,7 @@ bool Parser::IndexAccessedPath::empty() const } -pair Parser::tryParseIndexAccessedPath() +std::pair Parser::tryParseIndexAccessedPath() { // These two cases are very hard to distinguish: // x[7 * 20 + 3] a; and x[7 * 20 + 3] = 9; @@ -1763,7 +1763,7 @@ pair Parser::tryParseIndexAcce { case LookAheadInfo::VariableDeclaration: case LookAheadInfo::Expression: - return make_pair(statementType, IndexAccessedPath()); + return std::make_pair(statementType, IndexAccessedPath()); default: break; } @@ -1775,9 +1775,9 @@ pair Parser::tryParseIndexAcce IndexAccessedPath iap = parseIndexAccessedPath(); if (m_scanner->currentToken() == Token::Identifier || TokenTraits::isLocationSpecifier(m_scanner->currentToken())) - return make_pair(LookAheadInfo::VariableDeclaration, std::move(iap)); + return std::make_pair(LookAheadInfo::VariableDeclaration, std::move(iap)); else - return make_pair(LookAheadInfo::Expression, std::move(iap)); + return std::make_pair(LookAheadInfo::Expression, std::move(iap)); } ASTPointer Parser::parseVariableDeclarationStatement( @@ -1795,7 +1795,7 @@ ASTPointer Parser::parseVariableDeclarationStateme VarDeclParserOptions options; options.allowLocationSpecifier = true; - vector> variables; + std::vector> variables; variables.emplace_back(parseVariableDeclaration(options, _lookAheadArrayType)); nodeFactory.setEndPositionFromNode(variables.back()); @@ -2021,7 +2021,7 @@ ASTPointer Parser::parseLiteral() RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); Token initialToken = m_scanner->currentToken(); - ASTPointer value = make_shared(m_scanner->currentLiteral()); + ASTPointer value = std::make_shared(m_scanner->currentLiteral()); switch (initialToken) { @@ -2091,7 +2091,7 @@ ASTPointer Parser::parsePrimaryExpression() // Inside expressions "type" is the name of a special, globally-available function. nodeFactory.markEndPosition(); advance(); - expression = nodeFactory.createNode(make_shared("type")); + expression = nodeFactory.createNode(std::make_shared("type")); break; case Token::LParen: case Token::LBrack: @@ -2100,7 +2100,7 @@ ASTPointer Parser::parsePrimaryExpression() // Special cases: ()/[] is empty tuple/array type, (x) is not a real tuple, // (x,) is one-dimensional tuple, elements in arrays cannot be left out, only in tuples. advance(); - vector> components; + std::vector> components; Token oppositeToken = (token == Token::LParen ? Token::RParen : Token::RBrack); bool isArray = (token == Token::LBrack); @@ -2133,7 +2133,7 @@ ASTPointer Parser::parsePrimaryExpression() //used for casts unsigned firstSize; unsigned secondSize; - tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); + std::tie(firstSize, secondSize) = m_scanner->currentTokenInfo(); auto expressionType = nodeFactory.createNode( ElementaryTypeNameToken(m_scanner->currentToken(), firstSize, secondSize) ); @@ -2147,10 +2147,10 @@ ASTPointer Parser::parsePrimaryExpression() return expression; } -vector> Parser::parseFunctionCallListArguments() +std::vector> Parser::parseFunctionCallListArguments() { RecursionGuard recursionGuard(*this); - vector> arguments; + std::vector> arguments; if (m_scanner->currentToken() != Token::RParen) { arguments.push_back(parseExpression()); @@ -2226,17 +2226,17 @@ bool Parser::variableDeclarationStart() (currentToken == Token::Function && m_scanner->peekNextToken() == Token::LParen); } -optional Parser::findLicenseString(std::vector> const& _nodes) +std::optional Parser::findLicenseString(std::vector> const& _nodes) { // We circumvent the scanner here, because it skips non-docstring comments. - static regex const licenseNameRegex("([a-zA-Z0-9 ()+.-]+)"); - static regex const licenseDeclarationRegex("SPDX-License-Identifier:\\s*(.+?)([\n\r]|(\\*/))"); + static std::regex const licenseNameRegex("([a-zA-Z0-9 ()+.-]+)"); + static std::regex const licenseDeclarationRegex("SPDX-License-Identifier:\\s*(.+?)([\n\r]|(\\*/))"); // Search inside all parts of the source not covered by parsed nodes. // This will leave e.g. "global comments". using iter = std::string::const_iterator; - vector> sequencesToSearch; - string const& source = m_scanner->charStream().source(); + std::vector> sequencesToSearch; + std::string const& source = m_scanner->charStream().source(); sequencesToSearch.emplace_back(source.begin(), source.end()); for (ASTPointer const& node: _nodes) if (node->location().hasText()) @@ -2245,7 +2245,7 @@ optional Parser::findLicenseString(std::vector> cons sequencesToSearch.emplace_back(source.begin() + node->location().end, source.end()); } - vector licenseNames; + std::vector licenseNames; for (auto const& [start, end]: sequencesToSearch) { auto declarationsBegin = std::sregex_iterator(start, end, licenseDeclarationRegex); @@ -2254,14 +2254,14 @@ optional Parser::findLicenseString(std::vector> cons for (std::sregex_iterator declIt = declarationsBegin; declIt != declarationsEnd; ++declIt) if (!declIt->empty()) { - string license = boost::trim_copy(string((*declIt)[1])); + std::string license = boost::trim_copy(std::string((*declIt)[1])); licenseNames.emplace_back(std::move(license)); } } if (licenseNames.size() == 1) { - string const& license = licenseNames.front(); +std::string const& license = licenseNames.front(); if (regex_match(license, licenseNameRegex)) return license; else @@ -2340,7 +2340,7 @@ Parser::IndexAccessedPath Parser::parseIndexAccessedPath() { unsigned firstNum; unsigned secondNum; - tie(firstNum, secondNum) = m_scanner->currentTokenInfo(); + std::tie(firstNum, secondNum) = m_scanner->currentTokenInfo(); auto expressionType = ASTNodeFactory(*this).createNode( ElementaryTypeNameToken(m_scanner->currentToken(), firstNum, secondNum) ); @@ -2394,8 +2394,8 @@ ASTPointer Parser::typeNameFromIndexAccessStructure(Parser::IndexAcces } else { - vector path; - vector pathLocations; + std::vector path; + std::vector pathLocations; for (auto const& el: _iap.path) { @@ -2434,7 +2434,7 @@ ASTPointer Parser::expressionFromIndexAccessStructure( Identifier const& identifier = dynamic_cast(*_iap.path[i]); expression = nodeFactory.createNode( expression, - make_shared(identifier.name()), + std::make_shared(identifier.name()), identifier.location() ); } @@ -2454,7 +2454,7 @@ ASTPointer Parser::createEmptyParameterList() RecursionGuard recursionGuard(*this); ASTNodeFactory nodeFactory(*this); nodeFactory.setLocationEmpty(); - return nodeFactory.createNode(vector>()); + return nodeFactory.createNode(std::vector>()); } ASTPointer Parser::expectIdentifierToken() @@ -2468,7 +2468,7 @@ ASTPointer Parser::expectIdentifierTokenOrAddress() ASTPointer result; if (m_scanner->currentToken() == Token::Address) { - result = make_shared("address"); + result = std::make_shared("address"); advance(); } else @@ -2481,7 +2481,7 @@ ASTPointer Parser::expectIdentifierTokenOrAddress() ASTPointer Parser::getLiteralAndAdvance() { - ASTPointer identifier = make_shared(m_scanner->currentLiteral()); + ASTPointer identifier = std::make_shared(m_scanner->currentLiteral()); advance(); return identifier; } @@ -2504,7 +2504,7 @@ ASTPointer Parser::getStdlibImportPathAndAdvance() if (m_scanner->currentToken() == Token::Period) advance(); ASTPointer library = expectIdentifierToken(); - return make_shared(*std + "." + *library); + return std::make_shared(*std + "." + *library); } } diff --git a/scripts/check_style.sh b/scripts/check_style.sh index 7c85e671946a..7c1167490a58 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -31,6 +31,8 @@ NAMESPACE_STD_FREE_FILES=( libsolidity/codegen/* libsolidity/formal/* libsolidity/interface/* + libsolidity/lsp/* + libsolidity/parsing/* ) (