1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use std::collections::HashMap;
use anyhow::anyhow;
use lsp_server::{Connection, Message, Response};
use lsp_types::{
notification::{DidChangeTextDocument, DidOpenTextDocument, Notification, PublishDiagnostics},
request::{Formatting, Request},
DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentFormattingParams, OneOf,
Position, PublishDiagnosticsParams, Range, ServerCapabilities, TextDocumentSyncKind, TextEdit,
Url,
};
use tan::api::parse_string_all;
use tan_fmt::pretty::Formatter;
use tan_lint::compute_diagnostics;
use tracing::{info, trace};
use crate::util::VERSION;
pub struct Server {
documents: HashMap<String, String>,
}
// #TODO split further into methods.
impl Server {
pub fn new() -> Self {
Self {
documents: HashMap::default(),
}
}
pub fn run(&mut self) -> anyhow::Result<()> {
info!("Starting LSP server, v{}...", VERSION);
let (connection, io_threads) = Connection::stdio();
let server_capabilities = serde_json::to_value(&ServerCapabilities {
// definition_provider: Some(OneOf::Left(true)),
// references_provider: Some(OneOf::Left(true)),
// #Insight Enables didOpen/didChange notifications.
text_document_sync: Some(lsp_types::TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::FULL,
)),
rename_provider: Some(OneOf::Left(true)),
document_formatting_provider: Some(OneOf::Left(true)),
..Default::default()
})
.unwrap();
let initialization_params = connection.initialize(server_capabilities)?;
info!("Started.");
// Run the server.
self.run_loop(connection, initialization_params)?;
// Wait for the two threads to end (typically by trigger LSP Exit event).
io_threads.join()?;
info!("Shutting down server...");
Ok(())
}
// #TODO return a more precise result.
pub fn send_diagnostics(&self, connection: &Connection, uri: Url) -> anyhow::Result<()> {
let Some(input) = self.documents.get(uri.as_str()) else {
return Err(anyhow!("Unknown document").context("in send_diagnostics"));
};
let diagnostics = compute_diagnostics(input);
let pdm = PublishDiagnosticsParams {
uri: uri.clone(),
diagnostics,
version: None,
};
let notification = lsp_server::Notification {
method: PublishDiagnostics::METHOD.to_owned(),
params: serde_json::to_value(&pdm).unwrap(),
};
connection
.sender
.send(Message::Notification(notification))?;
Ok(())
}
pub fn run_loop(
&mut self,
connection: Connection,
_params: serde_json::Value,
) -> anyhow::Result<()> {
// #TODO use params to get root_uri and perform initial diagnostics for all files.
// let params: InitializeParams = serde_json::from_value(params).unwrap();
// eprintln!("{params:#?}");
for msg in &connection.receiver {
trace!("Got msg: {:?}.", msg);
match msg {
Message::Request(req) => {
if connection.handle_shutdown(&req)? {
return Ok(());
}
trace!("got request: {:?}", req);
// match cast::<GotoDefinition>(req.clone()) {
// Ok((id, params)) => {
// eprintln!("got gotoDefinition request #{id}: {params:?}");
// let result = Some(GotoDefinitionResponse::Array(Vec::new()));
// let result = serde_json::to_value(&result).unwrap();
// let resp = Response {
// id,
// result: Some(result),
// error: None,
// };
// connection.sender.send(Message::Response(resp))?;
// continue;
// }
// Err(err @ ExtractError::JsonError { .. }) => panic!("{err:?}"),
// Err(ExtractError::MethodMismatch(req)) => req,
// };
// match cast::<References>(req.clone()) {
// Ok((id, params)) => {
// eprintln!("got references request #{id}: {params:?}");
// let result = Some(Vec::<String>::new());
// let result = serde_json::to_value(&result).unwrap();
// let resp = Response {
// id,
// result: Some(result),
// error: None,
// };
// connection.sender.send(Message::Response(resp))?;
// continue;
// }
// Err(err @ ExtractError::JsonError { .. }) => panic!("{err:?}"),
// Err(ExtractError::MethodMismatch(req)) => req,
// };
match req.method.as_ref() {
Formatting::METHOD => {
let (id, params) =
req.extract::<DocumentFormattingParams>(Formatting::METHOD)?;
let document = params.text_document;
let Some(input) = self.documents.get(document.uri.as_str()) else {
return Err(anyhow!("Unknown document").context("in Formatting::METHOD"));
};
// #TODO don't parse all the time? is this even possible, probably not the input changed here.
let Ok(exprs) = parse_string_all(&input) else {
return Err(anyhow::anyhow!("Error"));
};
let formatter = Formatter::new(&exprs);
let formatted = formatter.format();
// #TODO does it make sense to compute diffs?
// Select the whole document for replacement
let start = Position::new(0, 0);
let end = Position::new(u32::MAX, u32::MAX);
let document_range = Range::new(start, end);
let result = Some(vec![TextEdit::new(document_range, formatted)]);
let result = serde_json::to_value(&result).unwrap();
let resp = Response {
id,
result: Some(result),
error: None,
};
connection.sender.send(Message::Response(resp))?;
continue;
}
_ => continue,
}
}
Message::Response(resp) => {
trace!("Got response: {:?}.", resp);
}
Message::Notification(notification) => {
info!("got notification: {:?}.", notification);
match notification.method.as_ref() {
"textDocument/didOpen" => {
if let Ok(params) = notification
.extract::<DidOpenTextDocumentParams>(DidOpenTextDocument::METHOD)
{
let document = params.text_document;
self.documents
.insert(document.uri.to_string(), document.text);
self.send_diagnostics(&connection, document.uri)?;
}
}
"textDocument/didChange" => {
if let Ok(params) = notification.extract::<DidChangeTextDocumentParams>(
DidChangeTextDocument::METHOD,
) {
let document = params.text_document;
let changes = params.content_changes;
if let Some(change) = changes.first() {
self.documents
.insert(document.uri.to_string(), change.text.clone());
self.send_diagnostics(&connection, document.uri)?;
}
}
}
_ => {
eprintln!("Unhandled: {}", notification.method);
}
}
// if let Ok(event) =
// &event.extract::<DidChangeTextDocumentParams>(DidChangeTextDocument::METHOD)
// {
// for change in event.content_changes.into_iter() {
// dbg!(change.text);
// }
// }
// #TODO try to switch to incremental sync.
}
}
}
Ok(())
}
}