vize_atelier_core 0.149.0

Atelier Core - The core workshop for Vize Vue template parsing and transforms
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! VDom code generation.
//!
//! This module generates JavaScript render function code from the transformed AST.

mod children;
mod context;
mod element;
mod expression;
mod generate;
mod helpers;
mod node;
mod patch_flag;
mod props;
mod root;
mod slots;
mod v_for;
mod v_if;

use crate::{
    ast::{RootNode, RuntimeHelper, TemplateChildNode},
    options::CodegenOptions,
};
use vize_carton::profile;

use children::is_directive_comment;
pub use context::{CodegenContext, CodegenResult};
use element::generate_root_node;
use generate::{collect_hoist_helpers, generate_hoists};
use node::generate_node;
use root::{
    generate_assets, generate_function_signature, generate_preamble_from_helpers,
    is_ignorable_root_text,
};

/// Generate code from root AST.
pub fn generate(root: &RootNode<'_>, options: CodegenOptions) -> CodegenResult {
    let mut ctx = CodegenContext::new(options);
    let root_children: std::vec::Vec<&TemplateChildNode<'_>> = root
        .children
        .iter()
        .filter(|child| !is_ignorable_root_text(child) && !is_directive_comment(child))
        .collect();

    // Generate function signature
    profile!(
        "atelier.codegen.function_signature",
        generate_function_signature(&mut ctx)
    );

    // Generate body
    ctx.indent();
    ctx.newline();

    // Generate component/directive resolution
    profile!("atelier.codegen.assets", generate_assets(&mut ctx, root));

    // Generate return statement
    ctx.push("return ");

    // Generate root node
    if root_children.is_empty() {
        ctx.push("null");
    } else if root_children.len() == 1 {
        // Single root child - wrap in block
        profile!(
            "atelier.codegen.root_node",
            generate_root_node(&mut ctx, root_children[0])
        );
    } else {
        // Multiple root children - wrap in fragment block
        ctx.use_helper(RuntimeHelper::OpenBlock);
        ctx.use_helper(RuntimeHelper::CreateElementBlock);
        ctx.use_helper(RuntimeHelper::Fragment);
        ctx.push("(");
        ctx.push(ctx.helper(RuntimeHelper::OpenBlock));
        ctx.push("(), ");
        ctx.push(ctx.helper(RuntimeHelper::CreateElementBlock));
        ctx.push("(");
        ctx.push(ctx.helper(RuntimeHelper::Fragment));
        ctx.push(", null, [");
        ctx.indent();
        for (i, child) in root_children.iter().enumerate() {
            if i > 0 {
                ctx.push(",");
            }
            ctx.newline();
            profile!(
                "atelier.codegen.fragment_child",
                generate_node(&mut ctx, child)
            );
        }
        ctx.deindent();
        ctx.newline();
        // Vue tags a root fragment as DEV_ROOT_FRAGMENT when it wraps a single
        // real node plus comment siblings, so dev tooling treats it as a root.
        let non_comment_children = root_children
            .iter()
            .filter(|child| !matches!(child, TemplateChildNode::Comment(_)))
            .count();
        if non_comment_children == 1 {
            ctx.push("], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))");
        } else {
            ctx.push("], 64 /* STABLE_FRAGMENT */))");
        }
    }

    ctx.deindent();
    ctx.newline();
    ctx.push("}");

    // Now generate preamble after we know all used helpers
    // Only include specific helpers from root.helpers that are known to be
    // added during transform but not tracked during codegen (like Unref)
    // We don't merge ALL root.helpers because transform may add helpers that
    // get optimized away during codegen (e.g., createElementVNode -> createElementBlock)
    let mut all_helpers: Vec<RuntimeHelper> = ctx.used_helpers.iter().copied().collect();
    if root.helpers.contains(&RuntimeHelper::Unref) && !all_helpers.contains(&RuntimeHelper::Unref)
    {
        all_helpers.push(RuntimeHelper::Unref);
    }
    // Collect helpers from hoisted nodes - generate_hoists() takes &CodegenContext (immutable)
    // so helpers used in hoisted VNodes aren't tracked via use_helper(). Pre-scan them here.
    profile!(
        "atelier.codegen.collect_hoist_helpers",
        collect_hoist_helpers(root, &mut all_helpers)
    );
    // Sort helpers for consistent output order
    all_helpers.sort();
    all_helpers.dedup();

    let mut preamble = profile!(
        "atelier.codegen.preamble",
        generate_preamble_from_helpers(&ctx, &all_helpers)
    );

    // Generate hoisted variable declarations (appended to preamble)
    let hoists_code = profile!("atelier.codegen.hoists", generate_hoists(&ctx, root));
    if !hoists_code.is_empty() {
        preamble.push('\n');
        preamble.push_str(&hoists_code);
    }

    CodegenResult {
        code: ctx.into_code(),
        preamble,
        map: None,
    }
}

#[cfg(test)]
#[allow(clippy::disallowed_macros)]
mod tests {
    use crate::compile;

    fn result_output(result: &super::CodegenResult) -> vize_carton::String {
        let mut output =
            vize_carton::String::with_capacity(result.preamble.len() + result.code.len() + 1);
        output.push_str(&result.preamble);
        output.push('\n');
        output.push_str(&result.code);
        output
    }

    macro_rules! assert_codegen_snapshot {
        ($result:expr) => {{
            let output = result_output(&$result);
            insta::assert_snapshot!(output.as_str());
        }};
    }

    #[test]
    fn test_codegen_simple_element() {
        let result = compile!("<div>hello</div>");
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_interpolation() {
        // When prefix_identifiers is false (default), expressions are not prefixed with _ctx.
        let result = compile!("<div>{{ msg }}</div>");
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_with_props() {
        let result = compile!(r#"<div id="app" class="container"></div>"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_component() {
        let result = compile!("<MyComponent />");
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_component_name_with_colon_uses_valid_identifier() {
        let allocator = bumpalo::Bump::new();
        let parser_opts = crate::ParserOptions {
            is_native_tag: Some(vize_carton::is_native_tag),
            ..Default::default()
        };
        let (mut root, errors) = crate::parse_with_options(
            &allocator,
            r#"<global:head title="Page Title" />"#,
            parser_opts,
        );
        assert!(errors.is_empty(), "Parse errors: {:?}", errors);

        crate::transform::transform(
            &allocator,
            &mut root,
            crate::TransformOptions::default(),
            None,
        );
        let output = result_output(&super::generate(&root, crate::CodegenOptions::default()));

        // Vue encodes non-word characters by char code (`:` -> 58), matching
        // `toValidAssetId` (issue #4422).
        assert!(
            output.contains(r#"const _component_global58head = _resolveComponent("global:head")"#)
        );
        assert!(output.contains("_createBlock(_component_global58head"));
        assert!(!output.contains("_component_global:head"));
    }

    #[test]
    fn test_codegen_self_component_resolve_marks_maybe_self_reference() {
        let result = compile!(
            "<FileTree />",
            super::CodegenOptions {
                component_name: Some("FileTree".into()),
                ..Default::default()
            }
        );
        let output = result_output(&result);

        assert!(
            output.contains(r#"const _component_FileTree = _resolveComponent("FileTree", true)"#),
            "self component resolution should pass maybeSelfReference. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_root_directive_comment_does_not_create_fragment_hole() {
        let result =
            compile!("<!-- @vize:forget sections are labeled by their headings --><section />");

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_root_only_directive_comment_compiles_to_null() {
        let result = compile!("<!-- @vize:forget no render output -->");

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_pascal_case_dynamic_component() {
        let result = compile!(r#"<Component :is="current" :active-class="klass" />"#);

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_pascal_case_dynamic_component_inside_v_for() {
        let result =
            compile!(r#"<Component :is="item.component" v-for="item in items" :key="item.id" />"#);

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_if_template_fragment_wraps_interpolation_in_text_vnode() {
        let result = compile!(
            r#"<p><template v-if="ready">{{ count }}</template><span v-if="pending">updating</span></p>"#
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_if_template_fragment_wraps_static_text_in_text_vnode() {
        let result = compile!(
            r#"<div><template v-if="ready">Found packages</template><span v-if="pending">updating</span></div>"#
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_preamble_module() {
        use crate::options::CodegenMode;
        let options = super::CodegenOptions {
            mode: CodegenMode::Module,
            ..Default::default()
        };
        let result = compile!("<div>hello</div>", options);
        insta::assert_snapshot!(result.preamble.as_str());
    }

    #[test]
    fn test_codegen_v_model_on_component() {
        let result = compile!(r#"<MyComponent v-model="msg" />"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_model_with_arg() {
        let result = compile!(r#"<MyComponent v-model:title="pageTitle" />"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_model_on_input() {
        let result = compile!(r#"<input v-model="inputValue" />"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_model_with_other_props() {
        // v-model with other props should not produce comments
        let result = compile!(r#"<MonacoEditor v-model="source" :language="editorLanguage" />"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_slot_fallback() {
        let result = compile!(r#"<slot name="label">{{ label }}</slot>"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_slot_without_fallback() {
        // Slot element without fallback should not have empty object or function
        let result = compile!(r#"<slot name="header"></slot>"#);
        insta::assert_snapshot!(result.code.as_str());
    }

    #[test]
    fn test_codegen_conditional_slot_outlet_with_bound_props_uses_render_slot() {
        let result = compile!(r#"<slot v-if="show" name="updater" v-bind="{ number, update }" />"#);
        let output = result_output(&result);

        assert!(
            output.contains(r#"_renderSlot(_ctx.$slots, "updater""#),
            "conditional slot outlet should use renderSlot. Got:\n{}",
            output
        );
        assert!(
            output.contains(r#"_mergeProps({ number, update }, { key: 0 })"#),
            "v-bind object props should be merged with the branch key. Got:\n{}",
            output
        );
        assert!(
            !output.contains(r#"_createElementBlock("slot""#)
                && !output.contains(r#"_createElementVNode("slot""#),
            "slot outlets should not be emitted as literal slot elements. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_codegen_v_for_slot_outlet_with_bound_props_uses_render_slot() {
        let result = compile!(
            r#"<slot v-for="(item, index) of items" v-bind="{ key: item.id }" :item="item" :index="index" />"#
        );
        let output = result_output(&result);

        assert!(
            output.contains(r#"_renderSlot(_ctx.$slots, "default""#),
            "v-for slot outlet should use renderSlot. Got:\n{}",
            output
        );
        assert!(
            output.contains(r#"_mergeProps({ key: item.id }, { item: item, index: index })"#),
            "slot v-bind object props should be preserved with explicit props. Got:\n{}",
            output
        );
        assert!(
            !output.contains(r#"_createElementBlock("slot""#)
                && !output.contains(r#"_createElementVNode("slot""#),
            "slot outlets should not be emitted as literal slot elements. Got:\n{}",
            output
        );
    }

    #[test]
    fn test_codegen_conditional_slot_with_else_does_not_append_undefined() {
        let result = compile!(
            r#"<MyDialog>
  <template v-if="step === 1" #header>First</template>
  <template v-else #header>Second</template>
</MyDialog>"#
        );
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_conditional_named_slot_preserves_implicit_default_slot() {
        let result = compile!(
            r#"<Parent>
  Not rendering!
  <template v-if="showNamed" #named>
    Named content
  </template>
</Parent>"#
        );
        let output = result_output(&result);

        assert!(
            output.contains("default: _withCtx(() => ["),
            "implicit default slot should be generated when createSlots is used:\n{}",
            output
        );
        assert!(
            output.contains("Not rendering!"),
            "default slot text should be preserved:\n{}",
            output
        );
        assert!(
            output.contains("name: \"named\""),
            "conditional named slot should still be dynamic:\n{}",
            output
        );
    }

    #[test]
    fn test_codegen_default_slot_with_v_if_is_stable() {
        let result = compile!(
            r#"<PageWithHeader>
  <div v-if="tab === 'overview'">Overview</div>
  <div v-else-if="tab === 'emojis'">Emojis</div>
  <div v-else>Charts</div>
</PageWithHeader>"#
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_forwarded_default_slot_is_marked_forwarded() {
        let result = compile!(r#"<MkSwiper><slot /></MkSwiper>"#);

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_if_branch_mixed_children_wrap_interpolations_in_text_vnodes() {
        let result = compile!(
            r#"<p v-if="speaker.affiliation || speaker.title">{{ speaker.affiliation }}<br v-if="speaker.affiliation && speaker.title" />{{ speaker.title }}</p>"#
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_if_branch_mixed_children_wraps_interpolation_in_text_vnode() {
        let result = compile!(
            r#"<div><label v-if="show">{{ msg }}<span v-if="required">*</span></label></div>"#
        );

        assert!(
            result
                .code
                .contains("_createTextVNode(_toDisplayString(msg), 1 /* TEXT */)"),
            "mixed children inside v-if branch should wrap interpolation in createTextVNode. Got:\n{}",
            result.code
        );
        assert!(
            !result.code.contains("[_toDisplayString(msg),"),
            "v-if branch should not emit raw string children inside arrays. Got:\n{}",
            result.code
        );
    }

    #[test]
    fn test_codegen_v_for_aliases_without_parentheses_stay_local() {
        use crate::options::{CodegenOptions, TransformOptions};
        use crate::parser::parse;
        use crate::transform::transform;
        use bumpalo::Bump;

        let allocator = Bump::new();
        let (mut root, _) = parse(
            &allocator,
            r#"<div><template v-for="item, index of items" :key="index"><UserCard :user="item" :data-index="index" /></template></div>"#,
        );

        transform(
            &allocator,
            &mut root,
            TransformOptions {
                prefix_identifiers: true,
                ..Default::default()
            },
            None,
        );

        let result = super::generate(
            &root,
            CodegenOptions {
                prefix_identifiers: true,
                ..Default::default()
            },
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_numeric_template_v_for_uses_fragment() {
        let result = compile!(
            r#"<div><template v-for="n in 4" :key="`set-${n}`"><button /><span v-for="(icon, i) in icons" :key="`${n}-${i}`" :class="icon" /></template></div>"#
        );

        assert!(
            !result.code.contains("\"template\""),
            "template v-for must not create a DOM template element. Got:\n{}",
            result.code
        );
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_v_for_scope_handlers_are_not_cached() {
        use crate::options::{CodegenOptions, TransformOptions};
        use crate::parser::parse;
        use crate::transform::transform;
        use bumpalo::Bump;

        let allocator = Bump::new();
        let (mut root, _) = parse(
            &allocator,
            r#"<button v-for="tab in tabs" :key="tab.id" @click="select(tab)">{{ tab.label }}</button>"#,
        );

        transform(
            &allocator,
            &mut root,
            TransformOptions {
                prefix_identifiers: true,
                ..Default::default()
            },
            None,
        );

        let result = super::generate(
            &root,
            CodegenOptions {
                prefix_identifiers: true,
                cache_handlers: true,
                ..Default::default()
            },
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_scoped_slot_params_stay_local_in_handlers() {
        use crate::options::{CodegenOptions, TransformOptions};
        use crate::parser::parse;
        use crate::transform::transform;
        use bumpalo::Bump;

        let allocator = Bump::new();
        let (mut root, _) = parse(
            &allocator,
            r#"<CommonPaginator>
  <template #default="{ item, index }">
    <button @click="showHistory(item)">{{ index }}</button>
    <button @click="() => edit(item.id)">{{ item.id }}</button>
  </template>
</CommonPaginator>"#,
        );

        transform(
            &allocator,
            &mut root,
            TransformOptions {
                prefix_identifiers: true,
                ..Default::default()
            },
            None,
        );

        let result = super::generate(
            &root,
            CodegenOptions {
                prefix_identifiers: true,
                cache_handlers: true,
                ..Default::default()
            },
        );

        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_escape_newline_in_attribute() {
        // Attribute values containing newlines should be properly escaped
        let result = compile!(
            r#"<div style="
            color: red;
            background: blue;
        "></div>"#
        );
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_escape_special_chars_in_attribute() {
        // Attribute values should escape backslashes and quotes
        let result = compile!(r#"<div data-value="line1\nline2"></div>"#);
        assert_codegen_snapshot!(result);
    }

    #[test]
    fn test_codegen_escape_multiline_style_attribute() {
        // Complex multiline style attribute (real-world case from Discord issue)
        let result = compile!(
            r#"<div style="
            display: flex;
            flex-direction: column;
        "></div>"#
        );
        assert_codegen_snapshot!(result);
    }
}