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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Definition provider for Vue SFC files.
//!
//! Provides go-to-definition for:
//! - Template expressions -> script bindings
//! - Component usages -> component definitions
//! - Import statements -> imported files

use tower_lsp::lsp_types::{GotoDefinitionResponse, Location, Position, Range};

use super::IdeContext;
use crate::virtual_code::BlockType;

/// Definition service for providing go-to-definition functionality.
pub struct DefinitionService;

impl DefinitionService {
    /// Get definition for the symbol at the current position.
    pub fn definition(ctx: &IdeContext) -> Option<GotoDefinitionResponse> {
        match ctx.block_type? {
            BlockType::Template => Self::definition_in_template(ctx),
            BlockType::Script | BlockType::ScriptSetup => Self::definition_in_script(ctx),
            BlockType::Style(_) => Self::definition_in_style(ctx),
        }
    }

    /// Find definition for a symbol in template context.
    fn definition_in_template(ctx: &IdeContext) -> Option<GotoDefinitionResponse> {
        // Get the word at the cursor position
        let word = Self::get_word_at_offset(&ctx.content, ctx.offset)?;

        if word.is_empty() {
            return None;
        }

        // Try to find the binding in script setup
        if let Some(ref virtual_docs) = ctx.virtual_docs {
            if let Some(ref script_setup) = virtual_docs.script_setup {
                // Find binding location in script setup
                if let Some(binding_loc) =
                    Self::find_binding_location(&script_setup.content, &word, true)
                {
                    // Calculate the actual position in the SFC file
                    let (line, character) =
                        Self::offset_to_position(&script_setup.content, binding_loc.offset);

                    // Adjust line based on script block position in SFC
                    // We need to get the actual script block start line
                    let sfc_line =
                        Self::get_script_setup_start_line(&ctx.content).unwrap_or(0) + line;

                    return Some(GotoDefinitionResponse::Scalar(Location {
                        uri: ctx.uri.clone(),
                        range: Range {
                            start: Position {
                                line: sfc_line,
                                character,
                            },
                            end: Position {
                                line: sfc_line,
                                character: character + word.len() as u32,
                            },
                        },
                    }));
                }
            }

            // Try regular script block
            if let Some(ref script) = virtual_docs.script {
                if let Some(binding_loc) =
                    Self::find_binding_location(&script.content, &word, false)
                {
                    let (line, character) =
                        Self::offset_to_position(&script.content, binding_loc.offset);

                    let sfc_line = Self::get_script_start_line(&ctx.content).unwrap_or(0) + line;

                    return Some(GotoDefinitionResponse::Scalar(Location {
                        uri: ctx.uri.clone(),
                        range: Range {
                            start: Position {
                                line: sfc_line,
                                character,
                            },
                            end: Position {
                                line: sfc_line,
                                character: character + word.len() as u32,
                            },
                        },
                    }));
                }
            }
        }

        None
    }

    /// Find definition for a symbol in script context.
    fn definition_in_script(ctx: &IdeContext) -> Option<GotoDefinitionResponse> {
        let word = Self::get_word_at_offset(&ctx.content, ctx.offset)?;

        if word.is_empty() {
            return None;
        }

        // Check for import statement - could be a component or module
        // For now, we'll handle simple cases

        // Look for local definitions in the same script block
        let script_content = Self::get_current_script_content(ctx)?;

        if let Some(binding_loc) = Self::find_binding_location(&script_content, &word, true) {
            let (line, character) = Self::offset_to_position(&script_content, binding_loc.offset);

            // Get the script block start line
            let sfc_line = match ctx.block_type {
                Some(BlockType::ScriptSetup) => {
                    Self::get_script_setup_start_line(&ctx.content).unwrap_or(0)
                }
                Some(BlockType::Script) => Self::get_script_start_line(&ctx.content).unwrap_or(0),
                _ => 0,
            } + line;

            return Some(GotoDefinitionResponse::Scalar(Location {
                uri: ctx.uri.clone(),
                range: Range {
                    start: Position {
                        line: sfc_line,
                        character,
                    },
                    end: Position {
                        line: sfc_line,
                        character: character + word.len() as u32,
                    },
                },
            }));
        }

        None
    }

    /// Find definition for a symbol in style context.
    fn definition_in_style(ctx: &IdeContext) -> Option<GotoDefinitionResponse> {
        let word = Self::get_word_at_offset(&ctx.content, ctx.offset)?;

        if word.is_empty() {
            return None;
        }

        // Check for v-bind() references to script variables
        // Look backwards to see if we're inside v-bind()
        let before_cursor = &ctx.content[..ctx.offset];
        if before_cursor.contains("v-bind(") {
            // Try to find the binding in script setup
            if let Some(ref virtual_docs) = ctx.virtual_docs {
                if let Some(ref script_setup) = virtual_docs.script_setup {
                    if let Some(binding_loc) =
                        Self::find_binding_location(&script_setup.content, &word, true)
                    {
                        let (line, character) =
                            Self::offset_to_position(&script_setup.content, binding_loc.offset);

                        let sfc_line =
                            Self::get_script_setup_start_line(&ctx.content).unwrap_or(0) + line;

                        return Some(GotoDefinitionResponse::Scalar(Location {
                            uri: ctx.uri.clone(),
                            range: Range {
                                start: Position {
                                    line: sfc_line,
                                    character,
                                },
                                end: Position {
                                    line: sfc_line,
                                    character: character + word.len() as u32,
                                },
                            },
                        }));
                    }
                }
            }
        }

        None
    }

    /// Get the current script block content based on context.
    fn get_current_script_content(ctx: &IdeContext) -> Option<String> {
        if let Some(ref virtual_docs) = ctx.virtual_docs {
            match ctx.block_type {
                Some(BlockType::ScriptSetup) => virtual_docs
                    .script_setup
                    .as_ref()
                    .map(|d| d.content.clone()),
                Some(BlockType::Script) => virtual_docs.script.as_ref().map(|d| d.content.clone()),
                _ => None,
            }
        } else {
            None
        }
    }

    /// Get the word at a given offset.
    fn get_word_at_offset(content: &str, offset: usize) -> Option<String> {
        if offset >= content.len() {
            return None;
        }

        let bytes = content.as_bytes();

        // If the character at offset is not a word character, return None
        if !Self::is_word_char(bytes[offset]) {
            return None;
        }

        // Find word start
        let mut start = offset;
        while start > 0 {
            let c = bytes[start - 1];
            if !Self::is_word_char(c) {
                break;
            }
            start -= 1;
        }

        // Find word end
        let mut end = offset;
        while end < bytes.len() {
            let c = bytes[end];
            if !Self::is_word_char(c) {
                break;
            }
            end += 1;
        }

        if start == end {
            return None;
        }

        Some(String::from_utf8_lossy(&bytes[start..end]).to_string())
    }

    /// Check if a byte is a valid word character.
    #[inline]
    fn is_word_char(c: u8) -> bool {
        c.is_ascii_alphanumeric() || c == b'_' || c == b'$'
    }

    /// Find the location of a binding definition in script content.
    fn find_binding_location(
        content: &str,
        name: &str,
        _is_setup: bool,
    ) -> Option<BindingLocation> {
        // Skip the header comments in virtual code
        let content_start = Self::skip_virtual_header(content);
        let search_content = &content[content_start..];

        // Search patterns for binding definitions
        let patterns = [
            format!("const {} ", name),
            format!("const {}=", name),
            format!("let {} ", name),
            format!("let {}=", name),
            format!("var {} ", name),
            format!("var {}=", name),
            format!("function {}(", name),
            format!("function {} (", name),
        ];

        for pattern in &patterns {
            if let Some(pos) = search_content.find(pattern.as_str()) {
                // Find the actual name position within the pattern
                let name_offset = pattern.find(name).unwrap_or(0);
                let actual_offset = content_start + pos + name_offset;

                return Some(BindingLocation {
                    name: name.to_string(),
                    offset: actual_offset,
                    kind: BindingKind::from_pattern(pattern),
                });
            }
        }

        // Check for destructuring patterns: const { name } = ...
        let destructure_pattern = format!("{{ {}", name);
        if let Some(pos) = search_content.find(destructure_pattern.as_str()) {
            let name_offset = destructure_pattern.find(name).unwrap_or(0);
            let actual_offset = content_start + pos + name_offset;

            return Some(BindingLocation {
                name: name.to_string(),
                offset: actual_offset,
                kind: BindingKind::Destructure,
            });
        }

        // Check for: { name, ... } pattern with possible whitespace
        let destructure_patterns = [
            format!("{{ {}, ", name),
            format!("{{ {} }}", name),
            format!(", {} }}", name),
            format!(", {}, ", name),
        ];

        for pattern in &destructure_patterns {
            if let Some(pos) = search_content.find(pattern.as_str()) {
                let name_offset = pattern.find(name).unwrap_or(0);
                let actual_offset = content_start + pos + name_offset;

                return Some(BindingLocation {
                    name: name.to_string(),
                    offset: actual_offset,
                    kind: BindingKind::Destructure,
                });
            }
        }

        None
    }

    /// Skip virtual code header comments.
    fn skip_virtual_header(content: &str) -> usize {
        let mut offset = 0;
        for line in content.lines() {
            if line.starts_with("//") || line.trim().is_empty() {
                offset += line.len() + 1; // +1 for newline
            } else {
                break;
            }
        }
        offset
    }

    /// Convert byte offset to (line, character) position.
    fn offset_to_position(content: &str, offset: usize) -> (u32, u32) {
        let mut line = 0u32;
        let mut col = 0u32;
        let mut current_offset = 0usize;

        for ch in content.chars() {
            if current_offset >= offset {
                break;
            }

            if ch == '\n' {
                line += 1;
                col = 0;
            } else {
                col += 1;
            }

            current_offset += ch.len_utf8();
        }

        (line, col)
    }

    /// Get the start line of <script setup> block in SFC.
    fn get_script_setup_start_line(content: &str) -> Option<u32> {
        let options = vize_atelier_sfc::SfcParseOptions::default();
        let descriptor = vize_atelier_sfc::parse_sfc(content, options).ok()?;
        descriptor
            .script_setup
            .as_ref()
            .map(|s| s.loc.start_line as u32)
    }

    /// Get the start line of <script> block in SFC.
    fn get_script_start_line(content: &str) -> Option<u32> {
        let options = vize_atelier_sfc::SfcParseOptions::default();
        let descriptor = vize_atelier_sfc::parse_sfc(content, options).ok()?;
        descriptor.script.as_ref().map(|s| s.loc.start_line as u32)
    }
}

/// Location of a binding definition.
#[derive(Debug, Clone)]
pub struct BindingLocation {
    /// The binding name.
    pub name: String,
    /// Byte offset in the content.
    pub offset: usize,
    /// Kind of binding.
    pub kind: BindingKind,
}

/// Kind of binding definition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingKind {
    /// const declaration
    Const,
    /// let declaration
    Let,
    /// var declaration
    Var,
    /// function declaration
    Function,
    /// Destructuring pattern
    Destructure,
    /// Import binding
    Import,
    /// Unknown
    Unknown,
}

impl BindingKind {
    fn from_pattern(pattern: &str) -> Self {
        if pattern.starts_with("const") {
            BindingKind::Const
        } else if pattern.starts_with("let") {
            BindingKind::Let
        } else if pattern.starts_with("var") {
            BindingKind::Var
        } else if pattern.starts_with("function") {
            BindingKind::Function
        } else {
            BindingKind::Unknown
        }
    }
}

/// Extract bindings with their locations from script content.
pub fn extract_bindings_with_locations(content: &str, is_setup: bool) -> Vec<BindingLocation> {
    let mut bindings = Vec::new();

    if !is_setup {
        return bindings;
    }

    let content_start = DefinitionService::skip_virtual_header(content);
    let search_content = &content[content_start..];

    for line in search_content.lines() {
        let trimmed = line.trim();
        let line_start = search_content[..search_content.find(line).unwrap_or(0)].len();

        // const/let/var declarations
        for keyword in &["const ", "let ", "var "] {
            if trimmed.starts_with(keyword) {
                if let Some(rest) = trimmed.strip_prefix(keyword) {
                    // Handle destructuring: { a, b }
                    if rest.starts_with('{') {
                        if let Some(end) = rest.find('}') {
                            let inner = &rest[1..end];
                            for part in inner.split(',') {
                                let name = part.split(':').next().unwrap_or("").trim();
                                if !name.is_empty() && is_valid_identifier(name) {
                                    if let Some(name_pos) = line.find(name) {
                                        bindings.push(BindingLocation {
                                            name: name.to_string(),
                                            offset: content_start + line_start + name_pos,
                                            kind: BindingKind::Destructure,
                                        });
                                    }
                                }
                            }
                        }
                    }
                    // Simple: const x = ...
                    else if let Some(name) = rest.split(['=', ':', ' ']).next() {
                        let name = name.trim();
                        if is_valid_identifier(name) {
                            if let Some(name_pos) = line.find(name) {
                                let kind = match *keyword {
                                    "const " => BindingKind::Const,
                                    "let " => BindingKind::Let,
                                    "var " => BindingKind::Var,
                                    _ => BindingKind::Unknown,
                                };
                                bindings.push(BindingLocation {
                                    name: name.to_string(),
                                    offset: content_start + line_start + name_pos,
                                    kind,
                                });
                            }
                        }
                    }
                }
            }
        }

        // Function declarations
        if trimmed.starts_with("function ") {
            if let Some(rest) = trimmed.strip_prefix("function ") {
                if let Some(name) = rest.split('(').next() {
                    let name = name.trim();
                    if is_valid_identifier(name) {
                        if let Some(name_pos) = line.find(name) {
                            bindings.push(BindingLocation {
                                name: name.to_string(),
                                offset: content_start + line_start + name_pos,
                                kind: BindingKind::Function,
                            });
                        }
                    }
                }
            }
        }
    }

    bindings
}

/// Check if a string is a valid JavaScript identifier.
fn is_valid_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    if !first.is_alphabetic() && first != '_' && first != '$' {
        return false;
    }
    chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_find_binding_location_const() {
        let content = r#"// Virtual TypeScript
// Generated

const message = ref('hello')
const count = ref(0)
"#;

        let loc = DefinitionService::find_binding_location(content, "message", true);
        assert!(loc.is_some());
        let loc = loc.unwrap();
        assert_eq!(loc.name, "message");
        assert_eq!(loc.kind, BindingKind::Const);
    }

    #[test]
    fn test_find_binding_location_function() {
        let content = r#"// Virtual TypeScript
// Generated

function handleClick() {
  console.log('clicked')
}
"#;

        let loc = DefinitionService::find_binding_location(content, "handleClick", true);
        assert!(loc.is_some());
        let loc = loc.unwrap();
        assert_eq!(loc.name, "handleClick");
        assert_eq!(loc.kind, BindingKind::Function);
    }

    #[test]
    fn test_find_binding_location_destructure() {
        let content = r#"// Virtual TypeScript
// Generated

const { data, error } = useFetch('/api')
"#;

        let loc = DefinitionService::find_binding_location(content, "data", true);
        assert!(loc.is_some());
        let loc = loc.unwrap();
        assert_eq!(loc.name, "data");
        assert_eq!(loc.kind, BindingKind::Destructure);
    }

    #[test]
    fn test_offset_to_position() {
        let content = "line1\nline2\nline3";

        // Start of line1
        let (line, col) = DefinitionService::offset_to_position(content, 0);
        assert_eq!(line, 0);
        assert_eq!(col, 0);

        // Middle of line1
        let (line, col) = DefinitionService::offset_to_position(content, 3);
        assert_eq!(line, 0);
        assert_eq!(col, 3);

        // Start of line2
        let (line, col) = DefinitionService::offset_to_position(content, 6);
        assert_eq!(line, 1);
        assert_eq!(col, 0);
    }

    #[test]
    fn test_get_word_at_offset() {
        let content = "const message = 'hello'";

        let word = DefinitionService::get_word_at_offset(content, 6);
        assert_eq!(word, Some("message".to_string()));

        let word = DefinitionService::get_word_at_offset(content, 5);
        assert_eq!(word, None); // space

        let word = DefinitionService::get_word_at_offset(content, 0);
        assert_eq!(word, Some("const".to_string()));
    }

    #[test]
    fn test_is_valid_identifier() {
        assert!(is_valid_identifier("foo"));
        assert!(is_valid_identifier("_foo"));
        assert!(is_valid_identifier("$foo"));
        assert!(is_valid_identifier("foo123"));
        assert!(!is_valid_identifier("123foo"));
        assert!(!is_valid_identifier(""));
    }
}