Refactor to plugin architecture with B3 CLI UX, C2 smoke tests, C3 CI scripts
Architecture overhaul (Wave 1-4 collaborative work): - Migrated dstalk-core from monolithic api.cpp to plugin-based design with host/service_registry/event_bus/plugin_loader and topological initialization. - Split public headers into dstalk_host.h / dstalk_services.h / dstalk_lsp.h / dstalk_types.h; deleted obsolete dstalk_api.h and inlined TLS/file/net code now provided by plugins. - Added 9 plugins: deepseek, anthropic, network, session, context, tools, config, file-io, lsp; AI plugins register as "ai.<provider>" services. B3 CLI interaction enhancement: - Prompt now shows current model name (A1). - /status command prints model/base_url/api_key (sanitized: shown only as set/unset)/services readiness (A2). - SIGINT/Ctrl+C handled on POSIX (signal) and Windows (SetConsoleCtrlHandler); /quit no longer std::exit(0) but sets a quit flag so dstalk_shutdown runs exactly once via natural control flow (B1+B2). - Cross-DLL free fixed: print_file uses dstalk_free instead of std::free (B4). - --batch mode plus isatty auto-detection for piped stdin (C1). - fgets truncation detection with friendly error and stdin draining (C3). - Distinct exit codes (init/AI/service-unavailable) (C4). - /model rejects empty model name (C5). C2 smoke test extension: - 4 new test blocks: null-safety (file_io/session/tools/config), escape-boundary round-trip, tools->execute call chain, session robustness (add(nullptr), clear -> token_count == 0). C3 CI build scripts: - scripts/ci-build.sh and scripts/ci-build.bat invoke cmake configure + parallel build + ctest, suitable for GitHub Actions. Build verified: dstalk-cli compiles, smoke test passes via ctest. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
38
plugins/lsp/CMakeLists.txt
Normal file
38
plugins/lsp/CMakeLists.txt
Normal file
@@ -0,0 +1,38 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
|
||||
# ============================================================
|
||||
# plugin-lsp — LSP (Language Server Protocol) 服务
|
||||
# 自行管理子进程,无外部服务依赖
|
||||
# ============================================================
|
||||
|
||||
add_library(plugin-lsp SHARED
|
||||
src/lsp_plugin.cpp
|
||||
)
|
||||
|
||||
target_include_directories(plugin-lsp PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/dstalk-core/include
|
||||
)
|
||||
|
||||
target_link_libraries(plugin-lsp PRIVATE dstalk)
|
||||
|
||||
# Boost.JSON 用于 JSON-RPC 消息构建/解析
|
||||
find_package(Boost REQUIRED CONFIG)
|
||||
target_link_libraries(plugin-lsp PRIVATE boost::boost)
|
||||
|
||||
target_compile_definitions(plugin-lsp PRIVATE
|
||||
BOOST_ALL_NO_LIB
|
||||
BOOST_ERROR_CODE_HEADER_ONLY
|
||||
BOOST_JSON_HEADER_ONLY
|
||||
)
|
||||
|
||||
# POSIX 平台需要 pthread (用于 std::thread)
|
||||
if(NOT WIN32)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(plugin-lsp PRIVATE Threads::Threads)
|
||||
endif()
|
||||
|
||||
set_target_properties(plugin-lsp PROPERTIES
|
||||
PREFIX ""
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins"
|
||||
)
|
||||
733
plugins/lsp/src/lsp_plugin.cpp
Normal file
733
plugins/lsp/src/lsp_plugin.cpp
Normal file
@@ -0,0 +1,733 @@
|
||||
/*
|
||||
* plugin-lsp — LSP (Language Server Protocol) 服务
|
||||
*
|
||||
* 自行管理语言服务器子进程,使用 JSON-RPC 2.0 over stdio 通信。
|
||||
* 无外部服务依赖(不依赖 http/config 等其他插件)。
|
||||
*/
|
||||
|
||||
#include "dstalk/dstalk_host.h"
|
||||
#include "dstalk/dstalk_services.h"
|
||||
|
||||
#include <boost/json.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
// ============================================================================
|
||||
// 平台相关 — 子进程管理 (内嵌 subprocess::Process)
|
||||
// ============================================================================
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <cerrno>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <fcntl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace json = boost::json;
|
||||
|
||||
// ============================================================================
|
||||
// 全局指针
|
||||
// ============================================================================
|
||||
static const dstalk_host_api_t* g_host = nullptr;
|
||||
|
||||
// ============================================================================
|
||||
// 子进程封装 (内嵌 subprocess.hpp)
|
||||
// ============================================================================
|
||||
struct Process {
|
||||
#ifdef _WIN32
|
||||
HANDLE hProcess = INVALID_HANDLE_VALUE;
|
||||
HANDLE hThread = INVALID_HANDLE_VALUE;
|
||||
HANDLE hStdIn = INVALID_HANDLE_VALUE;
|
||||
HANDLE hStdOut = INVALID_HANDLE_VALUE;
|
||||
#else
|
||||
pid_t pid = -1;
|
||||
int stdin_fd = -1;
|
||||
int stdout_fd = -1;
|
||||
#endif
|
||||
|
||||
bool start(const char* cmd) {
|
||||
if (!cmd || !cmd[0]) return false;
|
||||
stop();
|
||||
|
||||
#ifdef _WIN32
|
||||
SECURITY_ATTRIBUTES sa = {};
|
||||
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
|
||||
sa.bInheritHandle = TRUE;
|
||||
|
||||
HANDLE child_stdin_read = INVALID_HANDLE_VALUE;
|
||||
HANDLE child_stdout_write = INVALID_HANDLE_VALUE;
|
||||
|
||||
if (!CreatePipe(&child_stdin_read, &hStdIn, &sa, 0)) goto win32_fail;
|
||||
if (!SetHandleInformation(hStdIn, HANDLE_FLAG_INHERIT, 0)) goto win32_fail;
|
||||
if (!CreatePipe(&hStdOut, &child_stdout_write, &sa, 0)) goto win32_fail;
|
||||
if (!SetHandleInformation(hStdOut, HANDLE_FLAG_INHERIT, 0)) goto win32_fail;
|
||||
|
||||
{
|
||||
STARTUPINFOW si = {};
|
||||
si.cb = sizeof(STARTUPINFOW);
|
||||
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
|
||||
si.wShowWindow = SW_HIDE;
|
||||
si.hStdInput = child_stdin_read;
|
||||
si.hStdOutput = child_stdout_write;
|
||||
si.hStdError = child_stdout_write;
|
||||
|
||||
PROCESS_INFORMATION pi = {};
|
||||
std::string cmd_copy(cmd);
|
||||
wchar_t wcmd[4096] = {};
|
||||
if (MultiByteToWideChar(CP_UTF8, 0, cmd_copy.c_str(), -1, wcmd, 4096) == 0)
|
||||
goto win32_fail;
|
||||
|
||||
if (!CreateProcessW(nullptr, wcmd, nullptr, nullptr, TRUE,
|
||||
CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi))
|
||||
goto win32_fail;
|
||||
|
||||
hProcess = pi.hProcess;
|
||||
hThread = pi.hThread;
|
||||
}
|
||||
|
||||
CloseHandle(child_stdin_read);
|
||||
CloseHandle(child_stdout_write);
|
||||
return true;
|
||||
|
||||
win32_fail:
|
||||
if (child_stdin_read != INVALID_HANDLE_VALUE) CloseHandle(child_stdin_read);
|
||||
if (child_stdout_write != INVALID_HANDLE_VALUE) CloseHandle(child_stdout_write);
|
||||
if (hStdIn != INVALID_HANDLE_VALUE) { CloseHandle(hStdIn); hStdIn = INVALID_HANDLE_VALUE; }
|
||||
if (hStdOut != INVALID_HANDLE_VALUE) { CloseHandle(hStdOut); hStdOut = INVALID_HANDLE_VALUE; }
|
||||
if (hProcess != INVALID_HANDLE_VALUE) { CloseHandle(hProcess); hProcess = INVALID_HANDLE_VALUE; }
|
||||
if (hThread != INVALID_HANDLE_VALUE) { CloseHandle(hThread); hThread = INVALID_HANDLE_VALUE; }
|
||||
return false;
|
||||
|
||||
#else
|
||||
int pin[2] = {-1, -1};
|
||||
int pout[2] = {-1, -1};
|
||||
|
||||
if (pipe(pin) != 0) goto posix_fail;
|
||||
if (pipe(pout) != 0) goto posix_fail;
|
||||
|
||||
pid = fork();
|
||||
if (pid < 0) goto posix_fail;
|
||||
|
||||
if (pid == 0) {
|
||||
dup2(pin[0], STDIN_FILENO);
|
||||
close(pin[0]); close(pin[1]);
|
||||
dup2(pout[1], STDOUT_FILENO);
|
||||
close(pout[0]); close(pout[1]);
|
||||
|
||||
int max_fd = static_cast<int>(sysconf(_SC_OPEN_MAX));
|
||||
if (max_fd > 3) {
|
||||
for (int i = 3; i < max_fd; ++i) close(i);
|
||||
}
|
||||
|
||||
char* argv[64] = {};
|
||||
int argc = 0;
|
||||
char* cmd_copy = strdup(cmd);
|
||||
char* token = strtok(cmd_copy, " \t");
|
||||
while (token && argc < 63) {
|
||||
argv[argc++] = token;
|
||||
token = strtok(nullptr, " \t");
|
||||
}
|
||||
argv[argc] = nullptr;
|
||||
execvp(argv[0], argv);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
close(pin[0]);
|
||||
close(pout[1]);
|
||||
stdin_fd = pin[1];
|
||||
stdout_fd = pout[0];
|
||||
return true;
|
||||
|
||||
posix_fail:
|
||||
if (pin[0] != -1) close(pin[0]);
|
||||
if (pin[1] != -1) close(pin[1]);
|
||||
if (pout[0] != -1) close(pout[0]);
|
||||
if (pout[1] != -1) close(pout[1]);
|
||||
stdin_fd = -1;
|
||||
stdout_fd = -1;
|
||||
pid = -1;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void stop() {
|
||||
#ifdef _WIN32
|
||||
if (hProcess != INVALID_HANDLE_VALUE) {
|
||||
WaitForSingleObject(hProcess, 2000);
|
||||
TerminateProcess(hProcess, 1);
|
||||
CloseHandle(hProcess); hProcess = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if (hThread != INVALID_HANDLE_VALUE) { CloseHandle(hThread); hThread = INVALID_HANDLE_VALUE; }
|
||||
if (hStdIn != INVALID_HANDLE_VALUE) { CloseHandle(hStdIn); hStdIn = INVALID_HANDLE_VALUE; }
|
||||
if (hStdOut != INVALID_HANDLE_VALUE) { CloseHandle(hStdOut); hStdOut = INVALID_HANDLE_VALUE; }
|
||||
#else
|
||||
if (pid > 0) {
|
||||
kill(pid, SIGTERM);
|
||||
int status = 0;
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
if (waitpid(pid, &status, WNOHANG) > 0) break;
|
||||
usleep(100000);
|
||||
}
|
||||
if (waitpid(pid, &status, WNOHANG) == 0) {
|
||||
kill(pid, SIGKILL);
|
||||
waitpid(pid, &status, 0);
|
||||
}
|
||||
pid = -1;
|
||||
}
|
||||
if (stdin_fd != -1) { close(stdin_fd); stdin_fd = -1; }
|
||||
if (stdout_fd != -1) { close(stdout_fd); stdout_fd = -1; }
|
||||
#endif
|
||||
}
|
||||
|
||||
bool write(const std::string& data) {
|
||||
if (data.empty()) return true;
|
||||
#ifdef _WIN32
|
||||
if (hStdIn == INVALID_HANDLE_VALUE) return false;
|
||||
DWORD written = 0;
|
||||
return WriteFile(hStdIn, data.c_str(), static_cast<DWORD>(data.size()), &written, nullptr)
|
||||
&& written == data.size();
|
||||
#else
|
||||
if (stdin_fd < 0) return false;
|
||||
size_t total = 0;
|
||||
const char* buf = data.c_str();
|
||||
size_t len = data.size();
|
||||
while (total < len) {
|
||||
ssize_t n = ::write(stdin_fd, buf + total, len - total);
|
||||
if (n <= 0) return false;
|
||||
total += static_cast<size_t>(n);
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool read_line(std::string& line) {
|
||||
line.clear();
|
||||
#ifdef _WIN32
|
||||
if (hStdOut == INVALID_HANDLE_VALUE) return false;
|
||||
char ch; DWORD nread = 0;
|
||||
while (true) {
|
||||
if (!ReadFile(hStdOut, &ch, 1, &nread, nullptr)) return false;
|
||||
if (nread == 0) return false;
|
||||
line += ch;
|
||||
if (ch == '\n') return true;
|
||||
}
|
||||
#else
|
||||
if (stdout_fd < 0) return false;
|
||||
char ch;
|
||||
while (true) {
|
||||
ssize_t n = ::read(stdout_fd, &ch, 1);
|
||||
if (n <= 0) return false;
|
||||
line += ch;
|
||||
if (ch == '\n') return true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool read_bytes(std::string& buf, int count) {
|
||||
if (count <= 0) { buf.clear(); return true; }
|
||||
#ifdef _WIN32
|
||||
if (hStdOut == INVALID_HANDLE_VALUE) return false;
|
||||
buf.resize(static_cast<size_t>(count) + 1);
|
||||
DWORD total = 0, nread = 0;
|
||||
while (total < static_cast<DWORD>(count)) {
|
||||
if (!ReadFile(hStdOut, const_cast<char*>(buf.data()) + total,
|
||||
static_cast<DWORD>(count) - total, &nread, nullptr))
|
||||
return false;
|
||||
if (nread == 0) return false;
|
||||
total += nread;
|
||||
}
|
||||
buf[count] = '\0';
|
||||
buf.resize(count);
|
||||
return true;
|
||||
#else
|
||||
if (stdout_fd < 0) return false;
|
||||
buf.resize(count);
|
||||
size_t total = 0;
|
||||
while (total < static_cast<size_t>(count)) {
|
||||
ssize_t n = ::read(stdout_fd, const_cast<char*>(buf.data()) + total,
|
||||
static_cast<size_t>(count) - total);
|
||||
if (n <= 0) return false;
|
||||
total += static_cast<size_t>(n);
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// LSP 状态(静态单例)
|
||||
// ============================================================================
|
||||
struct LspState {
|
||||
Process proc;
|
||||
std::atomic<bool> running{false};
|
||||
std::string language;
|
||||
|
||||
std::atomic<int> next_id{1};
|
||||
|
||||
// 响应用于同步等待
|
||||
std::mutex mutex;
|
||||
std::condition_variable cv;
|
||||
std::unordered_map<int, std::string> pending_responses;
|
||||
|
||||
// 诊断缓存: URI -> JSON 字符串
|
||||
std::unordered_map<std::string, std::string> diagnostics;
|
||||
|
||||
// 读取线程
|
||||
std::thread reader_thread;
|
||||
};
|
||||
static LspState g_lsp;
|
||||
|
||||
// ============================================================================
|
||||
// 辅助函数
|
||||
// ============================================================================
|
||||
|
||||
static std::string_view trim(std::string_view sv) {
|
||||
while (!sv.empty() && (sv.front() == ' ' || sv.front() == '\t' ||
|
||||
sv.front() == '\r' || sv.front() == '\n'))
|
||||
sv.remove_prefix(1);
|
||||
while (!sv.empty() && (sv.back() == ' ' || sv.back() == '\t' ||
|
||||
sv.back() == '\r' || sv.back() == '\n'))
|
||||
sv.remove_suffix(1);
|
||||
return sv;
|
||||
}
|
||||
|
||||
static std::string frame_message(const std::string& body) {
|
||||
std::string frame;
|
||||
frame.reserve(64 + body.size());
|
||||
frame += "Content-Length: ";
|
||||
frame += std::to_string(body.size());
|
||||
frame += "\r\n\r\n";
|
||||
frame += body;
|
||||
return frame;
|
||||
}
|
||||
|
||||
static int parse_content_length(const std::string& line) {
|
||||
auto sv = trim(std::string_view(line));
|
||||
const char prefix[] = "Content-Length:";
|
||||
const size_t prefix_len = sizeof(prefix) - 1;
|
||||
|
||||
if (sv.size() <= prefix_len) return -1;
|
||||
for (size_t i = 0; i < prefix_len; ++i) {
|
||||
if (std::tolower(static_cast<unsigned char>(sv[i])) !=
|
||||
std::tolower(static_cast<unsigned char>(prefix[i])))
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::string_view num_sv = sv.substr(prefix_len);
|
||||
while (!num_sv.empty() && (num_sv.front() == ' ' || num_sv.front() == '\t'))
|
||||
num_sv.remove_prefix(1);
|
||||
|
||||
try { return std::stoi(std::string(num_sv)); }
|
||||
catch (...) { return -1; }
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// JSON-RPC 消息发送
|
||||
// ============================================================================
|
||||
|
||||
static int send_request(const std::string& method, const json::object& params) {
|
||||
int id = g_lsp.next_id.fetch_add(1);
|
||||
|
||||
json::object msg;
|
||||
msg["jsonrpc"] = "2.0";
|
||||
msg["id"] = id;
|
||||
msg["method"] = method;
|
||||
msg["params"] = params;
|
||||
|
||||
std::string body = json::serialize(msg);
|
||||
g_lsp.proc.write(frame_message(body));
|
||||
return id;
|
||||
}
|
||||
|
||||
static void send_notification(const std::string& method, const json::object& params) {
|
||||
json::object msg;
|
||||
msg["jsonrpc"] = "2.0";
|
||||
msg["method"] = method;
|
||||
msg["params"] = params;
|
||||
|
||||
std::string body = json::serialize(msg);
|
||||
g_lsp.proc.write(frame_message(body));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 消息处理
|
||||
// ============================================================================
|
||||
|
||||
static void handle_message(const std::string& body) {
|
||||
json::value val;
|
||||
try { val = json::parse(body); }
|
||||
catch (...) { return; }
|
||||
|
||||
json::object msg;
|
||||
try { msg = val.as_object(); }
|
||||
catch (...) { return; }
|
||||
|
||||
if (msg.contains("id") && !msg.contains("method")) {
|
||||
// 响应 (有 id, 无 method)
|
||||
int id = static_cast<int>(msg["id"].as_int64());
|
||||
std::lock_guard<std::mutex> lock(g_lsp.mutex);
|
||||
g_lsp.pending_responses[id] = body;
|
||||
g_lsp.cv.notify_all();
|
||||
|
||||
} else if (msg.contains("method") && !msg.contains("id")) {
|
||||
// 通知 (有 method, 无 id)
|
||||
std::string method;
|
||||
try { method = json::value_to<std::string>(msg["method"]); }
|
||||
catch (...) { return; }
|
||||
|
||||
if (method == "textDocument/publishDiagnostics") {
|
||||
if (!msg.contains("params")) return;
|
||||
auto params = msg["params"].as_object();
|
||||
if (!params.contains("uri")) return;
|
||||
|
||||
std::string uri = json::value_to<std::string>(params["uri"]);
|
||||
std::string diag_json;
|
||||
if (params.contains("diagnostics"))
|
||||
diag_json = json::serialize(params["diagnostics"]);
|
||||
else
|
||||
diag_json = "[]";
|
||||
|
||||
std::lock_guard<std::mutex> lock(g_lsp.mutex);
|
||||
g_lsp.diagnostics[uri] = diag_json;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 读取线程主循环
|
||||
// ============================================================================
|
||||
|
||||
static void reader_loop() {
|
||||
while (g_lsp.running) {
|
||||
std::string header_line;
|
||||
if (!g_lsp.proc.read_line(header_line)) break;
|
||||
|
||||
int content_length = parse_content_length(header_line);
|
||||
if (content_length < 0) continue;
|
||||
|
||||
// 跳过后续头直到空行 (\r\n 换行被视为非空行,只检查空行)
|
||||
while (true) {
|
||||
std::string line;
|
||||
if (!g_lsp.proc.read_line(line)) break;
|
||||
auto sv = trim(std::string_view(line));
|
||||
if (sv.empty()) break;
|
||||
}
|
||||
|
||||
std::string body;
|
||||
if (!g_lsp.proc.read_bytes(body, content_length)) break;
|
||||
|
||||
handle_message(body);
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(g_lsp.mutex);
|
||||
g_lsp.running = false;
|
||||
g_lsp.cv.notify_all();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// LSP 服务 vtable 实现 (定义在 vtable 变量之前)
|
||||
// ============================================================================
|
||||
|
||||
static int g_lsp_impl_stop();
|
||||
|
||||
static int g_lsp_impl_start(const char* server_cmd, const char* language) {
|
||||
if (!server_cmd || !server_cmd[0]) return -1;
|
||||
|
||||
// 如果已在运行, 先停止
|
||||
if (g_lsp.running) {
|
||||
g_lsp_impl_stop();
|
||||
}
|
||||
|
||||
g_lsp.language = language ? language : "";
|
||||
|
||||
// 启动进程
|
||||
if (!g_lsp.proc.start(server_cmd)) {
|
||||
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] failed to start: %s", server_cmd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 重置 ID 计数器
|
||||
g_lsp.next_id = 1;
|
||||
|
||||
// 启动读取线程
|
||||
g_lsp.running = true;
|
||||
g_lsp.reader_thread = std::thread(reader_loop);
|
||||
|
||||
// 构建 initialize 参数
|
||||
json::object text_doc_caps;
|
||||
{
|
||||
json::object hover;
|
||||
hover["dynamicRegistration"] = false;
|
||||
text_doc_caps["hover"] = hover;
|
||||
|
||||
json::object completion;
|
||||
completion["dynamicRegistration"] = false;
|
||||
text_doc_caps["completion"] = completion;
|
||||
|
||||
json::object diagnostic;
|
||||
diagnostic["dynamicRegistration"] = false;
|
||||
text_doc_caps["diagnostic"] = diagnostic;
|
||||
}
|
||||
|
||||
json::object capabilities;
|
||||
capabilities["textDocument"] = text_doc_caps;
|
||||
|
||||
json::object init_params;
|
||||
init_params["processId"] = nullptr;
|
||||
init_params["rootUri"] = nullptr;
|
||||
init_params["capabilities"] = capabilities;
|
||||
|
||||
// 发送 initialize 请求
|
||||
int init_id = send_request("initialize", init_params);
|
||||
|
||||
// 等待 initialize 响应 (最多 10 秒)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(g_lsp.mutex);
|
||||
bool got = g_lsp.cv.wait_for(lock, std::chrono::seconds(10), [init_id]() {
|
||||
return !g_lsp.running || g_lsp.pending_responses.count(init_id) > 0;
|
||||
});
|
||||
|
||||
if (!got || !g_lsp.running) {
|
||||
if (g_host) g_host->log(DSTALK_LOG_ERROR, "[lsp] initialize timed out");
|
||||
g_lsp_impl_stop();
|
||||
return -1;
|
||||
}
|
||||
g_lsp.pending_responses.erase(init_id);
|
||||
}
|
||||
|
||||
// 发送 initialized 通知
|
||||
send_notification("initialized", json::object{});
|
||||
|
||||
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] server started: %s", server_cmd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void g_lsp_impl_stop() {
|
||||
if (!g_lsp.running) return;
|
||||
|
||||
// 发送 shutdown 请求
|
||||
int shutdown_id = send_request("shutdown", json::object{});
|
||||
|
||||
// 等待 shutdown 响应 (最多 2 秒)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(g_lsp.mutex);
|
||||
g_lsp.cv.wait_for(lock, std::chrono::seconds(2), [shutdown_id]() {
|
||||
return !g_lsp.running || g_lsp.pending_responses.count(shutdown_id) > 0;
|
||||
});
|
||||
g_lsp.pending_responses.clear();
|
||||
}
|
||||
|
||||
// 发送 exit 通知
|
||||
send_notification("exit", json::object{});
|
||||
|
||||
// 停止读取线程
|
||||
g_lsp.running = false;
|
||||
g_lsp.proc.stop();
|
||||
|
||||
if (g_lsp.reader_thread.joinable())
|
||||
g_lsp.reader_thread.join();
|
||||
|
||||
g_lsp.diagnostics.clear();
|
||||
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] server stopped");
|
||||
}
|
||||
|
||||
static int g_lsp_impl_open_document(const char* uri, const char* content,
|
||||
const char* lang_id) {
|
||||
if (!g_lsp.running) return -1;
|
||||
if (!uri || !content || !lang_id) return -1;
|
||||
|
||||
json::object text_doc;
|
||||
text_doc["uri"] = uri;
|
||||
text_doc["languageId"] = lang_id;
|
||||
text_doc["version"] = 1;
|
||||
text_doc["text"] = content;
|
||||
|
||||
json::object params;
|
||||
params["textDocument"] = text_doc;
|
||||
|
||||
send_notification("textDocument/didOpen", params);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int g_lsp_impl_close_document(const char* uri) {
|
||||
if (!g_lsp.running) return -1;
|
||||
if (!uri) return -1;
|
||||
|
||||
json::object text_doc;
|
||||
text_doc["uri"] = uri;
|
||||
|
||||
json::object params;
|
||||
params["textDocument"] = text_doc;
|
||||
|
||||
send_notification("textDocument/didClose", params);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int g_lsp_impl_get_diagnostics(const char* uri, char** json_out) {
|
||||
if (!g_lsp.running) return -1;
|
||||
if (!uri || !json_out) return -1;
|
||||
|
||||
std::lock_guard<std::mutex> lock(g_lsp.mutex);
|
||||
auto it = g_lsp.diagnostics.find(uri);
|
||||
if (it == g_lsp.diagnostics.end()) {
|
||||
*json_out = g_host->strdup("[]");
|
||||
} else {
|
||||
*json_out = g_host->strdup(it->second.c_str());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int g_lsp_impl_get_hover(const char* uri, int line, int col, char** json_out) {
|
||||
if (!g_lsp.running) return -1;
|
||||
if (!uri || !json_out) return -1;
|
||||
|
||||
json::object position;
|
||||
position["line"] = line;
|
||||
position["character"] = col;
|
||||
|
||||
json::object text_doc;
|
||||
text_doc["uri"] = uri;
|
||||
|
||||
json::object params;
|
||||
params["textDocument"] = text_doc;
|
||||
params["position"] = position;
|
||||
|
||||
int req_id = send_request("textDocument/hover", params);
|
||||
|
||||
std::unique_lock<std::mutex> lock(g_lsp.mutex);
|
||||
bool got = g_lsp.cv.wait_for(lock, std::chrono::seconds(10), [req_id]() {
|
||||
return !g_lsp.running || g_lsp.pending_responses.count(req_id) > 0;
|
||||
});
|
||||
|
||||
if (!got || !g_lsp.running || g_lsp.pending_responses.count(req_id) == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::string response_body = g_lsp.pending_responses[req_id];
|
||||
g_lsp.pending_responses.erase(req_id);
|
||||
|
||||
json::value val;
|
||||
try { val = json::parse(response_body); }
|
||||
catch (...) { return -1; }
|
||||
|
||||
json::object resp;
|
||||
try { resp = val.as_object(); }
|
||||
catch (...) { return -1; }
|
||||
|
||||
if (!resp.contains("result")) return -1;
|
||||
|
||||
*json_out = g_host->strdup(json::serialize(resp["result"]).c_str());
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int g_lsp_impl_get_completion(const char* uri, int line, int col, char** json_out) {
|
||||
if (!g_lsp.running) return -1;
|
||||
if (!uri || !json_out) return -1;
|
||||
|
||||
json::object position;
|
||||
position["line"] = line;
|
||||
position["character"] = col;
|
||||
|
||||
json::object text_doc;
|
||||
text_doc["uri"] = uri;
|
||||
|
||||
json::object params;
|
||||
params["textDocument"] = text_doc;
|
||||
params["position"] = position;
|
||||
|
||||
int req_id = send_request("textDocument/completion", params);
|
||||
|
||||
std::unique_lock<std::mutex> lock(g_lsp.mutex);
|
||||
bool got = g_lsp.cv.wait_for(lock, std::chrono::seconds(10), [req_id]() {
|
||||
return !g_lsp.running || g_lsp.pending_responses.count(req_id) > 0;
|
||||
});
|
||||
|
||||
if (!got || !g_lsp.running || g_lsp.pending_responses.count(req_id) == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::string response_body = g_lsp.pending_responses[req_id];
|
||||
g_lsp.pending_responses.erase(req_id);
|
||||
|
||||
json::value val;
|
||||
try { val = json::parse(response_body); }
|
||||
catch (...) { return -1; }
|
||||
|
||||
json::object resp;
|
||||
try { resp = val.as_object(); }
|
||||
catch (...) { return -1; }
|
||||
|
||||
if (!resp.contains("result")) return -1;
|
||||
|
||||
*json_out = g_host->strdup(json::serialize(resp["result"]).c_str());
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 服务 vtable
|
||||
// ============================================================================
|
||||
|
||||
static dstalk_lsp_service_t g_service_vtable = {
|
||||
&g_lsp_impl_start,
|
||||
&g_lsp_impl_stop,
|
||||
&g_lsp_impl_open_document,
|
||||
&g_lsp_impl_close_document,
|
||||
&g_lsp_impl_get_diagnostics,
|
||||
&g_lsp_impl_get_hover,
|
||||
&g_lsp_impl_get_completion,
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// 生命周期回调
|
||||
// ============================================================================
|
||||
|
||||
static int on_init(const dstalk_host_api_t* host) {
|
||||
g_host = host;
|
||||
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] initializing LSP service plugin");
|
||||
return host->register_service("lsp", 1, &g_service_vtable);
|
||||
}
|
||||
|
||||
static void on_shutdown() {
|
||||
if (g_lsp.running) {
|
||||
g_lsp_impl_stop();
|
||||
}
|
||||
if (g_host) g_host->log(DSTALK_LOG_INFO, "[lsp] shutdown");
|
||||
g_host = nullptr;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 插件描述符
|
||||
// ============================================================================
|
||||
|
||||
static dstalk_plugin_info_t g_info = {
|
||||
/* .name = */ "lsp",
|
||||
/* .version = */ "1.0.0",
|
||||
/* .description = */ "Language Server Protocol client (subprocess manager)",
|
||||
/* .api_version = */ DSTALK_API_VERSION,
|
||||
/* .dependencies = */ { NULL }, // 无依赖,自行管理子进程
|
||||
/* .on_init = */ on_init,
|
||||
/* .on_shutdown = */ on_shutdown,
|
||||
/* .on_event = */ nullptr,
|
||||
};
|
||||
|
||||
extern "C" DSTALK_PLUGIN_EXPORT dstalk_plugin_info_t* dstalk_plugin_init(void) {
|
||||
return &g_info;
|
||||
}
|
||||
Reference in New Issue
Block a user