1#![forbid(unsafe_code)]
8#![warn(missing_docs, clippy::pedantic)]
9
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use tokio::sync::Mutex;
14use tower_lsp::jsonrpc::Result;
15#[allow(clippy::wildcard_imports)]
16use tower_lsp::lsp_types::*;
17use tower_lsp::{Client, LanguageServer, LspService, Server};
18
19pub mod code_actions;
20pub mod completion;
21pub mod diagnostics;
22pub mod format;
23pub mod goto;
24pub mod hover;
25
26pub struct Backend {
28 pub client: Client,
30 documents: Arc<Mutex<HashMap<Url, String>>>,
32}
33
34impl Backend {
35 #[must_use]
37 pub fn new(client: Client) -> Self {
38 Self {
39 client,
40 documents: Arc::new(Mutex::new(HashMap::new())),
41 }
42 }
43
44 async fn validate_and_publish(&self, uri: &Url, text: &str, version: Option<i32>) {
46 let file_name = uri.path();
47 let mut diags = Vec::new();
48
49 match ruprizzle_parser::parse_with_warnings(file_name, text) {
50 Ok((_schema, warnings)) => {
51 for warning in warnings {
52 diags.push(diagnostics::schema_error_to_diagnostic(text, &warning));
53 }
54 }
55 Err(errors) => {
56 for error in &errors.errors {
57 diags.push(diagnostics::schema_error_to_diagnostic(text, error));
58 }
59 }
60 }
61
62 self.client
63 .publish_diagnostics(uri.clone(), diags, version)
64 .await;
65 }
66}
67
68#[tower_lsp::async_trait]
69impl LanguageServer for Backend {
70 async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
71 Ok(InitializeResult {
72 capabilities: ServerCapabilities {
73 text_document_sync: Some(TextDocumentSyncCapability::Kind(
74 TextDocumentSyncKind::INCREMENTAL,
75 )),
76 completion_provider: Some(CompletionOptions {
77 trigger_characters: Some(vec![
78 "@".to_string(),
79 ".".to_string(),
80 ":".to_string(),
81 "[".to_string(),
82 ]),
83 ..CompletionOptions::default()
84 }),
85 definition_provider: Some(OneOf::Left(true)),
86 hover_provider: Some(HoverProviderCapability::Simple(true)),
87 document_formatting_provider: Some(OneOf::Left(true)),
88 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
89 ..ServerCapabilities::default()
90 },
91 server_info: Some(ServerInfo {
92 name: "ruprizzle-lsp".to_owned(),
93 version: Some(env!("CARGO_PKG_VERSION").to_owned()),
94 }),
95 })
96 }
97
98 async fn initialized(&self, _: InitializedParams) {
99 self.client
100 .log_message(MessageType::INFO, "ruprizzle-lsp initialised")
101 .await;
102 }
103
104 async fn shutdown(&self) -> Result<()> {
105 Ok(())
106 }
107
108 async fn did_open(&self, params: DidOpenTextDocumentParams) {
109 let uri = params.text_document.uri;
110 let text = params.text_document.text;
111 let version = Some(params.text_document.version);
112
113 let mut docs = self.documents.lock().await;
114 docs.insert(uri.clone(), text.clone());
115 drop(docs);
116
117 self.validate_and_publish(&uri, &text, version).await;
118 }
119
120 async fn did_change(&self, params: DidChangeTextDocumentParams) {
121 let uri = params.text_document.uri;
122 let version = Some(params.text_document.version);
123
124 let mut docs = self.documents.lock().await;
125 let text = docs.get(&uri).cloned().unwrap_or_default();
126
127 let mut text = text;
128 for change in params.content_changes {
129 if let Some(range) = change.range {
130 text = apply_change(&text, range, &change.text);
131 } else {
132 text = change.text;
133 }
134 }
135 docs.insert(uri.clone(), text.clone());
136 drop(docs);
137
138 self.validate_and_publish(&uri, &text, version).await;
139 }
140
141 async fn did_close(&self, params: DidCloseTextDocumentParams) {
142 let mut docs = self.documents.lock().await;
143 docs.remove(¶ms.text_document.uri);
144 self.client
145 .publish_diagnostics(params.text_document.uri, Vec::new(), None)
146 .await;
147 }
148
149 async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
150 let docs = self.documents.lock().await;
151 let Some(text) = docs.get(¶ms.text_document_position.text_document.uri) else {
152 return Ok(None);
153 };
154 let text = text.clone();
155 drop(docs);
156
157 let uri = ¶ms.text_document_position.text_document.uri;
158 let file_name = uri.path();
159 let schema = ruprizzle_parser::parse(file_name, &text).ok();
160 let position = params.text_document_position.position;
161
162 Ok(completion::complete(&text, schema.as_ref(), position))
163 }
164
165 async fn goto_definition(
166 &self,
167 params: GotoDefinitionParams,
168 ) -> Result<Option<GotoDefinitionResponse>> {
169 let docs = self.documents.lock().await;
170 let Some(text) = docs.get(¶ms.text_document_position_params.text_document.uri) else {
171 return Ok(None);
172 };
173 let text = text.clone();
174 drop(docs);
175
176 let uri = ¶ms.text_document_position_params.text_document.uri;
177 let file_name = uri.path();
178 let schema = ruprizzle_parser::parse(file_name, &text).ok();
179 let position = params.text_document_position_params.position;
180
181 Ok(goto::goto_definition(uri, &text, schema.as_ref(), position))
182 }
183
184 async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
185 let docs = self.documents.lock().await;
186 let Some(text) = docs.get(¶ms.text_document_position_params.text_document.uri) else {
187 return Ok(None);
188 };
189 let text = text.clone();
190 drop(docs);
191
192 let file_name = params
193 .text_document_position_params
194 .text_document
195 .uri
196 .path();
197 let schema = ruprizzle_parser::parse(file_name, &text).ok();
198 let position = params.text_document_position_params.position;
199
200 Ok(hover::hover(&text, schema.as_ref(), position))
201 }
202
203 async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
204 let docs = self.documents.lock().await;
205 let Some(text) = docs.get(¶ms.text_document.uri) else {
206 return Ok(None);
207 };
208 let text = text.clone();
209 drop(docs);
210
211 Ok(Some(format::format_document(&text)))
212 }
213
214 async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
215 let docs = self.documents.lock().await;
216 let Some(text) = docs.get(¶ms.text_document.uri) else {
217 return Ok(None);
218 };
219 let text = text.clone();
220 drop(docs);
221
222 let file_name = params.text_document.uri.path();
223 let schema = ruprizzle_parser::parse(file_name, &text).ok();
224
225 Ok(Some(code_actions::code_actions(
226 ¶ms.text_document.uri,
227 &text,
228 schema.as_ref(),
229 params.range,
230 )))
231 }
232}
233
234fn apply_change(text: &str, range: Range, new: &str) -> String {
235 let start = position_to_byte_offset(text, range.start);
236 let end = position_to_byte_offset(text, range.end);
237 let mut result = text.to_owned();
238 result.replace_range(start..end, new);
239 result
240}
241
242fn position_to_byte_offset(text: &str, pos: Position) -> usize {
243 let mut line = 0;
244 let mut col = 0;
245 for (i, c) in text.char_indices() {
246 if line == pos.line && col == pos.character {
247 return i;
248 }
249 if c == '\n' {
250 line += 1;
251 col = 0;
252 } else {
253 col += 1;
254 }
255 }
256 text.len()
257}
258
259pub async fn run_stdio() {
261 let (stdin, stdout) = (tokio::io::stdin(), tokio::io::stdout());
262 let (service, socket) = LspService::new(Backend::new);
263 Server::new(stdin, stdout, socket).serve(service).await;
264}