vize_atelier_core 0.64.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
//! Structural directive transforms (v-if, v-for).

use vize_carton::{Box, String, Vec};

use crate::ast::*;
use crate::errors::ErrorCode;

use super::context::clone_expression;
use super::traverse::traverse_children;
use super::{ExitFn, ParentNode, TransformContext};

/// Simple expression content for passing between functions
pub struct SimpleExpressionContent {
    pub content: String,
    pub is_static: bool,
    pub loc: SourceLocation,
}

#[derive(Clone, Copy)]
pub enum StructuralDirectiveKind {
    If,
    ElseIf,
    Else,
    For,
}

fn directive_expression_to_content(exp: ExpressionNode<'_>) -> SimpleExpressionContent {
    match exp {
        ExpressionNode::Simple(s) => {
            let s = Box::into_inner(s);
            SimpleExpressionContent {
                content: s.content,
                is_static: s.is_static,
                loc: s.loc,
            }
        }
        ExpressionNode::Compound(c) => {
            let c = Box::into_inner(c);
            let loc = c.loc;
            SimpleExpressionContent {
                content: loc.source.clone(),
                is_static: false,
                loc,
            }
        }
    }
}

/// Take the highest-priority structural directive from an element.
///
/// In Vue 3, v-if has higher priority than v-for when both are present on the same element.
/// This removes the selected directive from the element in the same pass we discover it.
pub fn take_structural_directive<'a>(
    el: &mut Box<'a, ElementNode<'a>>,
) -> Option<(StructuralDirectiveKind, Option<SimpleExpressionContent>)> {
    let mut selected_if = None;
    let mut selected_for = None;

    for (idx, prop) in el.props.iter().enumerate() {
        if let PropNode::Directive(dir) = prop {
            match dir.name.as_str() {
                "if" => {
                    selected_if = Some((idx, StructuralDirectiveKind::If));
                    break;
                }
                "else-if" => {
                    selected_if = Some((idx, StructuralDirectiveKind::ElseIf));
                    break;
                }
                "else" => {
                    selected_if = Some((idx, StructuralDirectiveKind::Else));
                    break;
                }
                "for" if selected_for.is_none() => {
                    selected_for = Some((idx, StructuralDirectiveKind::For));
                }
                _ => {}
            }
        }
    }

    let (directive_idx, directive_kind) = selected_if.or(selected_for)?;
    let directive = match el.props.remove(directive_idx) {
        PropNode::Directive(dir) => Box::into_inner(dir),
        PropNode::Attribute(_) => unreachable!("structural directives are always directive props"),
    };

    Some((
        directive_kind,
        directive.exp.map(directive_expression_to_content),
    ))
}

/// Extract and remove key prop from element
pub fn extract_key_prop<'a>(el: &mut ElementNode<'a>) -> Option<PropNode<'a>> {
    let mut key_index = None;
    for (i, prop) in el.props.iter().enumerate() {
        match prop {
            PropNode::Attribute(attr) if attr.name == "key" => {
                key_index = Some(i);
                break;
            }
            PropNode::Directive(dir) if dir.name == "bind" => {
                if let Some(ExpressionNode::Simple(arg)) = &dir.arg {
                    if arg.content == "key" {
                        key_index = Some(i);
                        break;
                    }
                }
            }
            _ => {}
        }
    }
    key_index.map(|i| el.props.remove(i))
}

/// Transform v-if directive
pub fn transform_v_if<'a>(
    ctx: &mut TransformContext<'a>,
    exp: Option<&SimpleExpressionContent>,
    is_root: bool,
) -> Option<std::vec::Vec<ExitFn<'a>>> {
    let allocator = ctx.allocator;

    if is_root {
        // Take the current element from parent
        let taken = ctx.take_current_node();
        let taken_node = taken?;

        // Get element info before moving
        let (element_loc, is_template_if) = match &taken_node {
            TemplateChildNode::Element(el) => {
                (el.loc.clone(), el.tag_type == ElementType::Template)
            }
            _ => return None,
        };

        // Create condition expression and process it for identifier prefixing
        let condition = exp.map(|e| {
            let raw_exp = ExpressionNode::Simple(Box::new_in(
                SimpleExpressionNode {
                    content: e.content.clone(),
                    is_static: e.is_static,
                    const_type: if e.is_static {
                        ConstantType::CanStringify
                    } else {
                        ConstantType::NotConstant
                    },
                    loc: e.loc.clone(),
                    js_ast: None,
                    hoisted: None,
                    identifiers: None,
                    is_handler_key: false,
                    is_ref_transformed: false,
                },
                allocator,
            ));
            // Process expression to add $setup. prefix
            if ctx.options.prefix_identifiers || ctx.options.is_ts {
                crate::transforms::transform_expression::process_expression(ctx, &raw_exp, false)
            } else {
                raw_exp
            }
        });

        // Extract user key from the element if present,
        // but NOT if the element also has v-for (the key belongs to v-for in that case)
        let mut user_key = None;
        let taken_node = match taken_node {
            TemplateChildNode::Element(mut el) => {
                let has_v_for = el
                    .props
                    .iter()
                    .any(|p| matches!(p, PropNode::Directive(d) if d.name.as_str() == "for"));
                if !has_v_for {
                    user_key = extract_key_prop(&mut el);
                }
                TemplateChildNode::Element(el)
            }
            other => other,
        };

        // Process user_key expression for identifier prefixing (e.g., keyA -> _ctx.keyA)
        if let Some(PropNode::Directive(ref mut dir)) = user_key {
            if ctx.options.prefix_identifiers || ctx.options.is_ts {
                if let Some(ref exp) = dir.exp {
                    let processed = crate::transforms::transform_expression::process_expression(
                        ctx, exp, false,
                    );
                    dir.exp = Some(processed);
                }
            }
        }

        // Create branch with the taken element
        let mut branch_children = Vec::new_in(allocator);
        branch_children.push(taken_node);

        let branch = IfBranchNode {
            condition,
            children: branch_children,
            user_key,
            is_template_if,
            loc: element_loc.clone(),
        };

        let mut branches = Vec::new_in(allocator);
        branches.push(branch);

        let if_node = IfNode {
            branches,
            codegen_node: None,
            loc: element_loc,
        };

        // Replace placeholder with IfNode
        ctx.replace_node(TemplateChildNode::If(Box::new_in(if_node, allocator)));

        // Add helpers
        ctx.helper(RuntimeHelper::OpenBlock);
        ctx.helper(RuntimeHelper::CreateBlock);
        ctx.helper(RuntimeHelper::Fragment);
        ctx.helper(RuntimeHelper::CreateComment);

        None
    } else {
        // Find previous v-if node and add branch to it
        let child_index = ctx.child_index;

        // First, find the if node index
        let found_if_idx = if let Some(parent) = &ctx.parent {
            let children = parent.children_mut();
            let mut found = None;

            // Look backwards for v-if node
            for j in (0..child_index).rev() {
                match &children[j] {
                    TemplateChildNode::If(_) => {
                        found = Some(j);
                        break;
                    }
                    TemplateChildNode::Comment(_) => continue,
                    TemplateChildNode::Text(t) if t.content.trim().is_empty() => continue,
                    _ => break,
                }
            }
            found
        } else {
            None
        };

        if let Some(if_idx) = found_if_idx {
            // Take current element
            let taken = ctx.take_current_node();
            let taken_node = taken?;

            let (element_loc, is_template_if) = match &taken_node {
                TemplateChildNode::Element(el) => {
                    (el.loc.clone(), el.tag_type == ElementType::Template)
                }
                _ => return None,
            };

            // Create condition for else-if, None for else
            let condition = exp.map(|e| {
                let raw_exp = ExpressionNode::Simple(Box::new_in(
                    SimpleExpressionNode {
                        content: e.content.clone(),
                        is_static: e.is_static,
                        const_type: if e.is_static {
                            ConstantType::CanStringify
                        } else {
                            ConstantType::NotConstant
                        },
                        loc: e.loc.clone(),
                        js_ast: None,
                        hoisted: None,
                        identifiers: None,
                        is_handler_key: false,
                        is_ref_transformed: false,
                    },
                    allocator,
                ));
                // Process expression to add $setup. prefix
                if ctx.options.prefix_identifiers || ctx.options.is_ts {
                    crate::transforms::transform_expression::process_expression(
                        ctx, &raw_exp, false,
                    )
                } else {
                    raw_exp
                }
            });

            // Extract user key from the element if present
            let mut user_key = None;
            let taken_node = match taken_node {
                TemplateChildNode::Element(mut el) => {
                    user_key = extract_key_prop(&mut el);
                    TemplateChildNode::Element(el)
                }
                other => other,
            };

            // Process user_key expression for identifier prefixing
            if let Some(PropNode::Directive(ref mut dir)) = user_key {
                if ctx.options.prefix_identifiers || ctx.options.is_ts {
                    if let Some(ref exp) = dir.exp {
                        let processed = crate::transforms::transform_expression::process_expression(
                            ctx, exp, false,
                        );
                        dir.exp = Some(processed);
                    }
                }
            }

            // Check for key collision with existing branches (vuejs/core #13881)
            let has_key_collision = if let Some(ref new_key) = user_key {
                let new_key_str = extract_key_value_str(new_key);
                if let Some(parent) = &ctx.parent {
                    let children = parent.children_mut();
                    if let TemplateChildNode::If(if_node) = &children[if_idx] {
                        if_node.branches.iter().any(|existing_branch| {
                            if let Some(ref existing_key) = existing_branch.user_key {
                                let existing_key_str = extract_key_value_str(existing_key);
                                matches!((&new_key_str, &existing_key_str), (Some(nk), Some(ek)) if nk == ek)
                            } else {
                                false
                            }
                        })
                    } else {
                        false
                    }
                } else {
                    false
                }
            } else {
                false
            };

            if has_key_collision {
                ctx.on_error(ErrorCode::VIfSameKey, None);
            }

            // Create new branch
            let mut branch_children = Vec::new_in(allocator);
            branch_children.push(taken_node);

            let branch = IfBranchNode {
                condition,
                children: branch_children,
                user_key,
                is_template_if,
                loc: element_loc,
            };

            // Add branch to if node and traverse its children
            // Save context state before traversing (traverse_children modifies parent)
            let saved_parent = ctx.parent;
            let saved_grandparent = ctx.grandparent;
            let saved_child_index = ctx.child_index;

            if let Some(parent) = &ctx.parent {
                let children = parent.children_mut();
                if let TemplateChildNode::If(if_node) = &mut children[if_idx] {
                    if_node.branches.push(branch);
                    // Traverse the newly added branch to process components in it
                    let branch_idx = if_node.branches.len() - 1;
                    let branch_ptr = &mut if_node.branches[branch_idx] as *mut IfBranchNode<'a>;
                    traverse_children(ctx, ParentNode::IfBranch(branch_ptr));
                }
            }

            // Restore context state before removing node
            ctx.parent = saved_parent;
            ctx.grandparent = saved_grandparent;
            ctx.child_index = saved_child_index;

            // Remove the placeholder we left
            ctx.remove_node();
        } else {
            ctx.on_error(ErrorCode::VElseNoAdjacentIf, None);
        }

        None
    }
}

/// Transform v-for directive
pub fn transform_v_for<'a>(
    ctx: &mut TransformContext<'a>,
    exp: Option<&SimpleExpressionContent>,
) -> Option<std::vec::Vec<ExitFn<'a>>> {
    let allocator = ctx.allocator;

    let Some(exp) = exp else {
        ctx.on_error(ErrorCode::VForNoExpression, None);
        return None;
    };

    // Take the current element from parent
    let taken = ctx.take_current_node();
    let taken_node = taken?;

    let element_loc = match &taken_node {
        TemplateChildNode::Element(el) => el.loc.clone(),
        _ => return None,
    };

    let parse_result = crate::transforms::parse_for_expression(allocator, &exp.content, &exp.loc);
    let mut source = parse_result.source;
    let value_alias = parse_result.value;
    let key_alias = parse_result.key;
    let index_alias = parse_result.index;

    // Process source expression with binding-aware identifier prefixing
    // This ensures imports and refs are correctly handled (e.g., _unref(PRESETS) instead of _ctx.PRESETS)
    if ctx.options.prefix_identifiers || ctx.options.is_ts {
        use crate::transforms::process_expression;
        // Process the source expression through the binding-aware transform
        let processed = process_expression(ctx, &source, false);
        source = processed;
    }

    // Create ForNode children with taken element
    let mut for_children = Vec::new_in(allocator);
    for_children.push(taken_node);

    // Create parse result (clone expressions for parse_result)
    let parse_result = ForParseResult {
        source: clone_expression(allocator, &source),
        value: value_alias.as_ref().map(|e| clone_expression(allocator, e)),
        key: key_alias.as_ref().map(|e| clone_expression(allocator, e)),
        index: index_alias.as_ref().map(|e| clone_expression(allocator, e)),
        finalized: false,
    };

    let for_node = ForNode {
        source,
        value_alias,
        key_alias,
        object_index_alias: index_alias,
        parse_result,
        children: for_children,
        codegen_node: None,
        loc: element_loc,
    };

    // Replace placeholder with ForNode
    ctx.replace_node(TemplateChildNode::For(Box::new_in(for_node, allocator)));

    // Add helpers
    ctx.helper(RuntimeHelper::RenderList);
    ctx.helper(RuntimeHelper::OpenBlock);
    ctx.helper(RuntimeHelper::CreateBlock);
    ctx.helper(RuntimeHelper::CreateElementBlock);
    ctx.helper(RuntimeHelper::Fragment);

    None
}

/// Extract key value string from a PropNode for comparison
fn extract_key_value_str(prop: &PropNode<'_>) -> Option<String> {
    match prop {
        PropNode::Attribute(attr) => attr.value.as_ref().map(|v| v.content.clone()),
        PropNode::Directive(dir) => dir.exp.as_ref().map(|exp| match exp {
            ExpressionNode::Simple(s) => s.content.clone(),
            ExpressionNode::Compound(c) => c.loc.source.clone(),
        }),
    }
}