vize_canon 0.13.0

Canon - The standard of correctness for Vize type checking
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
//! Type intelligence for Vue SFCs.
//!
//! Provides hover, completion, diagnostics, and navigation without IDE dependencies.
//! Can be used by LSP servers, playgrounds, CLI tools, etc.
//!
//! Design principles:
//! - Zero allocation in common paths
//! - Returns references where possible
//! - Lazy computation (only compute what's needed)
//! - Reusable across IDE and non-IDE contexts

use vize_carton::cstr;
use vize_carton::CompactString;
use vize_croquis::Croquis;
use vize_relief::BindingType;

use crate::source_map::{MappingKind, SourceMap, Span};

/// Hover information result.
#[derive(Debug, Clone)]
pub struct HoverInfo<'a> {
    /// Display text (markdown)
    pub contents: CompactString,
    /// Range in source that this hover applies to
    pub range: Option<Span>,
    /// The binding name if hovering over a binding
    pub binding_name: Option<&'a str>,
    /// The binding type if hovering over a binding
    pub binding_type: Option<BindingType>,
}

/// Completion item.
#[derive(Debug, Clone)]
pub struct Completion {
    /// Label shown in completion list
    pub label: CompactString,
    /// Kind of completion (variable, function, etc.)
    pub kind: CompletionKind,
    /// Detail text (type signature, etc.)
    pub detail: Option<CompactString>,
    /// Documentation (markdown)
    pub documentation: Option<CompactString>,
    /// Text to insert (if different from label)
    pub insert_text: Option<CompactString>,
    /// Sort priority (lower = higher priority)
    pub sort_priority: u8,
}

/// Completion item kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum CompletionKind {
    Variable = 1,
    Function = 2,
    Property = 3,
    Constant = 4,
    Component = 5,
    Directive = 6,
    Event = 7,
    Slot = 8,
    Keyword = 9,
}

/// Location in source.
#[derive(Debug, Clone, Copy)]
pub struct Location {
    /// Byte offset range
    pub span: Span,
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DiagnosticSeverity {
    Error = 1,
    Warning = 2,
    Info = 3,
    Hint = 4,
}

/// A diagnostic message.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// Severity level
    pub severity: DiagnosticSeverity,
    /// Human-readable message
    pub message: CompactString,
    /// Location in source
    pub span: Span,
    /// Error code (optional)
    pub code: Option<CompactString>,
}

/// Context for where the cursor is in the SFC.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CursorContext {
    /// In script block
    Script,
    /// In script setup block
    ScriptSetup,
    /// In template interpolation {{ expr }}
    Interpolation,
    /// In directive expression v-if="expr"
    DirectiveExpr,
    /// In directive argument :prop
    DirectiveArg,
    /// In event handler @click="handler"
    EventHandler,
    /// In v-for variable
    VForVar,
    /// In style block
    Style,
    /// Unknown context
    Unknown,
}

impl From<MappingKind> for CursorContext {
    fn from(kind: MappingKind) -> Self {
        match kind {
            MappingKind::Script => CursorContext::Script,
            MappingKind::Interpolation => CursorContext::Interpolation,
            MappingKind::DirectiveExpr => CursorContext::DirectiveExpr,
            MappingKind::DirectiveArg => CursorContext::DirectiveArg,
            MappingKind::EventHandler => CursorContext::EventHandler,
            MappingKind::VForVar => CursorContext::VForVar,
            MappingKind::SlotBinding => CursorContext::Unknown,
            MappingKind::ComponentRef => CursorContext::Unknown,
            MappingKind::Unknown => CursorContext::Unknown,
        }
    }
}

/// Type intelligence provider for Vue SFCs.
///
/// Provides IDE-like features without IDE dependencies.
/// Designed for reuse in LSP, playground, CLI tools, etc.
pub struct TypeIntelligence<'a> {
    /// Source code
    source: &'a str,
    /// Analysis summary from croquis
    summary: &'a Croquis,
    /// Source map for position mapping
    source_map: Option<&'a SourceMap>,
    /// Virtual TypeScript content
    virtual_ts: Option<&'a str>,
}

impl<'a> TypeIntelligence<'a> {
    /// Create a new TypeIntelligence provider.
    #[inline]
    pub fn new(source: &'a str, summary: &'a Croquis) -> Self {
        Self {
            source,
            summary,
            source_map: None,
            virtual_ts: None,
        }
    }

    /// Set source map for position mapping.
    #[inline]
    pub fn with_source_map(mut self, source_map: &'a SourceMap) -> Self {
        self.source_map = Some(source_map);
        self
    }

    /// Set virtual TypeScript for tsgo integration.
    #[inline]
    pub fn with_virtual_ts(mut self, virtual_ts: &'a str) -> Self {
        self.virtual_ts = Some(virtual_ts);
        self
    }

    /// Get the cursor context at the given offset.
    #[inline]
    pub fn cursor_context(&self, offset: u32) -> CursorContext {
        if let Some(map) = self.source_map {
            if let Some(mapping) = map.find_by_source(offset) {
                return mapping.kind.into();
            }
        }

        // Fallback: check if in script block
        // This is a simplified check - real implementation would check SFC blocks
        CursorContext::Unknown
    }

    /// Get hover information at the given offset.
    pub fn hover(&self, offset: u32) -> Option<HoverInfo<'a>> {
        // Find the identifier at offset
        let (name, span) = self.find_identifier_at(offset)?;

        // Look up binding in summary
        if let Some(&binding_type) = self.summary.bindings.bindings.get(name) {
            let contents = format_binding_hover(name, binding_type);
            return Some(HoverInfo {
                contents,
                range: Some(span),
                binding_name: Some(name),
                binding_type: Some(binding_type),
            });
        }

        // Check if it's a Vue global
        if let Some(contents) = get_vue_global_hover(name) {
            return Some(HoverInfo {
                contents,
                range: Some(span),
                binding_name: Some(name),
                binding_type: None,
            });
        }

        None
    }

    /// Get completions at the given offset.
    pub fn completions(&self, offset: u32) -> Vec<Completion> {
        let context = self.cursor_context(offset);
        let mut completions = Vec::with_capacity(32);

        match context {
            CursorContext::ScriptSetup | CursorContext::Script => {
                // Add Vue Composition API completions
                add_vue_api_completions(&mut completions);
            }
            CursorContext::Interpolation
            | CursorContext::DirectiveExpr
            | CursorContext::EventHandler => {
                // Add script setup bindings
                self.add_binding_completions(&mut completions);
                // Add Vue template globals
                add_vue_global_completions(&mut completions);
            }
            CursorContext::DirectiveArg => {
                // Add directive-specific completions
                add_directive_arg_completions(&mut completions);
            }
            _ => {
                // Default: add all bindings
                self.add_binding_completions(&mut completions);
            }
        }

        // Sort by priority
        completions.sort_unstable_by_key(|c| c.sort_priority);
        completions
    }

    /// Get definition location for identifier at offset.
    pub fn definition(&self, offset: u32) -> Option<Location> {
        let (name, _) = self.find_identifier_at(offset)?;

        if let Some(&(start, end)) = self.summary.binding_spans.get(name) {
            return Some(Location {
                span: Span::new(start, end),
            });
        }

        None
    }

    /// Find identifier at the given offset.
    /// Returns (name, span) or None if not on an identifier.
    fn find_identifier_at(&self, offset: u32) -> Option<(&'a str, Span)> {
        let bytes = self.source.as_bytes();
        let offset = offset as usize;

        if offset >= bytes.len() {
            return None;
        }

        // Check if we're on an identifier character
        if !is_ident_char(bytes[offset]) {
            return None;
        }

        // Find start of identifier
        let mut start = offset;
        while start > 0 && is_ident_char(bytes[start - 1]) {
            start -= 1;
        }

        // Find end of identifier
        let mut end = offset;
        while end < bytes.len() && is_ident_char(bytes[end]) {
            end += 1;
        }

        let name = std::str::from_utf8(&bytes[start..end]).ok()?;
        Some((name, Span::new(start as u32, end as u32)))
    }

    /// Add binding completions from summary.
    fn add_binding_completions(&self, completions: &mut Vec<Completion>) {
        for (name, &binding_type) in self.summary.bindings.bindings.iter() {
            let kind = binding_type_to_completion_kind(binding_type);
            let detail = Some(cstr!("{binding_type:?}"));

            completions.push(Completion {
                label: CompactString::new(name),
                kind,
                detail,
                documentation: None,
                insert_text: None,
                sort_priority: 10,
            });
        }
    }
}

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

/// Convert binding type to completion kind.
fn binding_type_to_completion_kind(bt: BindingType) -> CompletionKind {
    match bt {
        BindingType::SetupConst | BindingType::SetupLet | BindingType::LiteralConst => {
            CompletionKind::Constant
        }
        BindingType::SetupRef
        | BindingType::SetupReactiveConst
        | BindingType::SetupMaybeRef
        | BindingType::Data => CompletionKind::Variable,
        BindingType::Props | BindingType::PropsAliased => CompletionKind::Property,
        BindingType::Options => CompletionKind::Property,
        BindingType::JsGlobalUniversal
        | BindingType::JsGlobalBrowser
        | BindingType::JsGlobalNode
        | BindingType::JsGlobalDeno
        | BindingType::JsGlobalBun
        | BindingType::VueGlobal
        | BindingType::ExternalModule => CompletionKind::Variable,
    }
}

/// Format binding hover content.
fn format_binding_hover(name: &str, binding_type: BindingType) -> CompactString {
    let type_str = match binding_type {
        BindingType::SetupRef => "Ref",
        BindingType::SetupReactiveConst => "Reactive",
        BindingType::SetupConst => "const",
        BindingType::SetupLet => "let",
        BindingType::SetupMaybeRef => "MaybeRef",
        BindingType::Props => "props",
        BindingType::PropsAliased => "props (aliased)",
        BindingType::Data => "data",
        BindingType::Options => "options",
        BindingType::LiteralConst => "literal const",
        BindingType::JsGlobalUniversal => "global",
        BindingType::JsGlobalBrowser => "browser global",
        BindingType::JsGlobalNode => "node global",
        BindingType::JsGlobalDeno => "deno global",
        BindingType::JsGlobalBun => "bun global",
        BindingType::VueGlobal => "vue global",
        BindingType::ExternalModule => "external module",
    };
    cstr!("```typescript\n{name}: {type_str}\n```")
}

/// Get hover for Vue template globals.
fn get_vue_global_hover(name: &str) -> Option<CompactString> {
    let content = match name {
        "$attrs" => "```typescript\n$attrs: Record<string, unknown>\n```\n\nFallthrough attributes not declared as props.",
        "$slots" => "```typescript\n$slots: Slots\n```\n\nSlots passed by parent component.",
        "$emit" => "```typescript\n$emit(event: string, ...args: any[]): void\n```\n\nTrigger a custom event.",
        "$refs" => "```typescript\n$refs: Record<string, any>\n```\n\nTemplate refs registered via `ref` attribute.",
        "$el" => "```typescript\n$el: HTMLElement | undefined\n```\n\nRoot DOM element.",
        "$props" => "```typescript\n$props: Props\n```\n\nResolved props object.",
        "$data" => "```typescript\n$data: Record<string, unknown>\n```\n\nReactive data object.",
        "$options" => "```typescript\n$options: ComponentOptions\n```\n\nComponent options.",
        "$parent" => "```typescript\n$parent: ComponentPublicInstance | null\n```\n\nParent component instance.",
        "$root" => "```typescript\n$root: ComponentPublicInstance\n```\n\nRoot component instance.",
        "$watch" => "```typescript\n$watch(source, callback, options?): StopHandle\n```\n\nCreate a watcher.",
        "$forceUpdate" => "```typescript\n$forceUpdate(): void\n```\n\nForce re-render.",
        "$nextTick" => "```typescript\n$nextTick(callback?): Promise<void>\n```\n\nRun callback after next DOM update.",
        _ => return None,
    };
    Some(CompactString::new(content))
}

/// Add Vue API completions.
fn add_vue_api_completions(completions: &mut Vec<Completion>) {
    const VUE_API: &[(&str, &str)] = &[
        ("ref", "ref<T>(value: T): Ref<T>"),
        ("reactive", "reactive<T>(target: T): Reactive<T>"),
        ("computed", "computed<T>(getter: () => T): ComputedRef<T>"),
        ("watch", "watch(source, callback, options?)"),
        ("watchEffect", "watchEffect(effect, options?)"),
        ("onMounted", "onMounted(callback)"),
        ("onUnmounted", "onUnmounted(callback)"),
        ("defineProps", "defineProps<T>()"),
        ("defineEmits", "defineEmits<T>()"),
        ("defineExpose", "defineExpose(exposed)"),
        ("defineModel", "defineModel<T>(name?, options?)"),
    ];

    for (name, detail) in VUE_API {
        completions.push(Completion {
            label: CompactString::new(*name),
            kind: CompletionKind::Function,
            detail: Some(CompactString::new(*detail)),
            documentation: None,
            insert_text: None,
            sort_priority: 5,
        });
    }
}

/// Add Vue template global completions.
fn add_vue_global_completions(completions: &mut Vec<Completion>) {
    const GLOBALS: &[(&str, &str)] = &[
        ("$attrs", "Fallthrough attributes"),
        ("$slots", "Slots from parent"),
        ("$emit", "Emit event"),
        ("$refs", "Template refs"),
        ("$el", "Root element"),
        ("$props", "Props object"),
        ("$parent", "Parent instance"),
        ("$root", "Root instance"),
    ];

    for (name, detail) in GLOBALS {
        completions.push(Completion {
            label: CompactString::new(*name),
            kind: CompletionKind::Property,
            detail: Some(CompactString::new(*detail)),
            documentation: None,
            insert_text: None,
            sort_priority: 20,
        });
    }
}

/// Add directive argument completions.
fn add_directive_arg_completions(completions: &mut Vec<Completion>) {
    const EVENTS: &[&str] = &[
        "click",
        "input",
        "change",
        "submit",
        "focus",
        "blur",
        "keydown",
        "keyup",
        "keypress",
        "mouseenter",
        "mouseleave",
        "scroll",
    ];

    for event in EVENTS {
        completions.push(Completion {
            label: CompactString::new(*event),
            kind: CompletionKind::Event,
            detail: Some(CompactString::new("DOM event")),
            documentation: None,
            insert_text: None,
            sort_priority: 15,
        });
    }
}

#[cfg(test)]
mod tests {
    use super::{get_vue_global_hover, is_ident_char, TypeIntelligence};
    use vize_carton::CompactString;
    use vize_croquis::Croquis;
    use vize_relief::BindingType;

    #[test]
    fn test_is_ident_char() {
        assert!(is_ident_char(b'a'));
        assert!(is_ident_char(b'Z'));
        assert!(is_ident_char(b'0'));
        assert!(is_ident_char(b'_'));
        assert!(is_ident_char(b'$'));
        assert!(!is_ident_char(b' '));
        assert!(!is_ident_char(b'.'));
    }

    #[test]
    fn test_vue_global_hover() {
        assert!(get_vue_global_hover("$attrs").is_some());
        assert!(get_vue_global_hover("$emit").is_some());
        assert!(get_vue_global_hover("unknown").is_none());
    }

    #[test]
    fn test_definition_lookup() {
        // Source: "const count = ref(0)"
        let source = "const count = ref(0)";
        let mut summary = Croquis::default();
        summary
            .bindings
            .bindings
            .insert(CompactString::new("count"), BindingType::SetupRef);
        // "count" starts at offset 6, ends at 11
        summary
            .binding_spans
            .insert(CompactString::new("count"), (6, 11));

        let intel = TypeIntelligence::new(source, &summary);

        // Cursor on "count" (offset 7) should find definition
        let loc = intel.definition(7);
        assert!(loc.is_some());
        let loc = loc.unwrap();
        assert_eq!(loc.span.start, 6);
        assert_eq!(loc.span.end, 11);
    }

    #[test]
    fn test_definition_unknown_ident() {
        let source = "const count = ref(0)";
        let summary = Croquis::default();
        let intel = TypeIntelligence::new(source, &summary);

        // "count" not in binding_spans → None
        let loc = intel.definition(7);
        assert!(loc.is_none());
    }

    #[test]
    fn test_definition_not_on_ident() {
        let source = "const count = ref(0)";
        let summary = Croquis::default();
        let intel = TypeIntelligence::new(source, &summary);

        // Offset 5 is space → None
        let loc = intel.definition(5);
        assert!(loc.is_none());
    }
}