use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct DaemonRequest {
pub id: u64,
pub method: String,
#[serde(default = "serde_json::Value::default")]
pub params: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DaemonResponse {
pub id: u64,
#[serde(default)]
pub error: Option<String>,
#[serde(default = "serde_json::Value::default")]
pub result: serde_json::Value,
}
impl DaemonResponse {
pub fn ok(id: u64, result: serde_json::Value) -> Self {
Self {
id,
error: None,
result,
}
}
pub fn err(id: u64, message: impl Into<String>) -> Self {
Self {
id,
error: Some(message.into()),
result: serde_json::Value::Null,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SpawnParams {
pub language: String,
pub backend: String,
#[serde(default)]
pub root_path: Option<String>,
#[serde(default)]
pub extra_args: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LspRequestParams {
pub session_key: String,
pub method: String,
#[serde(default = "serde_json::Value::default")]
pub params: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LspNotifyParams {
pub session_key: String,
pub method: String,
#[serde(default = "serde_json::Value::default")]
pub params: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WaitNotifyParams {
pub session_key: String,
pub method: String,
#[serde(default)]
pub filter_uri: Option<String>,
#[serde(default)]
pub timeout_ms: Option<u64>,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_daemon_response_ok() {
let resp = DaemonResponse::ok(42, json!({"session_key": "abc"}));
assert_eq!(resp.id, 42);
assert_eq!(resp.error, None);
assert_eq!(resp.result["session_key"], "abc");
}
#[test]
fn test_daemon_response_err() {
let resp = DaemonResponse::err(1, "something went wrong");
assert_eq!(resp.id, 1);
assert_eq!(resp.error.as_deref(), Some("something went wrong"));
assert_eq!(resp.result, serde_json::Value::Null);
}
#[test]
fn test_request_serialization() {
let req = DaemonRequest {
id: 1,
method: "lsp/spawn".into(),
params: json!({
"language": "rust",
"backend": "rust-analyzer",
}),
};
let json = serde_json::to_string(&req).unwrap();
let parsed: DaemonRequest = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.id, 1);
assert_eq!(parsed.method, "lsp/spawn");
}
#[test]
fn test_spawn_params_repr() {
let p = SpawnParams {
language: "go".into(),
backend: "gopls".into(),
root_path: Some("/home/user/project".into()),
extra_args: vec!["-v".into()],
};
let json = serde_json::to_string(&p).unwrap();
let back: SpawnParams = serde_json::from_str(&json).unwrap();
assert_eq!(back.language, "go");
assert_eq!(back.extra_args, vec!["-v"]);
}
}