vize_canon 0.197.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
//! Import rewriter for transforming .vue imports to .vue.ts.
//!
//! This module uses oxc to parse TypeScript/JavaScript files and rewrite
//! import paths that reference .vue files to .vue.ts.

use oxc_allocator::Allocator;
use oxc_ast::ast::{Expression, Statement};
use oxc_ast_visit::Visit;
use oxc_ast_visit::walk;
use oxc_parser::Parser;
use oxc_span::SourceType;
use vize_carton::String;
use vize_carton::ToCompactString;
use vize_carton::cstr;

/// Offset adjustment for source map.
#[derive(Debug, Clone)]
pub struct OffsetAdjustment {
    /// Original offset before rewrite.
    pub original_offset: u32,
    /// Adjustment amount (positive = added chars, negative = removed chars).
    pub adjustment: i32,
}

/// Result of import rewriting.
#[derive(Debug)]
pub struct RewriteResult {
    /// Rewritten code.
    pub code: String,
    /// Source map for position translation.
    pub source_map: ImportSourceMap,
}

/// Source map for import rewrites.
#[derive(Debug, Default)]
pub struct ImportSourceMap {
    adjustments: Vec<OffsetAdjustment>,
}

impl ImportSourceMap {
    /// Create a new import source map.
    pub fn new(adjustments: Vec<OffsetAdjustment>) -> Self {
        Self { adjustments }
    }

    /// Create an empty source map.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Get the original offset from a virtual offset.
    pub fn get_original_offset(&self, virtual_offset: u32) -> u32 {
        let mut cumulative: i32 = 0;
        for adj in &self.adjustments {
            let adjusted = (adj.original_offset as i32 + cumulative) as u32;
            if virtual_offset < adjusted {
                break;
            }
            cumulative += adj.adjustment;
        }
        (virtual_offset as i32 - cumulative) as u32
    }

    /// Get the virtual offset from an original offset.
    pub fn get_virtual_offset(&self, original_offset: u32) -> u32 {
        let mut cumulative: i32 = 0;
        for adj in &self.adjustments {
            if original_offset < adj.original_offset {
                break;
            }
            cumulative += adj.adjustment;
        }
        (original_offset as i32 + cumulative) as u32
    }
}

/// Import rewriter that transforms .vue imports to .vue.ts.
pub struct ImportRewriter;

impl ImportRewriter {
    /// Create a new import rewriter.
    pub fn new() -> Self {
        Self
    }

    /// Rewrite imports in the given source code.
    pub fn rewrite(&self, source: &str, source_type: SourceType) -> RewriteResult {
        if !source.contains(".vue") {
            return RewriteResult {
                code: source.to_compact_string(),
                source_map: ImportSourceMap::empty(),
            };
        }

        self.rewrite_with(source, source_type, |path| {
            self.rewrite_module_specifier(path)
        })
    }

    /// Rewrite emitted declaration imports back to `.vue` specifiers.
    pub fn rewrite_declaration_specifiers(
        &self,
        source: &str,
        source_type: SourceType,
    ) -> RewriteResult {
        if !source.contains(".vue.ts") {
            return RewriteResult {
                code: source.to_compact_string(),
                source_map: ImportSourceMap::empty(),
            };
        }

        self.rewrite_with(source, source_type, |path| {
            self.rewrite_declaration_specifier(path)
        })
    }

    fn rewrite_with<F>(
        &self,
        source: &str,
        source_type: SourceType,
        rewrite_specifier: F,
    ) -> RewriteResult
    where
        F: Fn(&str) -> Option<String>,
    {
        let allocator = Allocator::default();
        let parser = Parser::new(&allocator, source, source_type);
        let result = parser.parse();

        let mut rewrites: Vec<(u32, u32, String)> = Vec::new();

        // Collect import/export rewrites
        for stmt in &result.program.body {
            match stmt {
                Statement::ImportDeclaration(decl) => {
                    if let Some(rewrite) = rewrite_specifier(&decl.source.value) {
                        rewrites.push((
                            decl.source.span.start + 1, // +1 to skip opening quote
                            decl.source.span.end - 1,   // -1 to skip closing quote
                            rewrite,
                        ));
                    }
                }
                Statement::ExportNamedDeclaration(decl) => {
                    if let Some(source) = &decl.source
                        && let Some(rewrite) = rewrite_specifier(&source.value)
                    {
                        rewrites.push((source.span.start + 1, source.span.end - 1, rewrite));
                    }
                }
                Statement::ExportAllDeclaration(decl) => {
                    if let Some(rewrite) = rewrite_specifier(&decl.source.value) {
                        rewrites.push((
                            decl.source.span.start + 1,
                            decl.source.span.end - 1,
                            rewrite,
                        ));
                    }
                }
                _ => {}
            }
        }

        // Collect dynamic imports
        let mut collector = DynamicImportCollector::new();
        collector.visit_program(&result.program);
        for (start, end, path) in collector.imports {
            if let Some(rewrite) = rewrite_specifier(&path) {
                rewrites.push((start, end, rewrite));
            }
        }

        // Sort by offset descending (process from end to start)
        rewrites.sort_by_key(|rewrite| std::cmp::Reverse(rewrite.0));

        let mut output = source.to_compact_string();
        let mut adjustments = Vec::new();

        for (start, end, new_path) in rewrites {
            let original_len = (end - start) as i32;
            let new_len = new_path.len() as i32;

            output.replace_range(start as usize..end as usize, new_path.as_str());

            adjustments.push(OffsetAdjustment {
                original_offset: start,
                adjustment: new_len - original_len,
            });
        }

        // Reverse to get ascending order
        adjustments.reverse();

        RewriteResult {
            code: output,
            source_map: ImportSourceMap::new(adjustments),
        }
    }

    /// Collect relative `.vue` import specifiers (those starting with `./`
    /// or `../`) from the source. The editor's Corsa session uses this to
    /// enumerate siblings whose virtual `.vue.ts` mirrors must be overlaid
    /// for relative resolution to succeed; alias and bare specifiers are
    /// excluded because they are handled by tsconfig `paths` and the ambient
    /// `*.vue.ts` declaration respectively. See issue #752.
    pub fn collect_relative_vue_specifiers(
        &self,
        source: &str,
        source_type: SourceType,
    ) -> Vec<String> {
        if !source.contains(".vue") {
            return Vec::new();
        }

        let allocator = Allocator::default();
        let parser = Parser::new(&allocator, source, source_type);
        let result = parser.parse();

        let mut specifiers: Vec<String> = Vec::new();
        let mut push = |path: &str| {
            if path.ends_with(".vue") && (path.starts_with("./") || path.starts_with("../")) {
                let candidate = path.to_compact_string();
                if !specifiers.iter().any(|s| s.as_str() == candidate.as_str()) {
                    specifiers.push(candidate);
                }
            }
        };

        for stmt in &result.program.body {
            match stmt {
                Statement::ImportDeclaration(decl) => push(&decl.source.value),
                Statement::ExportNamedDeclaration(decl) => {
                    if let Some(source) = &decl.source {
                        push(&source.value);
                    }
                }
                Statement::ExportAllDeclaration(decl) => push(&decl.source.value),
                _ => {}
            }
        }

        let mut collector = DynamicImportCollector::new();
        collector.visit_program(&result.program);
        for (_, _, path) in collector.imports {
            push(&path);
        }

        specifiers
    }

    /// Rewrite a module specifier if it's a .vue import.
    fn rewrite_module_specifier(&self, path: &str) -> Option<String> {
        // Rewrite every `.vue` import to `.vue.ts` so Corsa resolves the
        // generated virtual module. Relative imports (`./Foo.vue`) map directly
        // inside the mirror; tsconfig path-alias imports (`@/Foo.vue`) resolve
        // through the mirror-anchored `paths` of the virtual tsconfig. Missing
        // relative specifiers still surface as TS2307.
        if path.ends_with(".vue") {
            Some(cstr!("{path}.ts"))
        } else {
            None
        }
    }

    fn rewrite_declaration_specifier(&self, path: &str) -> Option<String> {
        if path.ends_with(".vue.ts") {
            return path
                .strip_suffix(".ts")
                .map(|value| value.to_compact_string());
        }
        None
    }
}

impl Default for ImportRewriter {
    fn default() -> Self {
        Self::new()
    }
}

/// Visitor to collect dynamic imports.
struct DynamicImportCollector {
    imports: Vec<(u32, u32, String)>,
}

impl DynamicImportCollector {
    fn new() -> Self {
        Self {
            imports: Vec::new(),
        }
    }
}

impl<'a> Visit<'a> for DynamicImportCollector {
    fn visit_import_expression(&mut self, expr: &oxc_ast::ast::ImportExpression<'a>) {
        // Check if the source is a string literal
        if let Expression::StringLiteral(lit) = &expr.source {
            self.imports.push((
                lit.span.start + 1, // +1 to skip opening quote
                lit.span.end - 1,   // -1 to skip closing quote
                lit.value.as_str().into(),
            ));
        }
        walk::walk_import_expression(self, expr);
    }
}

#[cfg(test)]
mod tests {
    use super::ImportRewriter;
    use oxc_span::SourceType;

    #[test]
    fn test_rewrite_default_import() {
        let rewriter = ImportRewriter::new();
        let source = r#"import App from './App.vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(result.code, r#"import App from './App.vue.ts';"#);
    }

    #[test]
    fn test_rewrite_named_import() {
        let rewriter = ImportRewriter::new();
        let source = r#"import { helper, type Props } from './helper.vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(
            result.code,
            r#"import { helper, type Props } from './helper.vue.ts';"#
        );
    }

    #[test]
    fn test_rewrite_side_effect_import() {
        let rewriter = ImportRewriter::new();
        let source = r#"import './global.vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(result.code, r#"import './global.vue.ts';"#);
    }

    #[test]
    fn test_no_rewrite_npm_import() {
        let rewriter = ImportRewriter::new();
        let source = r#"import { ref } from 'vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(result.code, r#"import { ref } from 'vue';"#);
    }

    #[test]
    fn test_rewrite_alias_import() {
        let rewriter = ImportRewriter::new();
        let source = r#"import App, { type Props } from '@/App.vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(
            result.code,
            r#"import App, { type Props } from '@/App.vue.ts';"#
        );
    }

    #[test]
    fn test_rewrite_export_from() {
        let rewriter = ImportRewriter::new();
        let source = r#"export { default as App } from './App.vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(
            result.code,
            r#"export { default as App } from './App.vue.ts';"#
        );
    }

    #[test]
    fn test_rewrite_dynamic_import() {
        let rewriter = ImportRewriter::new();
        let source = r#"const App = () => import('./App.vue');"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(result.code, r#"const App = () => import('./App.vue.ts');"#);
    }

    #[test]
    fn test_rewrite_parent_path() {
        let rewriter = ImportRewriter::new();
        let source = r#"import Parent from '../Parent.vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        assert_eq!(result.code, r#"import Parent from '../Parent.vue.ts';"#);
    }

    #[test]
    fn test_source_map_offset() {
        let rewriter = ImportRewriter::new();
        let source = r#"import App from './App.vue';
import { ref } from 'vue';
const x = 1;"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        // .vue -> .vue.ts adds 3 characters
        // Position after the rewrite should map back correctly
        let virtual_offset = 30; // After the first import
        let original_offset = result.source_map.get_original_offset(virtual_offset);

        // The adjustment is +3 (.ts added), so virtual - 3 = original
        assert!(original_offset < virtual_offset);
    }

    #[test]
    fn test_collect_relative_vue_specifiers() {
        let rewriter = ImportRewriter::new();
        let source = r#"import App from './App.vue';
import Sibling from '../shared/Sibling.vue';
import Aliased from '@/Aliased.vue';
import { ref } from 'vue';
import Lazy from './App.vue';
const Lazy2 = () => import('./Lazy.vue');
export { default as Re } from './Re.vue';
"#;
        let mut found = rewriter.collect_relative_vue_specifiers(source, SourceType::ts());
        found.sort();
        // Aliased and bare specifiers are intentionally excluded.
        assert_eq!(
            found.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
            [
                "../shared/Sibling.vue",
                "./App.vue",
                "./Lazy.vue",
                "./Re.vue"
            ]
        );
    }

    #[test]
    fn test_multiple_rewrites() {
        let rewriter = ImportRewriter::new();
        let source = r#"import App from './App.vue';
import Child from './Child.vue';
import { ref } from 'vue';"#;
        let result = rewriter.rewrite(source, SourceType::ts());

        insta::assert_snapshot!(result.code.as_str());
    }
}