vize_maestro 0.0.1-alpha.26

Maestro - Language Server Protocol implementation for Vize Vue templates
Documentation
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! LSP server implementation.
//!
//! This module contains the core LSP server using tower-lsp.

mod capabilities;
mod state;

pub use capabilities::*;
pub use state::*;

use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer};

use crate::document::DocumentStore;
use crate::ide::{
    CodeActionService, CodeLensService, CompletionService, DefinitionService, DiagnosticService,
    HoverService, IdeContext, ReferencesService, RenameService, SemanticTokensService,
    WorkspaceSymbolsService,
};

/// The Maestro LSP server.
pub struct MaestroServer {
    /// LSP client for sending notifications
    client: Client,
    /// Server state
    state: ServerState,
}

impl MaestroServer {
    /// Create a new Maestro server instance.
    pub fn new(client: Client) -> Self {
        Self {
            client,
            state: ServerState::new(),
        }
    }

    /// Get the document store.
    pub fn documents(&self) -> &DocumentStore {
        &self.state.documents
    }

    /// Publish diagnostics for a document.
    async fn publish_diagnostics(&self, uri: &Url) {
        let diagnostics = DiagnosticService::collect(&self.state, uri);
        self.client
            .publish_diagnostics(uri.clone(), diagnostics, None)
            .await;
    }

    /// Get block snippet completions (when outside all blocks)
    fn get_block_snippets(&self) -> Vec<CompletionItem> {
        vec![
            CompletionItem {
                label: "template".to_string(),
                kind: Some(CompletionItemKind::SNIPPET),
                detail: Some("Add template block".to_string()),
                insert_text: Some("<template>\n\t$1\n</template>".to_string()),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
            CompletionItem {
                label: "script setup".to_string(),
                kind: Some(CompletionItemKind::SNIPPET),
                detail: Some("Add script setup block".to_string()),
                insert_text: Some("<script setup lang=\"ts\">\n$1\n</script>".to_string()),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
            CompletionItem {
                label: "script".to_string(),
                kind: Some(CompletionItemKind::SNIPPET),
                detail: Some("Add script block".to_string()),
                insert_text: Some(
                    "<script lang=\"ts\">\nexport default {\n\t$1\n}\n</script>".to_string(),
                ),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
            CompletionItem {
                label: "style scoped".to_string(),
                kind: Some(CompletionItemKind::SNIPPET),
                detail: Some("Add scoped style block".to_string()),
                insert_text: Some("<style scoped>\n$1\n</style>".to_string()),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
            CompletionItem {
                label: "style".to_string(),
                kind: Some(CompletionItemKind::SNIPPET),
                detail: Some("Add style block".to_string()),
                insert_text: Some("<style>\n$1\n</style>".to_string()),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
        ]
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for MaestroServer {
    async fn initialize(&self, _params: InitializeParams) -> Result<InitializeResult> {
        Ok(InitializeResult {
            capabilities: server_capabilities(),
            server_info: Some(ServerInfo {
                name: "vize-maestro".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
        })
    }

    async fn initialized(&self, _params: InitializedParams) {
        self.client
            .log_message(MessageType::INFO, "vize_maestro LSP server initialized")
            .await;
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri;
        let content = params.text_document.text;
        let version = params.text_document.version;
        let language_id = params.text_document.language_id;

        self.state
            .documents
            .open(uri.clone(), content.clone(), version, language_id);

        // Generate virtual documents for the SFC
        self.state.update_virtual_docs(&uri, &content);

        self.publish_diagnostics(&uri).await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let uri = params.text_document.uri;
        let version = params.text_document.version;

        self.state
            .documents
            .apply_changes(&uri, params.content_changes, version);

        // Regenerate virtual documents with updated content
        if let Some(doc) = self.state.documents.get(&uri) {
            let content = doc.text();
            self.state.update_virtual_docs(&uri, &content);
        }

        self.publish_diagnostics(&uri).await;
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        let uri = params.text_document.uri;
        self.publish_diagnostics(&uri).await;
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        let uri = params.text_document.uri;
        self.state.documents.close(&uri);

        // Clean up virtual documents cache
        self.state.remove_virtual_docs(&uri);

        // Clear diagnostics
        self.client.publish_diagnostics(uri, vec![], None).await;
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        let uri = &params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();

        // Convert LSP position to byte offset
        let offset =
            crate::utils::position_to_offset_str(&content, position.line, position.character);

        // Use IdeContext and HoverService for context-aware hover
        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            if let Some(hover) = HoverService::hover(&ctx) {
                return Ok(Some(hover));
            }
        }

        Ok(None)
    }

    async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
        let uri = &params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let offset =
            crate::utils::position_to_offset_str(&content, position.line, position.character);

        // Use IdeContext and CompletionService for context-aware completions
        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            if let Some(response) = CompletionService::complete(&ctx) {
                return Ok(Some(response));
            }
        }

        // Fallback: offer block snippets if we can't determine context
        let items = self.get_block_snippets();
        if items.is_empty() {
            Ok(None)
        } else {
            Ok(Some(CompletionResponse::Array(items)))
        }
    }

    async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> Result<Option<GotoDefinitionResponse>> {
        let uri = &params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let offset =
            crate::utils::position_to_offset_str(&content, position.line, position.character);

        // Use IdeContext and DefinitionService for go-to-definition
        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            if let Some(response) = DefinitionService::definition(&ctx) {
                return Ok(Some(response));
            }
        }

        Ok(None)
    }

    async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
        let uri = &params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let include_declaration = params.context.include_declaration;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let offset =
            crate::utils::position_to_offset_str(&content, position.line, position.character);

        // Use IdeContext and ReferencesService for find-all-references
        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            if let Some(locations) = ReferencesService::references(&ctx, include_declaration) {
                return Ok(Some(locations));
            }
        }

        Ok(None)
    }

    #[allow(deprecated)] // DocumentSymbol.deprecated is deprecated in favor of tags
    async fn document_symbol(
        &self,
        params: DocumentSymbolParams,
    ) -> Result<Option<DocumentSymbolResponse>> {
        let uri = &params.text_document.uri;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let options = vize_atelier_sfc::SfcParseOptions {
            filename: uri.path().to_string(),
            ..Default::default()
        };

        let Ok(descriptor) = vize_atelier_sfc::parse_sfc(&content, options) else {
            return Ok(None);
        };

        let mut symbols = Vec::new();

        // Add template symbol
        if let Some(ref template) = descriptor.template {
            symbols.push(DocumentSymbol {
                name: "template".to_string(),
                kind: SymbolKind::MODULE,
                tags: None,
                deprecated: None,
                range: Range {
                    start: Position {
                        line: template.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: template.loc.end_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                },
                selection_range: Range {
                    start: Position {
                        line: template.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: template.loc.start_line.saturating_sub(1) as u32,
                        character: 10,
                    },
                },
                detail: template.lang.as_ref().map(|l| l.to_string()),
                children: None,
            });
        }

        // Add script symbol
        if let Some(ref script) = descriptor.script {
            symbols.push(DocumentSymbol {
                name: "script".to_string(),
                kind: SymbolKind::MODULE,
                tags: None,
                deprecated: None,
                range: Range {
                    start: Position {
                        line: script.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: script.loc.end_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                },
                selection_range: Range {
                    start: Position {
                        line: script.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: script.loc.start_line.saturating_sub(1) as u32,
                        character: 8,
                    },
                },
                detail: script.lang.as_ref().map(|l| l.to_string()),
                children: None,
            });
        }

        // Add script setup symbol
        if let Some(ref script_setup) = descriptor.script_setup {
            symbols.push(DocumentSymbol {
                name: "script setup".to_string(),
                kind: SymbolKind::MODULE,
                tags: None,
                deprecated: None,
                range: Range {
                    start: Position {
                        line: script_setup.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: script_setup.loc.end_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                },
                selection_range: Range {
                    start: Position {
                        line: script_setup.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: script_setup.loc.start_line.saturating_sub(1) as u32,
                        character: 14,
                    },
                },
                detail: script_setup.lang.as_ref().map(|l| l.to_string()),
                children: None,
            });
        }

        // Add style symbols
        for (i, style) in descriptor.styles.iter().enumerate() {
            let name = if let Some(ref module) = style.module {
                format!("style module={}", module)
            } else if style.scoped {
                "style scoped".to_string()
            } else {
                format!("style[{}]", i)
            };

            symbols.push(DocumentSymbol {
                name,
                kind: SymbolKind::MODULE,
                tags: None,
                deprecated: None,
                range: Range {
                    start: Position {
                        line: style.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: style.loc.end_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                },
                selection_range: Range {
                    start: Position {
                        line: style.loc.start_line.saturating_sub(1) as u32,
                        character: 0,
                    },
                    end: Position {
                        line: style.loc.start_line.saturating_sub(1) as u32,
                        character: 7,
                    },
                },
                detail: style.lang.as_ref().map(|l| l.to_string()),
                children: None,
            });
        }

        Ok(Some(DocumentSymbolResponse::Nested(symbols)))
    }

    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
        let uri = &params.text_document.uri;
        let range = params.range;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();

        // Create IDE context at start of range
        let offset =
            crate::utils::position_to_offset_str(&content, range.start.line, range.start.character);

        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            let actions = CodeActionService::code_actions(&ctx, range);
            if !actions.is_empty() {
                return Ok(Some(actions));
            }
        }

        Ok(None)
    }

    async fn prepare_rename(
        &self,
        params: TextDocumentPositionParams,
    ) -> Result<Option<PrepareRenameResponse>> {
        let uri = &params.text_document.uri;
        let position = params.position;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let offset =
            crate::utils::position_to_offset_str(&content, position.line, position.character);

        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            return Ok(RenameService::prepare_rename(&ctx));
        }

        Ok(None)
    }

    async fn rename(&self, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
        let uri = &params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let new_name = &params.new_name;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let offset =
            crate::utils::position_to_offset_str(&content, position.line, position.character);

        if let Some(ctx) = IdeContext::new(&self.state, uri, offset) {
            return Ok(RenameService::rename(&ctx, new_name));
        }

        Ok(None)
    }

    async fn semantic_tokens_full(
        &self,
        params: SemanticTokensParams,
    ) -> Result<Option<SemanticTokensResult>> {
        let uri = &params.text_document.uri;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        Ok(SemanticTokensService::get_tokens(&content, uri))
    }

    async fn code_lens(&self, params: CodeLensParams) -> Result<Option<Vec<CodeLens>>> {
        let uri = &params.text_document.uri;

        let Some(doc) = self.state.documents.get(uri) else {
            return Ok(None);
        };

        let content = doc.text();
        let lenses = CodeLensService::get_lenses(&content, uri);

        if lenses.is_empty() {
            Ok(None)
        } else {
            Ok(Some(lenses))
        }
    }

    async fn symbol(
        &self,
        params: WorkspaceSymbolParams,
    ) -> Result<Option<Vec<SymbolInformation>>> {
        let query = &params.query;
        let symbols = WorkspaceSymbolsService::search(&self.state, query);

        if symbols.is_empty() {
            Ok(None)
        } else {
            Ok(Some(symbols))
        }
    }
}