vize_canon 0.199.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
//! Options API template-binding emission for the virtual TypeScript generator.

use oxc_allocator::Allocator;
use oxc_ast::ast::{
    Argument, ArrayExpressionElement, ArrowFunctionExpression, CallExpression,
    ExportDefaultDeclarationKind, Expression, Function, ObjectExpression, ObjectPropertyKind,
    Program, PropertyKey, Statement,
};
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType};
use vize_croquis::{BindingType, Croquis};

use crate::virtual_ts::types::VirtualTsOptions;
use vize_carton::CompactString;
use vize_carton::FxHashSet;
use vize_carton::String;
use vize_carton::append;

// Emit `const <name>: any` declarations for Options API template bindings
// (`data`/`computed`/`methods`/`inject`/`setup`/`props`, plus any Nuxt 2 globals
// the legacy path collected). Options API is officially supported in Vue 3, so
// this is part of the standard build and driven by a runtime opt-in — it costs
// nothing unless the caller enables Options API / legacy checking.
pub(super) fn generate_options_api_variables(
    mut ts: &mut String,
    summary: &Croquis,
    options: &VirtualTsOptions,
) {
    let macro_prop_names: FxHashSet<&str> = summary
        .macros
        .props()
        .iter()
        .map(|prop| prop.name.as_str())
        .collect();
    let configured_globals: FxHashSet<&str> = options
        .template_globals
        .iter()
        .map(|global| global.name.as_str())
        .collect();
    let mut names: Vec<&str> = summary
        .bindings
        .bindings
        .iter()
        .filter_map(|(name, binding_type)| {
            let name = name.as_str();
            match binding_type {
                BindingType::Data | BindingType::Options | BindingType::VueGlobal => Some(name),
                BindingType::Props if !macro_prop_names.contains(name) => Some(name),
                _ => None,
            }
        })
        .filter(|name| !configured_globals.contains(name))
        .filter(|name| is_safe_value_identifier(name))
        .collect();
    names.sort_unstable();
    names.dedup();

    if names.is_empty() {
        return;
    }

    ts.push_str("  // Options API template bindings\n");
    for name in &names {
        append!(ts, "  const {name}: any = undefined as any;\n");
    }
    ts.push_str("  ");
    for name in &names {
        append!(ts, "void {name};");
    }
    ts.push('\n');
}

pub(super) fn generate_options_api_bridge(mut ts: &mut String, summary: &Croquis, script: &str) {
    let Some(bridge) = collect_options_api_bridge(script) else {
        return;
    };

    let mut names: Vec<&str> = summary
        .bindings
        .bindings
        .iter()
        .filter_map(|(name, binding_type)| {
            let name = name.as_str();
            match binding_type {
                BindingType::Data | BindingType::Options | BindingType::Props => {
                    is_safe_value_identifier(name).then_some(name)
                }
                _ => None,
            }
        })
        .collect();
    names.sort_unstable();
    names.dedup();

    if names.is_empty()
        && bridge.computed.is_empty()
        && bridge.methods.is_empty()
        && bridge.mapped_types.is_empty()
    {
        return;
    }

    ts.push_str("  // Options API typed instance bridge\n");
    for (index, mapped_type) in bridge.mapped_types.iter().enumerate() {
        append!(
            ts,
            "  type __VizeOptionsMap{index} = {{ {mapped_type} }};\n"
        );
    }
    ts.push_str("  type __VizeThis = {\n");
    for name in names {
        append!(ts, "    {name}: any;\n");
    }
    ts.push_str("  }");
    for index in 0..bridge.mapped_types.len() {
        append!(ts, " & __VizeOptionsMap{index}");
    }
    ts.push_str(";\n");

    for function in &bridge.computed {
        emit_bridge_function(ts, "computed", function);
    }
    for function in &bridge.methods {
        emit_bridge_function(ts, "method", function);
    }

    if !bridge.computed.is_empty() || !bridge.methods.is_empty() {
        ts.push_str("  ");
        let mut first = true;
        for function in bridge.computed.iter().chain(bridge.methods.iter()) {
            if !first {
                ts.push(' ');
            }
            append!(
                ts,
                "void __vize_{}_{};",
                function.kind_prefix(),
                function.safe_name
            );
            first = false;
        }
        ts.push('\n');
    }
    ts.push('\n');
}

fn emit_bridge_function(mut ts: &mut String, kind: &str, function: &OptionsFunction) {
    let params = if function.params.is_empty() {
        String::from("this: __VizeThis")
    } else {
        let mut params = String::from("this: __VizeThis, ");
        params.push_str(&function.params);
        params
    };
    append!(
        ts,
        "  function __vize_{kind}_{}({params}) ",
        function.safe_name
    );
    ts.push_str(&function.body);
    ts.push('\n');
}

#[derive(Debug, Default)]
struct OptionsApiBridge {
    computed: Vec<OptionsFunction>,
    methods: Vec<OptionsFunction>,
    mapped_types: Vec<String>,
}

#[derive(Debug)]
struct OptionsFunction {
    kind: OptionsFunctionKind,
    safe_name: CompactString,
    params: String,
    body: String,
}

impl OptionsFunction {
    fn kind_prefix(&self) -> &'static str {
        match self.kind {
            OptionsFunctionKind::Computed => "computed",
            OptionsFunctionKind::Method => "method",
        }
    }
}

#[derive(Debug)]
enum OptionsFunctionKind {
    Computed,
    Method,
}

fn collect_options_api_bridge(script: &str) -> Option<OptionsApiBridge> {
    let allocator = Allocator::default();
    let parsed = Parser::new(&allocator, script, SourceType::ts()).parse();
    if parsed.panicked {
        return None;
    }

    let options = component_options_from_program(&parsed.program)?;
    let mut bridge = OptionsApiBridge::default();
    collect_function_bridge(
        script,
        options,
        "computed",
        OptionsFunctionKind::Computed,
        &mut bridge.computed,
        &mut bridge.mapped_types,
    );
    collect_function_bridge(
        script,
        options,
        "methods",
        OptionsFunctionKind::Method,
        &mut bridge.methods,
        &mut bridge.mapped_types,
    );
    Some(bridge)
}

fn collect_function_bridge(
    script: &str,
    options: &ObjectExpression<'_>,
    option_name: &str,
    kind: OptionsFunctionKind,
    output: &mut Vec<OptionsFunction>,
    mapped_types: &mut Vec<String>,
) {
    let Some(object) = option_object_property(options, option_name) else {
        return;
    };

    for property in &object.properties {
        match property {
            ObjectPropertyKind::ObjectProperty(property) => {
                if property.computed {
                    continue;
                }
                let Some(name) = property_key_name(&property.key) else {
                    continue;
                };
                let Some(function) = options_function_from_expression(
                    script,
                    name,
                    &property.value,
                    match kind {
                        OptionsFunctionKind::Computed => OptionsFunctionKind::Computed,
                        OptionsFunctionKind::Method => OptionsFunctionKind::Method,
                    },
                ) else {
                    continue;
                };
                output.push(function);
            }
            ObjectPropertyKind::SpreadProperty(spread) => {
                if let Expression::CallExpression(call) = &spread.argument {
                    collect_mapped_type(call, mapped_types);
                }
            }
        }
    }
}

fn options_function_from_expression(
    script: &str,
    name: &str,
    expression: &Expression<'_>,
    kind: OptionsFunctionKind,
) -> Option<OptionsFunction> {
    let (params, body) = match expression {
        Expression::FunctionExpression(function) => function_parts(script, function)?,
        Expression::ArrowFunctionExpression(arrow) => arrow_function_parts(script, arrow)?,
        Expression::ParenthesizedExpression(parenthesized) => {
            return options_function_from_expression(script, name, &parenthesized.expression, kind);
        }
        Expression::TSAsExpression(ts_as) => {
            return options_function_from_expression(script, name, &ts_as.expression, kind);
        }
        Expression::TSSatisfiesExpression(ts_satisfies) => {
            return options_function_from_expression(script, name, &ts_satisfies.expression, kind);
        }
        Expression::TSNonNullExpression(ts_non_null) => {
            return options_function_from_expression(script, name, &ts_non_null.expression, kind);
        }
        _ => return None,
    };

    Some(OptionsFunction {
        kind,
        safe_name: CompactString::new(safe_identifier(name).as_str()),
        params,
        body,
    })
}

fn function_parts(script: &str, function: &Function<'_>) -> Option<(String, String)> {
    let params = params_source(script, &function.params)?;
    let body = function.body.as_ref()?;
    let body_source = source_slice(script, body.span())?;
    Some((params, String::from(body_source.trim())))
}

fn arrow_function_parts(
    script: &str,
    arrow: &ArrowFunctionExpression<'_>,
) -> Option<(String, String)> {
    let params = params_source(script, &arrow.params)?;
    let body_source = source_slice(script, arrow.body.span())?.trim();
    if arrow.expression {
        let mut body = String::from("{ return ");
        body.push_str(body_source.trim_end_matches(';'));
        body.push_str("; }");
        Some((params, body))
    } else {
        Some((params, String::from(body_source)))
    }
}

fn params_source(script: &str, params: &oxc_ast::ast::FormalParameters<'_>) -> Option<String> {
    let mut result = String::default();
    let mut first = true;
    for param in params.items.iter() {
        if !first {
            result.push_str(", ");
        }
        first = false;
        result.push_str(source_slice(script, param.span())?.trim());
    }
    if let Some(rest) = params.rest.as_ref() {
        if !first {
            result.push_str(", ");
        }
        result.push_str(source_slice(script, rest.span())?.trim());
    }
    Some(result)
}

fn collect_mapped_type(call: &CallExpression<'_>, mapped_types: &mut Vec<String>) {
    let Expression::Identifier(callee) = &call.callee else {
        return;
    };
    if !matches!(
        callee.name.as_str(),
        "mapState" | "mapGetters" | "mapWritableState" | "mapActions"
    ) {
        return;
    }

    let Some(Argument::Identifier(store)) = call.arguments.first() else {
        return;
    };
    let Some(Argument::ArrayExpression(keys)) = call.arguments.get(1) else {
        return;
    };
    let keys: Vec<&str> = keys
        .elements
        .iter()
        .filter_map(|element| {
            let ArrayExpressionElement::StringLiteral(literal) = element else {
                return None;
            };
            Some(literal.value.as_str())
        })
        .collect();
    if keys.is_empty() {
        return;
    }

    let mut key_union = String::default();
    for (index, key) in keys.iter().enumerate() {
        if index > 0 {
            key_union.push_str(" | ");
        }
        append!(key_union, "'{key}'");
    }

    let mut mapped_type = String::default();
    append!(
        mapped_type,
        "[K in {key_union}]: ReturnType<typeof {}>[K]",
        store.name.as_str()
    );
    mapped_types.push(mapped_type);
}

fn component_options_from_program<'a>(
    program: &'a Program<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    program.body.iter().find_map(|statement| {
        let Statement::ExportDefaultDeclaration(export) = statement else {
            return None;
        };
        component_options_from_export(&export.declaration)
    })
}

fn component_options_from_export<'a>(
    declaration: &'a ExportDefaultDeclarationKind<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    match declaration {
        ExportDefaultDeclarationKind::ObjectExpression(object) => Some(object.as_ref()),
        ExportDefaultDeclarationKind::CallExpression(call) => component_options_from_call(call),
        ExportDefaultDeclarationKind::ParenthesizedExpression(parenthesized) => {
            component_options_from_expression(&parenthesized.expression)
        }
        ExportDefaultDeclarationKind::TSAsExpression(ts_as) => {
            component_options_from_expression(&ts_as.expression)
        }
        ExportDefaultDeclarationKind::TSSatisfiesExpression(ts_satisfies) => {
            component_options_from_expression(&ts_satisfies.expression)
        }
        ExportDefaultDeclarationKind::TSNonNullExpression(ts_non_null) => {
            component_options_from_expression(&ts_non_null.expression)
        }
        _ => None,
    }
}

fn component_options_from_expression<'a>(
    expression: &'a Expression<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    match expression {
        Expression::ObjectExpression(object) => Some(object.as_ref()),
        Expression::CallExpression(call) => component_options_from_call(call),
        Expression::ParenthesizedExpression(parenthesized) => {
            component_options_from_expression(&parenthesized.expression)
        }
        Expression::TSAsExpression(ts_as) => component_options_from_expression(&ts_as.expression),
        Expression::TSSatisfiesExpression(ts_satisfies) => {
            component_options_from_expression(&ts_satisfies.expression)
        }
        Expression::TSNonNullExpression(ts_non_null) => {
            component_options_from_expression(&ts_non_null.expression)
        }
        _ => None,
    }
}

fn component_options_from_call<'a>(
    call: &'a CallExpression<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    if !is_define_component_callee(&call.callee) {
        return None;
    }
    let first = call.arguments.first()?;
    match first {
        Argument::ObjectExpression(object) => Some(object.as_ref()),
        Argument::CallExpression(call) => component_options_from_call(call),
        Argument::ParenthesizedExpression(parenthesized) => {
            component_options_from_expression(&parenthesized.expression)
        }
        Argument::TSAsExpression(ts_as) => component_options_from_expression(&ts_as.expression),
        Argument::TSSatisfiesExpression(ts_satisfies) => {
            component_options_from_expression(&ts_satisfies.expression)
        }
        Argument::TSNonNullExpression(ts_non_null) => {
            component_options_from_expression(&ts_non_null.expression)
        }
        _ => None,
    }
}

fn is_define_component_callee(callee: &Expression<'_>) -> bool {
    match callee {
        Expression::Identifier(callee) => {
            matches!(callee.name.as_str(), "defineComponent" | "_defineComponent")
        }
        Expression::StaticMemberExpression(member) => {
            matches!(
                member.property.name.as_str(),
                "defineComponent" | "_defineComponent"
            )
        }
        _ => false,
    }
}

fn option_object_property<'a>(
    object: &'a ObjectExpression<'a>,
    key_name: &str,
) -> Option<&'a ObjectExpression<'a>> {
    object.properties.iter().find_map(|property| {
        let ObjectPropertyKind::ObjectProperty(property) = property else {
            return None;
        };
        if property.computed || property_key_name(&property.key) != Some(key_name) {
            return None;
        }
        object_expression_from_expression(&property.value)
    })
}

fn object_expression_from_expression<'a>(
    expression: &'a Expression<'a>,
) -> Option<&'a ObjectExpression<'a>> {
    match expression {
        Expression::ObjectExpression(object) => Some(object.as_ref()),
        Expression::ParenthesizedExpression(parenthesized) => {
            object_expression_from_expression(&parenthesized.expression)
        }
        Expression::TSAsExpression(ts_as) => object_expression_from_expression(&ts_as.expression),
        Expression::TSSatisfiesExpression(ts_satisfies) => {
            object_expression_from_expression(&ts_satisfies.expression)
        }
        Expression::TSNonNullExpression(ts_non_null) => {
            object_expression_from_expression(&ts_non_null.expression)
        }
        _ => None,
    }
}

fn property_key_name<'a>(key: &'a PropertyKey<'a>) -> Option<&'a str> {
    match key {
        PropertyKey::StaticIdentifier(identifier) => Some(identifier.name.as_str()),
        PropertyKey::StringLiteral(string) => Some(string.value.as_str()),
        _ => None,
    }
}

fn source_slice(script: &str, span: oxc_span::Span) -> Option<&str> {
    script.get(span.start as usize..span.end as usize)
}

fn safe_identifier(name: &str) -> String {
    let mut result = String::default();
    for (index, ch) in name.chars().enumerate() {
        if (index == 0 && (ch.is_ascii_alphabetic() || ch == '_' || ch == '$'))
            || (index > 0 && (ch.is_ascii_alphanumeric() || ch == '_' || ch == '$'))
        {
            result.push(ch);
        } else {
            result.push('_');
        }
    }
    if result.is_empty() {
        result.push('_');
    }
    result
}

fn is_safe_value_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
        return false;
    }
    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '$')
}