vize_canon 0.29.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
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
//! Main virtual TypeScript generation entry points.
//!
//! Contains the public `generate_virtual_ts` and `generate_virtual_ts_with_offsets`
//! functions that orchestrate the full virtual TypeScript generation pipeline.

use vize_croquis::{BindingType, Croquis, ScopeData, ScopeKind, COMPILER_MACRO_NAMES};

use super::{
    helpers::{
        generate_template_context, to_safe_identifier, IMPORT_META_AUGMENTATION,
        VUE_SETUP_COMPILER_MACROS,
    },
    props::{generate_props_type, generate_props_variables},
    scope::generate_scope_closures,
    types::{VirtualTsOptions, VirtualTsOutput, VizeMapping},
};
use vize_carton::append;
use vize_carton::cstr;
use vize_carton::String;

/// Generate virtual TypeScript from Vue SFC analysis.
///
/// The generated TypeScript uses proper scope hierarchy:
/// 1. Module scope: imports only
/// 2. Setup scope (__setup function): compiler macros + script content
/// 3. Template scope (nested in setup): template expressions
///
/// This ensures compiler macros like defineProps are ONLY valid in setup scope.
pub fn generate_virtual_ts(
    summary: &Croquis,
    script_content: Option<&str>,
    template_ast: Option<&vize_relief::ast::RootNode<'_>>,
    template_offset: u32,
) -> VirtualTsOutput {
    generate_virtual_ts_with_offsets(
        summary,
        script_content,
        template_ast,
        0,
        template_offset,
        &VirtualTsOptions::default(),
    )
}

/// Generate virtual TypeScript with explicit script and template offsets.
///
/// `script_offset` is the byte offset of the script content within the SFC file.
/// `template_offset` is the byte offset of the template content within the SFC file.
/// When these are provided, source mappings point to SFC-absolute positions.
/// `options` controls template globals and other generation settings.
pub fn generate_virtual_ts_with_offsets(
    summary: &Croquis,
    script_content: Option<&str>,
    template_ast: Option<&vize_relief::ast::RootNode<'_>>,
    script_offset: u32,
    template_offset: u32,
    options: &VirtualTsOptions,
) -> VirtualTsOutput {
    let mut ts = String::default();
    let mut mappings: Vec<VizeMapping> = Vec::new();

    // Header with ES target library references.
    // These ensure import.meta, Promise, Array.includes(), etc. are available.
    ts.push_str("/// <reference lib=\"es2022\" />\n");
    ts.push_str("/// <reference lib=\"dom\" />\n");
    ts.push_str("/// <reference lib=\"dom.iterable\" />\n");
    ts.push_str("// ============================================\n");
    ts.push_str("// Virtual TypeScript for Vue SFC Type Checking\n");
    ts.push_str("// Generated by vize\n");
    ts.push_str("// ============================================\n\n");

    // Check for generic type parameter from <script setup generic="T">
    let (generic_param, mut is_async) = summary
        .scopes
        .iter()
        .find(|s| matches!(s.kind, ScopeKind::ScriptSetup))
        .map(|s| {
            if let ScopeData::ScriptSetup(data) = s.data() {
                (data.generic.as_ref().map(|s| s.as_str()), data.is_async)
            } else {
                (None, false)
            }
        })
        .unwrap_or((None, false));

    // Also detect top-level await in script content (Vue 3 script setup supports this)
    if let Some(script) = script_content {
        if script.contains("await ") && !is_async {
            is_async = true;
        }
    }

    // ImportMeta augmentation (must be at top level, before any code)
    ts.push_str(IMPORT_META_AUGMENTATION);
    ts.push('\n');

    // Vue type alias (shorthand for import('vue') type references).
    // Requires node_modules/vue to be resolvable (symlinked in temp dir).
    ts.push_str("type $Vue = import('vue');\n\n");

    // Module scope: Extract imports, re-exports, and type declarations to module level.
    // Type declarations (interface, type, enum) must be at module level so they
    // are accessible from `export type Props = ...` outside __setup().
    ts.push_str("// ========== Module Scope (imports) ==========\n");

    // Collect all module-level statement spans from croquis analysis
    let mut module_spans: Vec<(u32, u32)> = Vec::new();
    for imp in &summary.import_statements {
        module_spans.push((imp.start, imp.end));
    }
    for re in &summary.re_exports {
        module_spans.push((re.start, re.end));
    }
    for te in &summary.type_exports {
        module_spans.push((te.start, te.end));
    }
    module_spans.sort_by_key(|&(start, _)| start);

    if let Some(script) = script_content {
        // Emit each module-level statement with source mapping
        for &(start, end) in &module_spans {
            let text = &script[start as usize..end as usize];
            let gen_start = ts.len();
            ts.push_str(text);
            ts.push('\n');
            let gen_end = ts.len();
            mappings.push(VizeMapping {
                gen_range: gen_start..gen_end,
                src_range: (script_offset as usize + start as usize)
                    ..(script_offset as usize + end as usize),
            });
        }

        // Void-reference imported names that match compiler macro names.
        // These get shadowed by __setup() declarations, causing TS6133 at module level.
        let shadowed_imports: Vec<&&str> = COMPILER_MACRO_NAMES
            .iter()
            .filter(|&&name| summary.bindings.bindings.contains_key(name))
            .collect();
        if !shadowed_imports.is_empty() {
            ts.push_str("// Prevent TS6133 for imports shadowed by setup-scope compiler macros\n");
            for name in &shadowed_imports {
                append!(ts, "void {name};\n");
            }
        }
    }

    // Auto-import stubs (e.g., Nuxt composables)
    // Only emit stubs for names NOT already declared via imports or bindings.
    // Collect imported names from all module-level import statements to handle
    // cases where plain <script> imports are not in summary.bindings (which
    // only holds <script setup> bindings when both blocks exist).
    let imported_names: Vec<&str> = if let Some(script) = script_content {
        summary
            .import_statements
            .iter()
            .flat_map(|imp| {
                let text = script
                    .get(imp.start as usize..imp.end as usize)
                    .unwrap_or("");
                extract_import_names(text)
            })
            .collect()
    } else {
        Vec::new()
    };
    if !options.auto_import_stubs.is_empty() {
        let mut has_header = false;
        for stub in &options.auto_import_stubs {
            let name = extract_declared_name(stub);
            if let Some(name) = name {
                // Skip if already imported or declared in script bindings
                if summary.bindings.bindings.contains_key(name) || imported_names.contains(&name) {
                    continue;
                }
            }
            if !has_header {
                ts.push_str("\n// Auto-import stubs (framework-provided globals)\n");
                has_header = true;
            }
            ts.push_str(stub);
            ts.push('\n');
        }
    }
    ts.push('\n');

    // Props type (defined at module level so it's available inside __setup)
    generate_props_type(&mut ts, summary, generic_param);

    // Setup scope: function that contains compiler macros and script content
    ts.push_str("// ========== Setup Scope ==========\n");
    let async_prefix = if is_async { "async " } else { "" };
    let generic_params = generic_param.map(|g| cstr!("<{g}>")).unwrap_or_default();
    append!(ts, "{async_prefix}function __setup{generic_params}() {{\n",);

    // Compiler macros (only valid inside setup scope)
    ts.push_str(VUE_SETUP_COMPILER_MACROS);
    ts.push_str("\n\n");

    // User's script content (minus imports)
    if let Some(script) = script_content {
        ts.push_str("  // User setup code\n");
        let script_gen_start = ts.len();
        // Use split('\n') to correctly track byte offsets for CRLF files.
        // Rust's lines() strips \r from CRLF but +1 for \n undercounts,
        // causing src_byte_offset drift that incorrectly skips user code.
        let raw_lines: Vec<&str> = script.split('\n').collect();
        let mut src_byte_offset: usize = 0; // offset within script content

        // Check if script uses import.meta and add a polyfill variable.
        // This avoids TS1343 when module is not set to es2020+.
        let uses_import_meta = script.contains("import.meta");
        if uses_import_meta {
            ts.push_str("  const __import_meta: any = {};\n");
        }

        for raw_line in raw_lines.iter() {
            // Strip trailing \r for output (normalize CRLF to LF)
            let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
            // raw_line.len() includes \r if present; +1 for the \n from split
            let raw_byte_len = raw_line.len() + 1;

            // Skip lines that overlap with module-level spans (imports, re-exports, type decls)
            let line_start = src_byte_offset;
            let line_end = line_start + raw_line.len(); // use raw length for span check
            let is_module_level = module_spans
                .iter()
                .any(|&(s, e)| line_start < e as usize && line_end > s as usize);
            if is_module_level {
                src_byte_offset += raw_byte_len;
                continue;
            }
            let gen_line_start = ts.len();
            ts.push_str("  "); // indentation (not in source)
            let gen_content_start = ts.len();

            // Process the line: strip `export` keyword (invalid inside function),
            // replace import.meta with polyfill variable
            let mut output_line = std::borrow::Cow::Borrowed(line);

            // Strip `export` from non-import lines inside setup scope
            let trimmed_line = output_line.trim_start();
            if trimmed_line.starts_with("export ")
                && !trimmed_line.starts_with("export type ")
                && !trimmed_line.starts_with("export interface ")
            {
                let leading_ws = &output_line[..output_line.len() - trimmed_line.len()];
                let rest = trimmed_line.strip_prefix("export ").unwrap();
                #[allow(clippy::disallowed_types)]
                {
                    output_line = std::borrow::Cow::Owned(cstr!("{leading_ws}{rest}").into());
                }
            }

            // Replace import.meta with polyfill variable to avoid TS1343
            if uses_import_meta && output_line.contains("import.meta") {
                #[allow(clippy::disallowed_types)]
                {
                    output_line = std::borrow::Cow::Owned(
                        output_line.replace("import.meta", "__import_meta"),
                    );
                }
            }

            ts.push_str(&output_line);
            let gen_content_end = ts.len();
            ts.push('\n');
            // Map the line content (excluding the "  " indent prefix)
            if !line.is_empty() {
                let src_line_start = script_offset as usize + src_byte_offset;
                let src_line_end = src_line_start + line.len();
                mappings.push(VizeMapping {
                    gen_range: gen_content_start..gen_content_end,
                    src_range: src_line_start..src_line_end,
                });
            }
            let _ = gen_line_start; // suppress unused warning
            src_byte_offset += raw_byte_len;
        }
        let script_gen_end = ts.len();
        append!(
            ts,
            "  // @vize-map: {script_gen_start}:{script_gen_end} -> 0:{}\n\n",
            script.len()
        );
    }

    // Template scope (nested inside setup)
    if template_ast.is_some() {
        ts.push_str("  // ========== Template Scope (inherits from setup) ==========\n");

        // Collect ref bindings for auto-unwrapping in template
        let ref_bindings: Vec<&str> = summary
            .bindings
            .bindings
            .iter()
            .filter(|(_, bt)| matches!(bt, BindingType::SetupRef | BindingType::SetupMaybeRef))
            .map(|(name, _)| name.as_str())
            .collect();

        // Capture ref types BEFORE template scope to avoid circular references.
        // `typeof count` here refers to the setup-scope Ref<number>.
        if !ref_bindings.is_empty() {
            ts.push_str("  // Ref type captures (before template scope shadows them)\n");
            for name in &ref_bindings {
                append!(ts, "  type __Ref_{name} = typeof {name};\n");
            }
        }

        // Semicolon prevents ASI issues when user script doesn't end with `;`
        // (e.g., `console.log(x)\n(function...)` would be parsed as a call)
        ts.push_str("  ;(function __template() {\n");

        // Shadow ref bindings with unwrapped types.
        // `var` allows reassignment (Vue templates can assign to refs).
        if !ref_bindings.is_empty() {
            ts.push_str("    // Auto-unwrap refs (Vue template behavior)\n");
            ts.push_str("    type __UnwrapRef<T> = import('vue').UnwrapRef<T>;\n");
            for name in &ref_bindings {
                append!(
                    ts,
                    "    var {name}: __UnwrapRef<__Ref_{name}> = undefined as any;\n"
                );
            }
        }

        // Vue template context (available in template expressions)
        ts.push_str(&generate_template_context(options));
        ts.push('\n');

        // Props are available in template as variables
        generate_props_variables(&mut ts, summary, script_content, generic_param);

        // Generate scope closures
        generate_scope_closures(&mut ts, &mut mappings, summary, template_offset);

        // Declare unresolved components (auto-imported or built-in) as `any`
        if !summary.used_components.is_empty() {
            let mut has_unresolved = false;
            for component in &summary.used_components {
                let name = component.as_str();
                // Skip if already declared via script bindings (import/const)
                if summary.bindings.bindings.contains_key(name) {
                    continue;
                }
                if !has_unresolved {
                    ts.push_str(
                        "\n  // Auto-imported/built-in components (not in script bindings)\n",
                    );
                    has_unresolved = true;
                }
                let safe = to_safe_identifier(name);
                append!(ts, "  const {safe}: any = undefined as any;\n");
            }

            ts.push_str("\n  // Mark used components as referenced\n");
            for component in &summary.used_components {
                let safe = to_safe_identifier(component.as_str());
                append!(ts, "  void {safe};\n");
            }
        }

        // Reference all setup bindings to prevent TS6133 for variables
        // used only in CSS v-bind() or other non-template contexts
        if !summary.bindings.bindings.is_empty() {
            ts.push_str("\n  // Reference setup bindings (used in template/CSS v-bind)\n  ");
            let mut first = true;
            for name in summary.bindings.bindings.keys() {
                // Skip bindings that are JS keywords or would cause syntax errors
                if matches!(
                    name.as_str(),
                    "default"
                        | "class"
                        | "new"
                        | "delete"
                        | "void"
                        | "typeof"
                        | "in"
                        | "instanceof"
                        | "return"
                        | "switch"
                        | "case"
                        | "break"
                        | "continue"
                        | "throw"
                        | "try"
                        | "catch"
                        | "finally"
                        | "if"
                        | "else"
                        | "for"
                        | "while"
                        | "do"
                        | "with"
                        | "var"
                        | "let"
                        | "const"
                        | "function"
                        | "this"
                        | "super"
                        | "import"
                        | "export"
                        | "yield"
                        | "await"
                        | "async"
                        | "static"
                        | "enum"
                        | "implements"
                        | "interface"
                        | "package"
                        | "private"
                        | "protected"
                        | "public"
                ) {
                    continue;
                }
                if !first {
                    ts.push(' ');
                }
                append!(ts, "void {name};");
                first = false;
            }
            ts.push('\n');
        }

        ts.push_str("  })();\n");
    }

    // Reference props destructure bindings at setup scope level.
    // These variables are declared in user script (e.g., `const { foo } = defineProps<...>()`)
    // but shadowed inside __template() by generate_props_variables, so void them here.
    if let Some(destructure) = summary.macros.props_destructure() {
        if !destructure.bindings.is_empty() {
            ts.push_str("\n  // Reference destructured props (prevent TS6133)\n  ");
            let mut first = true;
            for binding in destructure.bindings.values() {
                if !first {
                    ts.push(' ');
                }
                append!(ts, "void {};", binding.local);
                first = false;
            }
            if let Some(ref rest) = destructure.rest_id {
                if !first {
                    ts.push(' ');
                }
                append!(ts, "void {};", rest);
            }
            ts.push('\n');
        }
    }

    // Return exposed object from __setup() so its type can be extracted at module level.
    // This keeps the runtime args expression in scope (where the bindings are defined).
    let has_runtime_expose = summary
        .macros
        .define_expose()
        .is_some_and(|e| e.type_args.is_none() && e.runtime_args.is_some());
    if has_runtime_expose {
        let runtime_args = summary
            .macros
            .define_expose()
            .unwrap()
            .runtime_args
            .as_ref()
            .unwrap();
        append!(ts, "\n  return ({runtime_args});\n");
    }

    // Close setup function
    ts.push_str("}\n\n");

    // Invoke setup (void suppresses TS2349 for async/generic functions)
    ts.push_str("// Invoke setup to verify types\n");
    ts.push_str("void __setup();\n\n");

    // Emits type
    let emits_already_defined = summary
        .type_exports
        .iter()
        .any(|te| te.name.as_str() == "Emits");
    if !emits_already_defined {
        ts.push_str("export type Emits = {};\n");
    }

    // Slots type
    let slots_type_args = summary
        .macros
        .define_slots()
        .and_then(|m| m.type_args.as_ref());
    if let Some(type_args) = slots_type_args {
        let inner_type = type_args
            .strip_prefix('<')
            .and_then(|s| s.strip_suffix('>'))
            .unwrap_or(type_args.as_str());
        append!(ts, "export type Slots = {inner_type};\n");
    } else {
        ts.push_str("export type Slots = {};\n");
    }

    // Exposed type (for InstanceType and useTemplateRef)
    if let Some(expose) = summary.macros.define_expose() {
        if let Some(ref type_args) = expose.type_args {
            let inner_type = type_args
                .strip_prefix('<')
                .and_then(|s| s.strip_suffix('>'))
                .unwrap_or(type_args.as_str());
            append!(ts, "export type Exposed = {inner_type};\n");
        } else if expose.runtime_args.is_some() {
            // Runtime args are returned from __setup() to keep them in scope.
            // Use Awaited<ReturnType<...>> to handle both sync and async setup.
            ts.push_str("export type Exposed = Awaited<ReturnType<typeof __setup>>;\n");
        }
    }
    ts.push('\n');

    // Default export
    ts.push_str("// ========== Default Export ==========\n");
    ts.push_str("declare const __vize_component__: {\n");
    ts.push_str("  props: Props;\n");
    ts.push_str("  emits: Emits;\n");
    ts.push_str("  slots: Slots;\n");
    ts.push_str("};\n");
    ts.push_str("export default __vize_component__;\n");

    VirtualTsOutput { code: ts, mappings }
}

/// Extract imported identifier names from an import statement string.
/// Handles `import { a, b as c } from "..."` and `import D from "..."`.
/// Returns the local names (e.g., `["a", "c", "D"]`).
fn extract_declared_name(stub: &str) -> Option<&str> {
    for prefix in [
        "declare function ",
        "declare const ",
        "declare let ",
        "declare var ",
    ] {
        let Some(rest) = stub.strip_prefix(prefix) else {
            continue;
        };
        let end = rest
            .find(['<', '(', ':', '=', ';', ' '])
            .unwrap_or(rest.len());
        let name = rest[..end].trim();
        if !name.is_empty() {
            return Some(name);
        }
    }

    None
}

fn extract_import_names(import_text: &str) -> Vec<&str> {
    let mut names = Vec::new();

    // Find the content between { and }
    if let Some(brace_start) = import_text.find('{') {
        if let Some(brace_end) = import_text.find('}') {
            let inner = &import_text[brace_start + 1..brace_end];
            for part in inner.split(',') {
                let part = part.trim();
                if part.is_empty() || part.starts_with("//") || part.starts_with("type ") {
                    continue;
                }
                // Handle "name as alias" -> use alias
                if let Some(as_pos) = part.find(" as ") {
                    let alias = part[as_pos + 4..].trim();
                    if !alias.is_empty() {
                        names.push(alias);
                    }
                } else {
                    // Simple name (strip \r for CRLF files)
                    let name = part.strip_suffix('\r').unwrap_or(part);
                    if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                        names.push(name);
                    }
                }
            }
        }
    } else {
        // Handle `import Name from "..."`
        let text = import_text.trim();
        if let Some(rest) = text.strip_prefix("import ") {
            if let Some(from_pos) = rest.find(" from ") {
                let name = rest[..from_pos].trim();
                if !name.is_empty()
                    && !name.contains('{')
                    && !name.contains('*')
                    && name.chars().all(|c| c.is_alphanumeric() || c == '_')
                {
                    names.push(name);
                }
            }
        }
    }

    names
}