vize_atelier_core 0.237.0

Atelier Core - The core workshop for Vize Vue template parsing, transform lanes, and code generation
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
//! TransformContext implementation.

use vize_carton::{Box, Bump, CompactString, String};
use vize_croquis::reactivity::ReactiveKind;
use vize_croquis::{BindingType, Croquis, ScopeBinding, ScopeKind, VForScopeData, VSlotScopeData};

use crate::errors::{CompilerError, ErrorCode};
use crate::options::TransformOptions;
use crate::{
    CacheExpression, CommentNode, ConstantType, ExpressionNode, JsChildNode, RuntimeHelper,
    SimpleExpressionNode, SourceLocation, TemplateChildNode,
};

use super::TransformContext;

impl<'a> TransformContext<'a> {
    /// Create a new transform context
    pub fn new(allocator: &'a Bump, source: String, options: TransformOptions) -> Self {
        Self::new_with_template_syntax_quirks(allocator, source, options, false)
    }

    /// Create a new transform context with template syntax quirk compatibility.
    pub fn new_with_template_syntax_quirks(
        allocator: &'a Bump,
        source: String,
        options: TransformOptions,
        template_syntax_quirks: bool,
    ) -> Self {
        let ssr = options.ssr;
        Self {
            allocator,
            source,
            options,
            root: None,
            parent: None,
            grandparent: None,
            current_node: None,
            child_index: 0,
            helpers: crate::runtime_helpers::RuntimeHelpers::default(),
            components: std::vec::Vec::new(),
            directives: std::vec::Vec::new(),
            #[cfg(feature = "legacy")]
            filters: std::vec::Vec::new(),
            hoists: vize_carton::Vec::new_in(allocator),
            cached: vize_carton::Vec::new_in(allocator),
            temps: 0,
            scope_chain: vize_croquis::ScopeChain::new(),
            scoped_slots: 0,
            in_v_once: false,
            in_ssr: ssr,
            errors: std::vec::Vec::new(),
            template_syntax_quirks,
            node_removed: false,
            analysis: None,
            hoisted_scope_id: None,
        }
    }

    /// Create a new transform context with Vue parser quirk compatibility.
    #[deprecated(note = "use new_with_template_syntax_quirks instead")]
    pub fn new_with_vue_parser_quirks(
        allocator: &'a Bump,
        source: String,
        options: TransformOptions,
        vue_parser_quirks: bool,
    ) -> Self {
        Self::new_with_template_syntax_quirks(allocator, source, options, vue_parser_quirks)
    }

    /// Create a new transform context with semantic analysis data
    pub fn with_analysis(
        allocator: &'a Bump,
        source: String,
        options: TransformOptions,
        analysis: &'a Croquis,
    ) -> Self {
        Self::with_analysis_and_template_syntax_quirks(allocator, source, options, analysis, false)
    }

    /// Create a new transform context with semantic analysis data and template syntax quirks.
    pub fn with_analysis_and_template_syntax_quirks(
        allocator: &'a Bump,
        source: String,
        options: TransformOptions,
        analysis: &'a Croquis,
        template_syntax_quirks: bool,
    ) -> Self {
        let mut ctx = Self::new_with_template_syntax_quirks(
            allocator,
            source,
            options,
            template_syntax_quirks,
        );
        ctx.analysis = Some(analysis);
        ctx
    }

    /// Create a new transform context with semantic analysis data and Vue parser quirks.
    #[deprecated(note = "use with_analysis_and_template_syntax_quirks instead")]
    pub fn with_analysis_and_vue_parser_quirks(
        allocator: &'a Bump,
        source: String,
        options: TransformOptions,
        analysis: &'a Croquis,
        vue_parser_quirks: bool,
    ) -> Self {
        Self::with_analysis_and_template_syntax_quirks(
            allocator,
            source,
            options,
            analysis,
            vue_parser_quirks,
        )
    }

    /// Set the analysis summary
    pub fn set_analysis(&mut self, analysis: &'a Croquis) {
        self.analysis = Some(analysis);
    }

    /// Get the analysis summary if available
    #[inline]
    pub fn analysis(&self) -> Option<&Croquis> {
        self.analysis
    }

    /// Check if analysis data is available
    #[inline]
    pub fn has_analysis(&self) -> bool {
        self.analysis.is_some()
    }

    /// Whether template syntax quirk compatibility is enabled.
    #[inline]
    pub fn template_syntax_quirks(&self) -> bool {
        self.template_syntax_quirks
    }

    /// Whether Vue parser quirk compatibility is enabled.
    #[inline]
    #[deprecated(note = "use template_syntax_quirks instead")]
    pub fn vue_parser_quirks(&self) -> bool {
        self.template_syntax_quirks()
    }

    /// Check if a variable is defined (from analysis or binding metadata)
    ///
    /// This checks both the scope chain (template-local) and script bindings.
    pub fn is_variable_defined(&self, name: &str) -> bool {
        // First check scope chain (v-for, v-slot variables)
        if self.scope_chain.is_defined(name) {
            return true;
        }

        // Check analysis summary if available
        if let Some(analysis) = &self.analysis {
            return analysis.is_defined(name);
        }

        // Fall back to binding metadata from options
        if let Some(metadata) = &self.options.binding_metadata {
            return metadata.bindings.contains_key(name);
        }

        false
    }

    /// Get the binding type for a name
    pub fn get_binding_type(&self, name: &str) -> Option<BindingType> {
        // First check scope chain
        if let Some((_, binding)) = self.scope_chain.lookup(name) {
            return Some(binding.binding_type);
        }

        // Check analysis summary
        if let Some(analysis) = &self.analysis {
            return analysis.get_binding_type(name);
        }

        // Fall back to binding metadata
        if let Some(metadata) = &self.options.binding_metadata {
            return metadata.bindings.get(name).copied();
        }

        None
    }

    /// Check if a name needs $setup prefix (for script setup bindings)
    ///
    /// Returns true if the name is a script binding and should use $setup prefix.
    pub fn needs_setup_prefix(&self, name: &str) -> bool {
        // Skip if in scope (v-for, v-slot)
        if self.scope_chain.is_defined(name) {
            return false;
        }

        // Check binding type
        if let Some(binding_type) = self.get_binding_type(name) {
            matches!(
                binding_type,
                BindingType::SetupConst
                    | BindingType::SetupLet
                    | BindingType::SetupRef
                    | BindingType::SetupMaybeRef
                    | BindingType::SetupReactiveConst
            )
        } else {
            false
        }
    }

    /// Check if a binding is a ref that needs .value in script
    pub fn is_ref(&self, name: &str) -> bool {
        if let Some(analysis) = &self.analysis {
            analysis.bindings.is_ref(name)
        } else if let Some(binding_type) = self.get_binding_type(name) {
            matches!(
                binding_type,
                BindingType::SetupRef | BindingType::SetupMaybeRef
            )
        } else {
            false
        }
    }

    /// Check if a binding is from props
    pub fn is_prop(&self, name: &str) -> bool {
        if let Some(analysis) = &self.analysis {
            analysis.bindings.is_prop(name)
        } else {
            matches!(
                self.get_binding_type(name),
                Some(BindingType::Props | BindingType::PropsAliased)
            )
        }
    }

    /// Get the ReactiveKind for a name (from Croquis ReactivityTracker)
    pub fn get_reactive_kind(&self, name: &str) -> Option<ReactiveKind> {
        self.analysis?.reactivity.lookup(name).map(|s| s.kind)
    }

    /// Check if a binding is read-only (Computed, Readonly, ShallowReadonly)
    pub fn is_readonly_binding(&self, name: &str) -> bool {
        self.get_reactive_kind(name).is_some_and(|k| {
            matches!(
                k,
                ReactiveKind::Computed | ReactiveKind::Readonly | ReactiveKind::ShallowReadonly
            )
        })
    }

    /// Check if a component is registered (from analysis or binding metadata)
    pub fn is_component_registered(&self, name: &str) -> bool {
        if let Some(analysis) = &self.analysis
            && analysis.is_component_registered(name)
        {
            return true;
        }

        if let Some(metadata) = &self.options.binding_metadata
            && metadata.bindings.contains_key(name)
        {
            return true;
        }

        false
    }

    /// Add a helper
    pub fn helper(&mut self, helper: RuntimeHelper) {
        self.helpers.add(helper);
    }

    /// Remove a helper
    pub fn remove_helper(&mut self, helper: RuntimeHelper) {
        self.helpers.remove(helper);
    }

    /// Check if helper exists
    pub fn has_helper(&self, helper: RuntimeHelper) -> bool {
        self.helpers.contains(helper)
    }

    /// Add a component (maintains insertion order for code generation)
    pub fn add_component(&mut self, component: impl Into<String>) {
        let component = component.into();
        if !self.components.contains(&component) {
            self.components.push(component);
        }
    }

    /// Add a directive (maintains insertion order for code generation)
    pub fn add_directive(&mut self, directive: impl Into<String>) {
        let directive = directive.into();
        if !self.directives.contains(&directive) {
            self.directives.push(directive);
        }
    }

    /// Register a Vue 2 pipe filter (maintains first-seen order for codegen).
    ///
    /// Legacy-only; only ever called from the dialect-gated filter rewrite.
    #[cfg(feature = "legacy")]
    pub(crate) fn add_filter(&mut self, filter: impl Into<String>) {
        let filter = filter.into();
        if !self.filters.contains(&filter) {
            self.filters.push(filter);
        }
    }

    /// Whether the resolved dialect supports Vue 2 pipe filters
    /// (`{{ msg | capitalize }}`). Resolved from
    /// [`vize_armature::legacy::LegacyDialectCapabilities`] for the dialect on
    /// [`TransformOptions::dialect`](crate::options::TransformOptions::dialect).
    ///
    /// Always `false` for the default Vue 3 dialect, so the filter rewrite is
    /// never entered there. Legacy-only.
    #[cfg(feature = "legacy")]
    #[inline]
    pub(crate) fn supports_filters(&self) -> bool {
        vize_armature::legacy::LegacyDialectCapabilities::for_dialect(self.options.dialect)
            .supports_filters
    }

    /// Whether the resolved dialect is the Vue 2 / 2.7 template line, which
    /// carried the removed v-on event-modifier sugar (`@click.native`, numeric
    /// keycodes such as `@keyup.13`). Resolved from
    /// [`vize_armature::legacy::LegacyVueVersion::from_dialect`] for the dialect
    /// on [`TransformOptions::dialect`](crate::options::TransformOptions::dialect).
    ///
    /// Always `false` for the default Vue 3 dialect (and every other legacy
    /// line), so the Vue 2 event-modifier desugaring is never entered there and
    /// the directive's modifiers stay byte-identical to today's output.
    /// Legacy-only.
    #[cfg(feature = "legacy")]
    #[inline]
    pub(crate) fn supports_v2_event_sugar(&self) -> bool {
        matches!(
            vize_armature::legacy::LegacyVueVersion::from_dialect(self.options.dialect),
            Some(vize_armature::legacy::LegacyVueVersion::V2)
        )
    }

    /// Add an identifier to current scope
    pub fn add_identifier(&mut self, id: impl Into<CompactString>) {
        self.scope_chain
            .add_binding(id.into(), ScopeBinding::new(BindingType::SetupConst, 0));
    }

    /// Enter a new scope
    pub fn enter_scope(&mut self, kind: ScopeKind) {
        self.scope_chain.enter_scope(kind);
    }

    /// Exit the current scope
    pub fn exit_scope(&mut self) {
        self.scope_chain.exit_scope();
    }

    /// Enter a v-for scope with the given aliases
    pub fn enter_v_for_scope(
        &mut self,
        value_alias: Option<&str>,
        key_alias: Option<&str>,
        index_alias: Option<&str>,
        source: &str,
    ) {
        self.scope_chain.enter_v_for_scope(
            VForScopeData {
                value_alias: CompactString::new(value_alias.unwrap_or("")),
                value_bindings: value_alias
                    .map(|alias| vize_carton::smallvec![CompactString::new(alias)])
                    .unwrap_or_default(),
                key_alias: key_alias.map(CompactString::new),
                index_alias: index_alias.map(CompactString::new),
                source: CompactString::new(source),
                key_expression: None,
            },
            0,
            0,
        );
    }

    /// Enter a v-slot scope with the given slot params
    pub fn enter_v_slot_scope(
        &mut self,
        name: &str,
        props_pattern: Option<&str>,
        prop_names: &[String],
        start: u32,
        end: u32,
    ) {
        self.scope_chain.enter_v_slot_scope(
            VSlotScopeData {
                name: CompactString::new(name),
                props_pattern: props_pattern.map(CompactString::new),
                prop_names: prop_names
                    .iter()
                    .map(|name| CompactString::new(name.as_str()))
                    .collect(),
                // The runtime transform does not type slot props; only the
                // editor's virtual-TS generation consumes the owning component.
                component: None,
            },
            start,
            end,
        );
    }

    /// Check if identifier is in scope
    pub fn is_in_scope(&self, id: &str) -> bool {
        self.scope_chain.is_defined(id)
    }

    /// Hoist an expression
    pub fn hoist(&mut self, node: JsChildNode<'a>) -> usize {
        let index = self.hoists.len();
        self.hoists.push(Some(node));
        index
    }

    /// Cache an expression
    pub fn cache(&mut self, exp: CacheExpression<'a>) -> usize {
        let index = self.cached.len();
        let boxed = Box::new_in(exp, self.allocator);
        self.cached.push(Some(boxed));
        index
    }

    /// Report an error
    pub fn on_error(&mut self, code: ErrorCode, loc: Option<SourceLocation>) {
        self.errors.push(CompilerError::new(code, loc));
    }

    /// Report an error with a custom message (e.g. parser details appended
    /// to the code's default message, mirroring `@vue/compiler-core`).
    pub fn on_error_with_message(
        &mut self,
        code: ErrorCode,
        message: impl Into<CompactString>,
        loc: Option<SourceLocation>,
    ) {
        self.errors
            .push(CompilerError::with_message(code, message, loc));
    }

    /// Replace current node with a new node
    pub fn replace_node(&mut self, new_node: TemplateChildNode<'a>) {
        if let Some(parent) = &self.parent {
            let children = parent.children_mut();
            if self.child_index < children.len() {
                children[self.child_index] = new_node;
                self.current_node = Some(&mut children[self.child_index] as *mut _);
            }
        }
    }

    /// Take the current node, replacing it with a placeholder
    pub fn take_current_node(&mut self) -> Option<TemplateChildNode<'a>> {
        if let Some(parent) = &self.parent {
            let children = parent.children_mut();
            if self.child_index < children.len() {
                let placeholder = TemplateChildNode::Comment(Box::new_in(
                    CommentNode::new("", SourceLocation::STUB),
                    self.allocator,
                ));
                let taken = std::mem::replace(&mut children[self.child_index], placeholder);
                return Some(taken);
            }
        }
        None
    }

    /// Remove current node
    pub fn remove_node(&mut self) {
        if let Some(parent) = &self.parent {
            let children = parent.children_mut();
            if self.child_index < children.len() {
                children.remove(self.child_index);
                self.current_node = None;
                self.node_removed = true;
            }
        }
    }

    /// Remove a specific node
    pub fn remove_node_at(&mut self, index: usize) {
        if let Some(parent) = &self.parent {
            let children = parent.children_mut();
            if index < children.len() {
                children.remove(index);
                if index < self.child_index {
                    self.child_index -= 1;
                }
                self.node_removed = true;
            }
        }
    }

    /// Check if node was removed
    pub fn was_node_removed(&self) -> bool {
        self.node_removed
    }

    /// Reset node removed flag
    pub fn reset_node_removed(&mut self) {
        self.node_removed = false;
    }
}

/// Clone an expression into the arena
pub(super) fn clone_expression<'a>(
    allocator: &'a Bump,
    exp: &ExpressionNode<'a>,
) -> ExpressionNode<'a> {
    match exp {
        ExpressionNode::Simple(s) => ExpressionNode::Simple(Box::new_in(
            SimpleExpressionNode {
                content: s.content.clone(),
                is_static: s.is_static,
                const_type: s.const_type,
                loc: s.loc.clone(),
                js_ast: None,
                hoisted: None,
                identifiers: None,
                is_handler_key: s.is_handler_key,
                is_ref_transformed: s.is_ref_transformed,
            },
            allocator,
        )),
        ExpressionNode::Compound(c) => {
            // For compound expressions, we recreate from source
            ExpressionNode::Simple(Box::new_in(
                SimpleExpressionNode {
                    content: c.loc.source.clone(),
                    is_static: false,
                    const_type: ConstantType::NotConstant,
                    loc: c.loc.clone(),
                    js_ast: None,
                    hoisted: None,
                    identifiers: None,
                    is_handler_key: c.is_handler_key,
                    is_ref_transformed: false,
                },
                allocator,
            ))
        }
    }
}