#include #include #include #include #include #include #include #include #include #include #include namespace vls { namespace { namespace Protocol = Void::LanguageServer::Protocol; using Protocol::as_object; using Protocol::as_string; using Protocol::find_member; const Json *member(const Json *value, std::string_view key) { const auto *object = as_object(value); return object ? find_member(*object, key) : nullptr; } // One writer serves both compiler notifications and request responses. Enqueueing a // publication never holds the input owner's lock across a potentially blocking stream write. class Output { public: Output(std::ostream &stream, bool asynchronous) : stream_(stream), asynchronous_(asynchronous) { if (asynchronous_) writer_ = std::jthread([this] { drain(); }); } ~Output() { finish(); } bool send(std::string body) { if (!asynchronous_) return bool(write_frame(stream_, body)); std::lock_guard lock{mutex_}; constexpr std::size_t limit = 32 * 1024 * 1024; if (finished_ || failed_ || queue_.size() >= 512 || body.size() > limit - bytes_) { failed_ = true; wake_.notify_one(); return false; } bytes_ += body.size(); queue_.push_back(std::move(body)); wake_.notify_one(); return true; } bool finish() { { std::lock_guard lock{mutex_}; finished_ = true; wake_.notify_one(); } if (writer_.joinable()) writer_.join(); return !failed_; } private: std::ostream &stream_; bool asynchronous_, finished_{}, failed_{}; std::mutex mutex_; std::condition_variable wake_; std::deque queue_; std::size_t bytes_{}; std::jthread writer_; void drain() { std::unique_lock lock{mutex_}; for (;;) { wake_.wait(lock, [&] { return !queue_.empty() || finished_ || failed_; }); if (failed_ || queue_.empty()) return; auto body = std::move(queue_.front()); queue_.pop_front(); lock.unlock(); bool ok{}; try { ok = bool(write_frame(stream_, body)); } catch (const std::exception &) { } lock.lock(); bytes_ -= body.size(); if (!ok) { failed_ = true; return; } } } }; Json error_payload(std::int64_t code, std::string_view message) { return Json{Json::Object{{"code", Json{code}}, {"message", Json{std::string{message}}}}}; } DispatchResult reply(const Json &id, std::string key, Json payload) { Json::Object envelope{{"jsonrpc", Json{std::string{"2.0"}}}, {"id", id}}; envelope.emplace(std::move(key), std::move(payload)); auto body = Protocol::serialize_json(Json{std::move(envelope)}); if (body) return {.response = std::move(*body), .exit_code = std::nullopt}; auto fallback = Protocol::serialize_json( Json{Json::Object{{"jsonrpc", Json{std::string{"2.0"}}}, {"id", id}, {"error", error_payload(-32603, "Internal error")}}}); if (fallback) return {.response = std::move(*fallback), .exit_code = std::nullopt, .diagnostic = "failed to encode response"}; return {.response = std::nullopt, .exit_code = 1, .diagnostic = "failed to encode response ID"}; } DispatchResult error(const Json &id, std::int64_t code, std::string_view message) { return reply(id, "error", error_payload(code, message)); } } // namespace Server::Server(WorkspaceLaunch launch, std::function send) : workspace_(launch) { if (launch.root && launch.diagnostics_profile && send) diagnostics_ = std::make_unique( *launch.root, std::move(launch.diagnostics_profile), workspace_, documents_, std::move(send)); } Server::~Server() = default; DispatchResult Server::handle(std::string_view body) { auto parsed = parse_json(body); if (!parsed) return error(Json{nullptr}, -32700, "Parse error"); const auto *object = std::get_if(&parsed->value); if (!object) return error(Json{nullptr}, -32600, "Invalid Request"); const auto *id_value = find_member(*object, "id"); const auto *method_value = find_member(*object, "method"); const auto *method = as_string(method_value); const auto *version = as_string(find_member(*object, "jsonrpc")); const auto *params = find_member(*object, "params"); const auto *result_value = find_member(*object, "result"); const auto *error_value = find_member(*object, "error"); // This shell issues no requests. Valid peer responses are unmatched and // must be ignored, including errors whose correlation ID is null. if (version && *version == "2.0" && !method_value && id_value && ((result_value != nullptr) != (error_value != nullptr))) { const bool valid_id = std::holds_alternative(id_value->value) || request_id(*id_value).has_value(); bool valid_payload = result_value != nullptr; if (error_value) { if (const auto *details = as_object(error_value)) { if (const auto *code = find_member(*details, "code"); code && as_string(find_member(*details, "message"))) { const auto checked = request_id(*code); valid_payload = checked && std::holds_alternative(*checked); } } } if (valid_id && valid_payload) return {}; } const bool notification = !id_value; Json id{nullptr}; if (id_value) { auto checked = request_id(*id_value); if (!checked) return error(Json{nullptr}, -32600, "Invalid Request"); id = Protocol::request_id_json(std::move(*checked)); } if (!version || *version != "2.0" || !method || result_value || error_value) { // Method-bearing objects without IDs are notifications, even when // malformed. They must never elicit a response. if (notification && method && *method == "textDocument/didChange" && state_ == State::running) { if (diagnostics_) diagnostics_->begin_update(); reject_change_envelope(documents_, params); if (diagnostics_) diagnostics_->finish_update(); return {.response = std::nullopt, .exit_code = std::nullopt, .diagnostic = "invalid didChange envelope"}; } if (notification && method_value) return {}; return error(id, -32600, "Invalid Request"); } if (notification) { if (*method == "exit") { if (diagnostics_) diagnostics_->stop(); return {.response = std::nullopt, .exit_code = state_ == State::shutdown ? 0 : 1}; } if (state_ == State::running) { if (*method == "workspace/didChangeWorkspaceFolders" || *method == "workspace/didChangeConfiguration") { if (diagnostics_) diagnostics_->begin_update(); auto updated = *method == "workspace/didChangeWorkspaceFolders" ? workspace_.update_folders(params) : workspace_.configure(params); if (diagnostics_) diagnostics_->finish_update(true); if (!updated) return {.response = std::nullopt, .exit_code = std::nullopt, .diagnostic = updated.error().substr(0, 256)}; return {}; } const bool change = *method == "textDocument/didOpen" || *method == "textDocument/didChange" || *method == "textDocument/didClose"; if (diagnostics_ && change) diagnostics_->begin_update(); auto synced = synchronize_document(documents_, *method, params); if (diagnostics_ && change) diagnostics_->finish_update(); if (!synced) return {.response = std::nullopt, .exit_code = std::nullopt, .diagnostic = synced.error().substr(0, 256)}; } return {}; } if (state_ == State::shutdown) return error(id, -32600, "Invalid Request"); if (state_ == State::awaiting_initialize && *method != "initialize") return error(id, -32002, "Server not initialized"); if (*method == "initialize") { if (state_ != State::awaiting_initialize) return error(id, -32600, "Invalid Request"); if (!params || !std::holds_alternative(params->value)) return error(id, -32602, "initialize params must be an object"); if (auto configured = workspace_.initialize(*params); !configured) return error(id, -32602, configured.error().substr(0, 256)); const auto encoding = negotiate_position_encoding(*params); if (!documents_.set_position_encoding(encoding)) return error(id, -32603, "Could not set document position encoding"); if (diagnostics_) { const auto *cap = member(member(member(params, "capabilities"), "textDocument"), "publishDiagnostics"); diagnostics_->set_version_support( Protocol::as_bool(member(cap, "versionSupport")).value_or(false)); const auto *edit = member(member(member(params, "capabilities"), "workspace"), "workspaceEdit"); diagnostics_->set_transactional_rename( Protocol::as_bool(member(edit, "documentChanges")).value_or(false)); } Json::Object sync{{"openClose", Json{true}}, {"change", Json{std::int64_t{2}}}}; Json::Object capabilities{ {"positionEncoding", Json{std::string{Void::LanguageServer::Documents::encoding_name(encoding)}}}, {"textDocumentSync", Json{std::move(sync)}}, {"workspace", Json{Json::Object{ {"workspaceFolders", Json{Json::Object{{"supported", Json{true}}, {"changeNotifications", Json{true}}}}}}}}}; if (diagnostics_ && diagnostics_->supports_occurrences()) { capabilities.emplace("hoverProvider", Json{true}); capabilities.emplace("definitionProvider", Json{true}); } if (diagnostics_) capabilities.emplace("completionProvider", Json{Json::Object{{"triggerCharacters", Json{Json::Array{}}}, {"resolveProvider", Json{true}}}}); if (diagnostics_ && diagnostics_->supports_occurrences()) capabilities.emplace("signatureHelpProvider", Json{Json::Object{{"triggerCharacters", Json{Json::Array{Json{std::string{"("}}, Json{std::string{","}}}}}}}); Json::Object info{{"name", Json{std::string{"VoidLanguageServer"}}}, {"version", Json{std::string{server_version}}}}; auto initialized = reply(id, "result", Json{Json::Object{{"capabilities", Json{std::move(capabilities)}}, {"serverInfo", Json{std::move(info)}}}}); if (initialized.diagnostic.empty()) state_ = State::running; return initialized; } if (params && !std::holds_alternative(params->value) && !std::holds_alternative(params->value) && !std::holds_alternative(params->value)) return error(id, -32600, "Invalid Request"); if (*method == "voidLanguageServer/providerStatus") { auto status = workspace_.provider_status(params); if (!status) return error(id, -32602, status.error().substr(0, 256)); return reply(id, "result", std::move(*status)); } if (*method == "voidLanguageServer/analysisStatus") { const auto *uri = as_string(member(member(params, "textDocument"), "uri")); if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri)) return error(id, -32602, "Expected textDocument.uri"); return reply(id, "result", diagnostics_ ? diagnostics_->status(*uri) : Json{Json::Object{{"state", Json{std::string{"disabled"}}}}}); } if (*method == "textDocument/hover" || *method == "textDocument/definition" || *method == "textDocument/signatureHelp") { if (!diagnostics_ || !diagnostics_->supports_occurrences()) return error(id, -32601, "Method not found"); const auto *uri = as_string(member(member(params, "textDocument"), "uri")); const auto *position = member(params, "position"); const auto *line = position ? member(position, "line") : nullptr; const auto *character = position ? member(position, "character") : nullptr; const auto *line_value = line ? std::get_if(&line->value) : nullptr; const auto *character_value = character ? std::get_if(&character->value) : nullptr; if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !line_value || !character_value || *line_value < 0 || *character_value < 0 || *line_value > Void::LanguageServer::Documents::kMaxPositionValue || *character_value > Void::LanguageServer::Documents::kMaxPositionValue) return error(id, -32602, "Expected textDocument.uri and a bounded position"); const Void::LanguageServer::Documents::Position selected{ static_cast(*line_value), static_cast(*character_value)}; auto result = *method == "textDocument/hover" ? diagnostics_->hover(*uri, selected) : *method == "textDocument/definition" ? diagnostics_->definition(*uri, selected) : diagnostics_->signature_help(*uri, selected); return reply(id, "result", std::move(result)); } if (*method == "completionItem/resolve") { if (!diagnostics_) return error(id, -32601, "Method not found"); if (!params) return error(id, -32602, "Expected a completion item"); return reply(id, "result", diagnostics_->completion_resolve(*params)); } if (*method == "textDocument/completion") { if (!diagnostics_) return error(id, -32601, "Method not found"); const auto *uri = as_string(member(member(params, "textDocument"), "uri")); const auto *position = member(params, "position"); const auto *line = position ? member(position, "line") : nullptr; const auto *character = position ? member(position, "character") : nullptr; const auto *line_value = line ? std::get_if(&line->value) : nullptr; const auto *character_value = character ? std::get_if(&character->value) : nullptr; if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !line_value || !character_value || *line_value < 0 || *character_value < 0 || *line_value > Void::LanguageServer::Documents::kMaxPositionValue || *character_value > Void::LanguageServer::Documents::kMaxPositionValue) return error(id, -32602, "Expected textDocument.uri and a bounded position"); return reply( id, "result", diagnostics_->completion(*uri, {static_cast(*line_value), static_cast(*character_value)})); } if (*method == "textDocument/references" || *method == "textDocument/prepareRename" || *method == "textDocument/rename") { if (!diagnostics_ || !diagnostics_->supports_occurrences()) return error(id, -32601, "Method not found"); const auto *uri = as_string(member(member(params, "textDocument"), "uri")); const auto *position = member(params, "position"); const auto *line = position ? member(position, "line") : nullptr; const auto *character = position ? member(position, "character") : nullptr; const auto *line_value = line ? std::get_if(&line->value) : nullptr; const auto *character_value = character ? std::get_if(&character->value) : nullptr; if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !line_value || !character_value || *line_value < 0 || *character_value < 0 || *line_value > Void::LanguageServer::Documents::kMaxPositionValue || *character_value > Void::LanguageServer::Documents::kMaxPositionValue) return error(id, -32602, "Expected textDocument.uri and a bounded position"); const Void::LanguageServer::Documents::Position selected{ static_cast(*line_value), static_cast(*character_value)}; semantic::EditorDiagnostics::NavigationReply navigation; if (*method == "textDocument/references") navigation = diagnostics_->references(*uri, selected); else if (*method == "textDocument/prepareRename") navigation = diagnostics_->prepare_rename(*uri, selected); else { const auto *name = as_string(member(params, "newName")); if (!name || name->size() > 256) return error(id, -32602, "Expected a bounded newName"); navigation = diagnostics_->rename(*uri, selected, *name); } if (navigation.refusal) return error(id, -32803, navigation.refusal->substr(0, 256)); return reply(id, "result", std::move(navigation.result)); } if (*method == "workspace/symbol") { if (!diagnostics_ || !diagnostics_->supports_occurrences()) return error(id, -32601, "Method not found"); const auto *query = as_string(member(params, "query")); if (!query || query->size() > 256) return error(id, -32602, "Expected a bounded workspace symbol query"); return reply(id, "result", diagnostics_->workspace_symbols(*query)); } if (*method == "shutdown") { if (params && !std::holds_alternative(params->value)) return error(id, -32602, "shutdown takes no params"); auto stopped = reply(id, "result", Json{nullptr}); if (diagnostics_) diagnostics_->stop(); if (stopped.diagnostic.empty()) state_ = State::shutdown; return stopped; } return error(id, -32601, "Method not found"); } int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnostics, FrameLimits limits, WorkspaceLaunch launch) { try { Output egress{output, bool(launch.diagnostics_profile)}; Server server{std::move(launch), [&](std::string body) { return egress.send(std::move(body)); }}; for (;;) { auto frame = read_frame(input, limits); if (!frame) { diagnostics << "vls: " << frame.error() << '\n'; return 1; } if (!*frame) { diagnostics << "vls: unexpected EOF before exit notification\n"; return 1; } auto dispatched = server.handle(**frame); if (!dispatched.diagnostic.empty()) diagnostics << "vls: " << dispatched.diagnostic << '\n'; if (dispatched.response) { if (!egress.send(std::move(*dispatched.response))) { diagnostics << "vls: failed to write protocol frame\n"; return 1; } } if (dispatched.exit_code) return egress.finish() ? *dispatched.exit_code : 1; } } catch (const std::exception &) { diagnostics << "vls: failed to process protocol stream\n"; return 1; } } } // namespace vls