Skip to content

Commit

Permalink
Purge using namespace from libsolidity/lsp and parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
nikola-matic committed Aug 15, 2023
1 parent 579259d commit 364a446
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 211 deletions.
9 changes: 3 additions & 6 deletions libsolidity/lsp/DocumentHoverHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@

namespace solidity::lsp
{

using namespace std;

using namespace solidity::lsp;
using namespace solidity::langutil;
using namespace solidity::frontend;
Expand All @@ -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())
{
Expand Down
21 changes: 10 additions & 11 deletions libsolidity/lsp/FileRepository.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@

#include <fmt/format.h>

using namespace std;
using namespace solidity;
using namespace solidity::lsp;
using namespace solidity::frontend;
Expand All @@ -54,11 +53,11 @@ void FileRepository::setIncludePaths(std::vector<boost::filesystem::path> _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
Expand Down Expand Up @@ -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.
Expand All @@ -110,9 +109,9 @@ Result<boost::filesystem::path> FileRepository::tryResolvePath(std::string const
)
return boost::filesystem::path(_strippedSourceUnitName);

vector<boost::filesystem::path> candidates;
vector<reference_wrapper<boost::filesystem::path const>> prefixes = {m_basePath};
prefixes += (m_includePaths | ranges::to<vector<reference_wrapper<boost::filesystem::path const>>>);
std::vector<boost::filesystem::path> candidates;
std::vector<std::reference_wrapper<boost::filesystem::path const>> prefixes = {m_basePath};
prefixes += (m_includePaths | ranges::to<std::vector<std::reference_wrapper<boost::filesystem::path const>>>);
auto const defaultInclude = m_basePath / "node_modules";
if (m_includePaths.empty())
prefixes.emplace_back(defaultInclude);
Expand Down Expand Up @@ -148,7 +147,7 @@ Result<boost::filesystem::path> 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),
Expand All @@ -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<boost::filesystem::path> const resolvedPath = tryResolvePath(strippedSourceUnitName);
if (!resolvedPath.message().empty())
return ReadCallback::Result{false, resolvedPath.message()};
Expand Down
5 changes: 2 additions & 3 deletions libsolidity/lsp/GotoDefinition.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,14 @@
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::lsp;
using namespace std;

void GotoDefinition::operator()(MessageID _id, Json::Value const& _args)
{
auto const [sourceUnitName, lineColumn] = extractSourceUnitNameAndLineColumn(_args);

ASTNode const* sourceNode = m_server.astNodeAtSourceLocation(sourceUnitName, lineColumn);

vector<SourceLocation> locations;
std::vector<SourceLocation> locations;
if (auto const* expression = dynamic_cast<Expression const*>(sourceNode))
{
// Handles all expressions that can have one or more declaration annotation.
Expand All @@ -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<string const>(path)});
locations.emplace_back(SourceLocation{0, 0, std::make_shared<std::string const>(path)});
}

Json::Value reply = Json::arrayValue;
Expand Down
7 changes: 3 additions & 4 deletions libsolidity/lsp/HandlerBase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -52,10 +51,10 @@ Json::Value HandlerBase::toJson(SourceLocation const& _location) const
return item;
}

pair<string, LineColumn> HandlerBase::extractSourceUnitNameAndLineColumn(Json::Value const& _args) const
std::pair<std::string, LineColumn> 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) <<
Expand Down
61 changes: 30 additions & 31 deletions libsolidity/lsp/LanguageServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@

#include <fmt/format.h>

using namespace std;
using namespace std::string_literals;
using namespace std::placeholders;

Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -196,7 +195,7 @@ void LanguageServer::changeConfiguration(Json::Value const& _settings)
int typeFailureCount = 0;
if (jsonIncludePaths.isArray())
{
vector<boost::filesystem::path> includePaths;
std::vector<boost::filesystem::path> includePaths;
for (Json::Value const& jsonPath: jsonIncludePaths)
{
if (jsonPath.isString())
Expand All @@ -214,9 +213,9 @@ void LanguageServer::changeConfiguration(Json::Value const& _settings)
}
}

vector<boost::filesystem::path> LanguageServer::allSolidityFilesFromProject() const
std::vector<boost::filesystem::path> LanguageServer::allSolidityFilesFromProject() const
{
vector<fs::path> collectedPaths{};
std::vector<fs::path> 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).
Expand All @@ -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)
Expand All @@ -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))
Expand All @@ -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<string, Json::Value> diagnosticsBySourceUnit;
for (string const& sourceUnitName: m_fileRepository.sourceUnits() | ranges::views::keys)
std::map<std::string, Json::Value> 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<Error const> const& error: m_compilerStack.errors())
for (std::shared_ptr<Error const> const& error: m_compilerStack.errors())
{
SourceLocation const* location = error->sourceLocation();
if (!location || !location->sourceName)
Expand All @@ -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);
Expand All @@ -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();
Expand All @@ -336,13 +335,13 @@ bool LanguageServer::run()
MessageID id;
try
{
optional<Json::Value> const jsonMessage = m_client.receive();
std::optional<Json::Value> 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));

Expand Down Expand Up @@ -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();
Expand All @@ -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
Expand All @@ -440,7 +439,7 @@ void LanguageServer::semanticTokensFull(MessageID _id, Json::Value const& _args)

compile();

auto const sourceName = m_fileRepository.uriToSourceUnitName(uri.as<string>());
auto const sourceName = m_fileRepository.uriToSourceUnitName(uri.as<std::string>());
SourceUnit const& ast = m_compilerStack.ast(sourceName);
m_compilerStack.charStream(sourceName);
Json::Value data = SemanticTokensBuilder().build(ast, m_compilerStack.charStream(sourceName));
Expand All @@ -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")
Expand All @@ -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();
Expand All @@ -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"])
{
Expand All @@ -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<SourceLocation> change = parseRange(m_fileRepository, sourceUnitName, jsonContentChange["range"]);
std::optional<SourceLocation> 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<size_t>(change->start), static_cast<size_t>(change->end - change->start), std::move(text));
text = std::move(buffer);
}
Expand All @@ -542,25 +541,25 @@ 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();
}

ASTNode const* LanguageServer::astNodeAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos)
{
return get<ASTNode const*>(astNodeAndOffsetAtSourceLocation(_sourceUnitName, _filePos));
return std::get<ASTNode const*>(astNodeAndOffsetAtSourceLocation(_sourceUnitName, _filePos));
}

tuple<ASTNode const*, int> LanguageServer::astNodeAndOffsetAtSourceLocation(std::string const& _sourceUnitName, LineColumn const& _filePos)
std::tuple<ASTNode const*, int> 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<int> sourcePos = m_compilerStack.charStream(_sourceUnitName).translateLineColumnToPosition(_filePos);
std::optional<int> sourcePos = m_compilerStack.charStream(_sourceUnitName).translateLineColumnToPosition(_filePos);
if (!sourcePos)
return {nullptr, -1};

Expand Down
Loading

0 comments on commit 364a446

Please sign in to comment.