verter_core 0.0.1-alpha.1

Vue 3 SFC compiler - transforms Vue Single File Components to render functions with TypeScript support
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
//! Vue v-slot expression parsing.
//!
//! Parses Vue v-slot expressions which use function parameter syntax.
//! Examples: `{ data }`, `{ item, index = 0 }`, `{ rowData: role }: { rowData: ProjectRole }`
//!
//! The slot content is wrapped as arrow function parameters and parsed:
//! `{ foo, bar }` → `({ foo, bar })=>{}`

use oxc_allocator::Allocator;
use oxc_ast::ast::{Expression, FormalParameters};
use oxc_diagnostics::OxcDiagnostic;
use oxc_parser::Parser;
use oxc_span::SourceType;
use rustc_hash::FxHashSet;

use super::span::subtract_formal_parameters_spans;
use crate::common::Span;
use crate::utils::oxc::bindings::{
    collect_expression_reference_spans, collect_pattern_local_spans,
    collect_pattern_reference_spans, collect_type_reference_spans,
};

/// Result of parsing a v-slot expression.
#[derive(Debug)]
pub struct VSlotParseResult<'a> {
    /// The byte offset added by wrapping (1 for "(").
    /// Subtract this from AST spans to get original source offsets.
    pub offset: u32,

    /// The parsed formal parameters from the slot expression.
    /// Contains the parameter patterns, type annotations, and default values.
    pub params: Option<FormalParameters<'a>>,

    /// Parse errors, if any.
    pub errors: Option<Vec<OxcDiagnostic>>,
}

impl<'a> VSlotParseResult<'a> {
    /// Returns true if parsing was successful (no errors and params are present).
    pub fn is_ok(&self) -> bool {
        self.errors.is_none() && self.params.is_some()
    }
}

/// Combined result of parsing a v-slot expression with extracted bindings.
///
/// This combines the parse result (AST) with the extracted bindings (locals/references)
/// in a single struct for convenience.
///
/// Bindings are stored as spans to avoid self-referential struct issues and save memory.
/// Use `span.slice(source)` to get the string value when needed.
#[derive(Debug)]
pub struct VSlotWithBindings<'a> {
    /// The parsed v-slot expression result containing the AST.
    pub result: VSlotParseResult<'a>,

    /// Spans of local bindings declared by the slot parameters.
    /// For `{ item, index }`, this would contain spans for "item" and "index".
    /// Use `span.slice(source)` to get the string value.
    pub locals: Vec<Span>,

    /// Spans of external references used in the slot expression (type annotations, defaults).
    /// For `{ data }: { data: MyType }`, this would contain a span for "MyType".
    /// Use `span.slice(source)` to get the string value.
    pub references: Vec<Span>,
}

impl<'a> VSlotWithBindings<'a> {
    /// Returns the parsed formal parameters from the slot expression.
    pub fn params(&self) -> Option<&FormalParameters<'a>> {
        self.result.params.as_ref()
    }

    /// Returns true if there are any parse errors.
    pub fn has_errors(&self) -> bool {
        self.result.errors.is_some()
    }

    /// Returns true if parsing was successful.
    pub fn is_ok(&self) -> bool {
        self.result.is_ok()
    }

    /// Returns the offset added by wrapping.
    pub fn offset(&self) -> u32 {
        self.result.offset
    }
}

/// Extract binding spans from FormalParameters.
///
/// This is an internal function used by `parse_vslot_with_bindings`.
/// Returns spans instead of string references to avoid self-referential struct issues.
fn extract_slot_bindings_internal(
    params: &FormalParameters<'_>,
    source: &str,
) -> (Vec<Span>, Vec<Span>) {
    let mut locals = Vec::new();
    let mut references_set = FxHashSet::default();

    // Extract local spans from parameters
    for param in &params.items {
        collect_pattern_local_spans(&param.pattern, &mut locals);
    }
    if let Some(rest) = &params.rest {
        collect_pattern_local_spans(&rest.rest.argument, &mut locals);
    }

    // Build ignored set from local names (need the actual strings to filter references)
    let ignored: FxHashSet<&[u8]> = locals
        .iter()
        .map(|span| span.slice(source).as_bytes())
        .collect();

    // Extract reference spans from type annotations and default values
    for param in &params.items {
        // Default value (initializer)
        if let Some(init) = &param.initializer {
            collect_expression_reference_spans(init, &ignored, &mut references_set);
        }
        // Type annotation on the parameter (on FormalParameter, not BindingPattern)
        if let Some(annotation) = &param.type_annotation {
            collect_type_reference_spans(&annotation.type_annotation, &mut references_set);
        }
        // References in default values within the pattern
        collect_pattern_reference_spans(&param.pattern, &ignored, &mut references_set);
    }
    if let Some(rest) = &params.rest {
        if let Some(annotation) = &rest.type_annotation {
            collect_type_reference_spans(&annotation.type_annotation, &mut references_set);
        }
    }

    let references: Vec<Span> = references_set.into_iter().collect();
    (locals, references)
}

/// Parse a Vue v-slot expression.
///
/// # Arguments
/// * `allocator` - The OXC allocator for AST memory
/// * `source` - The v-slot expression content (e.g., "{ data }", "item, index")
/// * `source_type` - The source type (e.g., TSX, JavaScript)
///
/// # Returns
/// A `VSlotParseResult` containing the parsed FormalParameters and offset info.
///
/// # How it works
/// 1. Wraps the content as arrow function parameters: `({content})=>{}`
/// 2. Parses as an expression (ArrowFunctionExpression)
/// 3. Extracts the FormalParameters
///
/// # Offset Adjustment
/// The wrapper adds 1 byte (`(`) before the content. Subtract `result.offset`
/// from any AST spans to get the original source position.
///
/// # Example
/// ```ignore
/// let allocator = Allocator::default();
/// let result = parse_vslot(&allocator, "{ data, index = 0 }", SourceType::tsx());
/// assert!(result.is_ok());
/// // result.params contains the parsed parameters
/// // Each param span needs result.offset subtracted for original position
/// ```
pub fn parse_vslot<'a>(
    allocator: &'a Allocator,
    source: &str,
    source_type: SourceType,
) -> VSlotParseResult<'a> {
    // Handle empty/whitespace-only input
    if source.trim().is_empty() {
        return VSlotParseResult {
            params: None,
            offset: 0,
            errors: None,
        };
    }

    // Wrap as arrow function parameters: `({content})=>{}`
    // The opening `(` adds 1 byte offset
    const WRAPPER_OFFSET: u32 = 1;
    let wrapped_string = format!("({})=>{{}}", source);
    // Allocate the wrapped string in the allocator so it lives as long as the allocator
    let wrapped = allocator.alloc_str(&wrapped_string);

    // Parse as expression
    let parser = Parser::new(allocator, wrapped, source_type);
    let result = parser.parse_expression();

    match result {
        Ok(expr) => {
            // Extract FormalParameters from ArrowFunctionExpression
            if let Expression::ArrowFunctionExpression(arrow) = expr {
                let mut params = arrow.unbox().params.unbox();
                // Adjust spans to reflect original source positions (subtract wrapper offset)
                subtract_formal_parameters_spans(&mut params, WRAPPER_OFFSET);
                VSlotParseResult {
                    params: Some(params),
                    offset: WRAPPER_OFFSET,
                    errors: None,
                }
            } else {
                VSlotParseResult {
                    params: None,
                    offset: WRAPPER_OFFSET,
                    errors: Some(vec![OxcDiagnostic::error(
                        "Failed to parse slot expression as arrow function parameters",
                    )]),
                }
            }
        }
        Err(errors) => VSlotParseResult {
            params: None,
            offset: WRAPPER_OFFSET,
            errors: Some(errors),
        },
    }
}

/// Parse a Vue v-slot expression and extract bindings in one pass.
///
/// This is the preferred function when you need both the parsed AST and the
/// extracted bindings, as it avoids having to call separate functions.
///
/// # Arguments
/// * `allocator` - The OXC allocator for AST memory
/// * `source` - The v-slot expression content (e.g., "{ data }", "item, index")
/// * `source_type` - The source type (e.g., TSX, JavaScript)
///
/// # Returns
/// A `VSlotWithBindings` containing:
/// - `result`: The parsed VSlotParseResult with AST
/// - `locals`: Declared parameter bindings (e.g., `["item", "index"]`)
/// - `references`: External identifiers referenced (e.g., `["MyType"]` from type annotations)
///
/// # Example
/// ```ignore
/// let allocator = Allocator::default();
/// let result = parse_vslot_with_bindings(&allocator, "{ data }: { data: MyType }", SourceType::tsx());
/// assert!(result.is_ok());
/// assert_eq!(result.locals, vec!["data"]);
/// assert_eq!(result.references, vec!["MyType"]);
/// ```
pub fn parse_vslot_with_bindings<'a>(
    allocator: &'a Allocator,
    source: &str,
    source_type: SourceType,
) -> VSlotWithBindings<'a> {
    let result = parse_vslot(allocator, source, source_type);

    // Extract bindings if parsing succeeded
    let (locals, references) = if result.errors.is_some() {
        (Vec::new(), Vec::new())
    } else if let Some(params) = &result.params {
        extract_slot_bindings_internal(params, source)
    } else {
        (Vec::new(), Vec::new())
    };

    VSlotWithBindings {
        result,
        locals,
        references,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxc_ast::ast::BindingPattern;

    fn parse(source: &str) -> VSlotParseResult<'static> {
        let allocator = Box::leak(Box::new(Allocator::default()));
        parse_vslot(allocator, source, SourceType::tsx())
    }

    #[test]
    fn test_simple_identifier() {
        let result = parse("data");
        assert!(result.is_ok());
        assert_eq!(result.offset, 1);

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        // Check the parameter is an identifier with adjusted spans
        if let BindingPattern::BindingIdentifier(id) = &params.items[0].pattern {
            assert_eq!(id.name.as_str(), "data");
            // Spans are now adjusted to original positions (0-4 for "data")
            assert_eq!(id.span.start, 0);
            assert_eq!(id.span.end, 4);
        } else {
            panic!("Expected BindingIdentifier");
        }
    }

    #[test]
    fn test_object_destructuring() {
        let result = parse("{ item, index }");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        // Check the parameter is an object pattern
        if let BindingPattern::ObjectPattern(obj) = &params.items[0].pattern {
            assert_eq!(obj.properties.len(), 2);
        } else {
            panic!("Expected ObjectPattern");
        }
    }

    #[test]
    fn test_renamed_destructuring() {
        let result = parse("{ rowData: role }");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        if let BindingPattern::ObjectPattern(obj) = &params.items[0].pattern {
            assert_eq!(obj.properties.len(), 1);
            // The binding should be 'role'
            if let BindingPattern::BindingIdentifier(id) = &obj.properties[0].value {
                assert_eq!(id.name.as_str(), "role");
            } else {
                panic!("Expected BindingIdentifier for renamed property");
            }
        } else {
            panic!("Expected ObjectPattern");
        }
    }

    #[test]
    fn test_with_default_value() {
        let result = parse("{ item = defaultItem }");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        if let BindingPattern::ObjectPattern(obj) = &params.items[0].pattern {
            assert_eq!(obj.properties.len(), 1);
            // The property should have a default value (AssignmentPattern)
            if let BindingPattern::AssignmentPattern(_) = &obj.properties[0].value {
                // OK - has default
            } else {
                panic!("Expected AssignmentPattern for default value");
            }
        } else {
            panic!("Expected ObjectPattern");
        }
    }

    #[test]
    fn test_with_type_annotation() {
        let result = parse("{ data }: { data: MyType }");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        // Check type annotation is present
        assert!(params.items[0].type_annotation.is_some());
    }

    #[test]
    fn test_multiple_params() {
        let result = parse("item, index, extra");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 3);
    }

    #[test]
    fn test_rest_parameter() {
        let result = parse("first, ...rest");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1); // 'first' is a regular param
        assert!(params.rest.is_some()); // '...rest' is the rest element
    }

    #[test]
    fn test_nested_destructuring() {
        let result = parse("{ user: { name, id } }");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);
    }

    #[test]
    fn test_array_destructuring() {
        let result = parse("[first, second]");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        if let BindingPattern::ArrayPattern(_) = &params.items[0].pattern {
            // OK
        } else {
            panic!("Expected ArrayPattern");
        }
    }

    #[test]
    fn test_empty_input() {
        let result = parse("");
        // Empty input returns None for params but no errors
        assert!(result.params.is_none());
        assert!(result.errors.is_none());
    }

    #[test]
    fn test_whitespace_only() {
        let result = parse("   ");
        assert!(result.params.is_none());
        assert!(result.errors.is_none());
    }

    #[test]
    fn test_invalid_syntax() {
        let result = parse("{ invalid: }");
        assert!(!result.is_ok());
        assert!(!result.errors.is_none());
    }

    #[test]
    fn test_complex_type_annotation() {
        let result = parse("data: Array<Item>");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert!(params.items[0].type_annotation.is_some());
    }

    #[test]
    fn test_default_with_function_call() {
        let result = parse("data = getData()");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        // Parameter with default value at top level
        assert!(params.items[0].initializer.is_some());
    }

    #[test]
    fn test_span_offset() {
        let result = parse("data");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        if let BindingPattern::BindingIdentifier(id) = &params.items[0].pattern {
            // Spans are now pre-adjusted to original positions
            // "data" should be 0-4 in the original source
            assert_eq!(id.span.start, 0);
            assert_eq!(id.span.end, 4);
        }
    }

    #[test]
    fn test_complex_slot_expression() {
        // Real-world example from Vue
        let result = parse("{ rowData: role }: { rowData: ProjectRole }");
        assert!(result.is_ok());

        let params = result.params.unwrap();
        assert_eq!(params.items.len(), 1);

        // Check destructuring
        if let BindingPattern::ObjectPattern(obj) = &params.items[0].pattern {
            if let BindingPattern::BindingIdentifier(id) = &obj.properties[0].value {
                assert_eq!(id.name.as_str(), "role");
            }
        }

        // Check type annotation
        assert!(params.items[0].type_annotation.is_some());
    }
}