fervid 0.2.0

Vue SFC compiler written in Rust
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
use fervid_core::{
    AttributeOrBinding, FervidAtom, StrOrExpr, VBindDirective, VCustomDirective, VForDirective,
    VModelDirective, VOnDirective, VSlotDirective, VueDirectives,
};
use nom::{
    branch::alt,
    bytes::complete::{tag, take_till},
    character::complete::char,
    combinator::fail,
    error::{ErrorKind, ParseError},
    multi::many0,
    sequence::{delimited, preceded},
    Err, IResult,
};
use swc_core::common::DUMMY_SP;

use crate::parser_old::{
    ecma::{parse_js, parse_js_pat},
    html_utils::html_name,
};

pub fn parse_attributes(
    input: &str,
) -> IResult<&str, (Vec<AttributeOrBinding>, Option<Box<VueDirectives>>)> {
    let mut directives = None;
    let mut attrs = Vec::new();
    let mut input = input;

    loop {
        let len = input.len();

        // Skip whitespace
        input = input.trim_start();

        // Try parsing a directive first
        let directive_result = parse_directive(input, &mut attrs, &mut directives);
        match directive_result {
            // Err(Err::Error(_)) => return Ok((input, (attrs, directives))),
            // Err(e) => return Err(e),
            Ok((new_input, _)) => {
                // infinite loop check: the parser must always consume
                if new_input.len() == len {
                    return Err(Err::Error(ParseError::from_error_kind(
                        input,
                        ErrorKind::Many0,
                    )));
                }

                input = new_input;
            }

            Err(_) => {
                // Try parsing a regular attribute
                let attribute_result = parse_vanilla_attr(input, &mut attrs);

                match attribute_result {
                    Err(Err::Error(_)) => return Ok((input, (attrs, directives))),
                    Err(e) => return Err(e),
                    Ok((new_input, _)) => {
                        // infinite loop check: the parser must always consume
                        if new_input.len() == len {
                            return Err(Err::Error(ParseError::from_error_kind(
                                input,
                                ErrorKind::Many0,
                            )));
                        }

                        input = new_input;
                    }
                }
            }
        }
    }
}

fn parse_vanilla_attr<'i>(
    input: &'i str,
    out: &mut Vec<AttributeOrBinding>,
) -> IResult<&'i str, ()> {
    let (input, attr_name) = html_name(input)?;

    /* Support omitting a `=` char */
    let eq: Result<(&str, char), nom::Err<nom::error::Error<_>>> = char('=')(input);
    match eq {
        // consider omitted attribute as attribute name itself (as current Vue compiler does)
        Err(_) => {
            out.push(AttributeOrBinding::RegularAttribute {
                name: attr_name.into(),
                value: attr_name.into(),
                span: DUMMY_SP
            });
            Ok((input, ()))
        }

        Ok((input, _)) => {
            let (input, attr_value) = parse_attr_value(input)?;

            #[cfg(dbg_print)]
            println!("Dynamic attr: value = {:?}", attr_value);

            out.push(AttributeOrBinding::RegularAttribute {
                name: attr_name.into(),
                value: attr_value.into(),
                span: DUMMY_SP
            });

            Ok((input, ()))
        }
    }
}

fn parse_attr_value(input: &str) -> IResult<&str, &str> {
    delimited(char('"'), take_till(|c| c == '"'), char('"'))(input)
}

/// Parses a directive in form of `v-directive-name:directive-attribute.modifier1.modifier2`
///
/// Allows for shortcuts like `@` (same as `v-on`), `:` (`v-bind`) and `#` (`v-slot`)
fn parse_directive<'i>(
    input: &'i str,
    attributes: &mut Vec<AttributeOrBinding>,
    directives: &mut Option<Box<VueDirectives>>,
) -> IResult<&'i str, ()> {
    let (input, prefix) = alt((tag("v-"), tag("@"), tag("#"), tag(":"), tag(".")))(input)?;

    // https://vuejs.org/api/built-in-directives.html#v-bind
    let mut is_bind_prop = false;
    let mut is_dynamic = false;

    // Determine directive name
    let mut has_argument = false;
    let (input, directive_name) = match prefix {
        "v-" => {
            let (input, name) = html_name(input)?;

            // next char is colon, shift input and set flag
            if let Some(':') = input.chars().next() {
                has_argument = true;
                (&input[1..], name)
            } else {
                (input, name)
            }
        }

        "@" => {
            has_argument = true;
            (input, "on")
        }

        ":" => {
            has_argument = true;
            (input, "bind")
        }

        "." => {
            has_argument = true;
            is_bind_prop = true;
            (input, "bind")
        }

        "#" => {
            has_argument = true;
            (input, "slot")
        }

        _ => {
            return Err(nom::Err::Error(nom::error::Error {
                code: nom::error::ErrorKind::Tag,
                input,
            }))
        }
    };

    // Read argument part if we spotted `:` earlier
    let (input, argument) = if has_argument {
        // Support v-slot:[slotname], v-bind:[attr], etc.
        let (input, arg) = if input.starts_with("[") {
            is_dynamic = true;

            delimited(char('['), html_name, char(']'))(input)?
        } else {
            html_name(input)?
        };

        (input, Some(arg))
    } else {
        (input, None)
    };

    #[cfg(dbg_print)]
    {
        println!();
        println!("Parsed directive {:?}", directive_name);
        println!("Has argument: {}, argument: {:?}", has_argument, argument);
    }

    // Read modifiers
    let (input, modifiers): (&str, Vec<&str>) =
        many0(preceded(char('.'), html_name))(input).unwrap_or((input, vec![]));

    // Value
    let (input, value) = if !input.starts_with('=') {
        (input, None)
    } else {
        let (input, value) = parse_attr_value(&input[1..])?;
        (input, Some(value))
    };

    macro_rules! fail {
        () => {
            // TODO: this fails at a very unexpected location,
            // but maybe it needs to rewind back to the start
            return fail(input);
        };
    }

    /// Unwrapping the value or failing
    macro_rules! expect_value {
        () => {
            if let Some(value) = value {
                value
            } else {
                fail!();
            }
        };
    }

    macro_rules! get_directives {
        () => {
            directives.get_or_insert_with(|| Box::new(VueDirectives::default()))
        };
    }

    macro_rules! push_directive {
        ($key: ident, $value: expr) => {
            let directives = get_directives!();
            directives.$key = Some($value);
        };
    }

    macro_rules! push_directive_js {
        ($key: ident, $value: expr) => {
            // TODO span
            match parse_js($value, 0, 0) {
                Ok(parsed) => {
                    let directives = get_directives!();
                    directives.$key = Some(parsed);
                }
                Result::Err(_) => {}
            }
        };
    }

    let argument = argument.map(|v| FervidAtom::from(v));
    let modifiers: Vec<FervidAtom> = modifiers.into_iter().map(|v| FervidAtom::from(v)).collect();

    // Type the directive
    match directive_name {
        // Directives arranged by estimated usage frequency
        "bind" => {
            // Get flags
            let mut is_camel = false;
            let mut is_prop = is_bind_prop;
            let mut is_attr = false;
            for modifier in modifiers.iter() {
                match modifier.as_ref() {
                    "camel" => is_camel = true,
                    "prop" => is_prop = true,
                    "attr" => is_attr = true,
                    _ => {}
                }
            }

            let value = expect_value!();

            // TODO span
            let Ok(parsed_expr) = parse_js(value, 0, 0) else {
                fail!();
            };

            // TODO don't fail the directive but skip it instead
            let argument = convert_argument(argument, is_dynamic, input)?;

            attributes.push(AttributeOrBinding::VBind(VBindDirective {
                argument,
                value: parsed_expr,
                is_camel,
                is_prop,
                is_attr,
                span: DUMMY_SP
            }));
        }
        "on" => {
            let argument = convert_argument(argument, is_dynamic, input)?;

            attributes.push(AttributeOrBinding::VOn(VOnDirective {
                event: argument,
                handler: value.and_then(|value| {
                    // TODO span
                    let parse_result = parse_js(value, 0, 0);
                    match parse_result {
                        Ok(parsed_expr) => Some(parsed_expr),
                        Err(_) => None,
                    }
                }),
                modifiers,
                span: DUMMY_SP
            }));
        }
        "if" => {
            let value = expect_value!();

            // TODO Span
            match parse_js(value, 0, 0) {
                Ok(condition) => {
                    push_directive!(v_if, condition);
                }
                Result::Err(_) => {}
            }
        }
        "else-if" => {
            let value = expect_value!();

            // TODO Span
            match parse_js(value, 0, 0) {
                Ok(condition) => {
                    push_directive!(v_else_if, condition);
                }
                Result::Err(_) => {}
            }
        }
        "else" => {
            push_directive!(v_else, ());
        }
        "for" => {
            let value = expect_value!();

            let Some((itervar, iterable)) = split_itervar_and_iterable(value) else {
                fail!();
            };

            // TODO Span
            match parse_js(itervar, 0, 0) {
                Ok(itervar) => match parse_js(iterable, 0, 0) {
                    Ok(iterable) => {
                        push_directive!(
                            v_for,
                            VForDirective {
                                iterable,
                                itervar,
                                patch_flags: Default::default(),
                                span: DUMMY_SP
                            }
                        );
                    }
                    Result::Err(_) => {}
                },
                Result::Err(_) => {}
            };
        }
        "model" => {
            let value = expect_value!();
            let argument = convert_argument(argument, is_dynamic, input)?;

            // TODO Span
            match parse_js(value, 0, 0) {
                Ok(model_binding) => {
                    let directives = get_directives!();
                    directives.v_model.push(VModelDirective {
                        argument,
                        value: model_binding,
                        update_handler: None,
                        modifiers,
                        span: DUMMY_SP, // TODO
                    });
                }
                Result::Err(_) => {}
            }
        }
        "slot" => {
            let value = value.and_then(|v| {
                // TODO Span
                match parse_js_pat(v, 0, 0) {
                    Ok(value) => Some(Box::new(value)),
                    Result::Err(_) => None,
                }
            });
            let argument = convert_argument(argument, is_dynamic, input)?;

            push_directive!(
                v_slot,
                VSlotDirective {
                    slot_name: argument,
                    value,
                }
            );
        }
        "show" => {
            let value = expect_value!();
            push_directive_js!(v_show, value);
        }
        "html" => {
            let value = expect_value!();
            push_directive_js!(v_html, value);
        }
        "text" => {
            let value = expect_value!();
            push_directive_js!(v_text, value);
        }
        "once" => {
            push_directive!(v_once, ());
        }
        "pre" => {
            push_directive!(v_pre, ());
        }
        "memo" => {
            let value = expect_value!();
            push_directive_js!(v_memo, value);
        }
        "cloak" => {
            push_directive!(v_cloak, ());
        }

        // Custom
        _ => 'custom: {
            let argument = convert_argument(argument, is_dynamic, input)?;

            // If no value, include as is
            let Some(value) = value else {
                let directives = get_directives!();
                directives.custom.push(VCustomDirective {
                    name: directive_name.into(),
                    argument,
                    modifiers,
                    value: None,
                });
                break 'custom;
            };

            // If there is a value, try parsing it and only include the successfully parsed values
            match parse_js(value, 0, 0) {
                Ok(parsed) => {
                    let directives = get_directives!();
                    directives.custom.push(VCustomDirective {
                        name: directive_name.into(),
                        argument,
                        modifiers,
                        value: Some(parsed),
                    });
                }
                Result::Err(_) => {}
            }
        }
    };

    Ok((input, ()))
}

/// Converts a raw Option<&str> argument to an argument
/// which value is either a string or a js expression.
/// If parsing Js fails, returns Err.
fn convert_argument<'s>(
    argument: Option<FervidAtom>,
    is_dynamic: bool,
    input: &'s str,
) -> Result<Option<StrOrExpr>, nom::Err<nom::error::Error<&'s str>>> {
    match argument {
        Some(raw_arg) => {
            if is_dynamic {
                // TODO Span & better error
                let Ok(dynamic_argument) = parse_js(&raw_arg, 0, 0) else {
                    return Err(nom::Err::Error(nom::error::Error::from_error_kind(
                        input,
                        ErrorKind::Fail,
                    )));
                };

                Ok(Some(StrOrExpr::Expr(dynamic_argument)))
            } else {
                Ok(Some(StrOrExpr::Str(raw_arg)))
            }
        }
        None => Ok(None),
    }
}

// fn parse_dynamic_attr(input: &str) -> IResult<&str, HtmlAttribute> {
//     let (input, directive) = parse_directive(input)?;

//     #[cfg(dbg_print)]
//     println!("Dynamic attr: directive = {:?}", directive);

//     /* Try taking a `=` char, early return if it's not there */
//     if !input.starts_with('=') {
//         return Ok((input, directive));
//     }

//     let (input, attr_value) = parse_attr_value(&input[1..])?;

//     #[cfg(dbg_print)]
//     println!("Dynamic attr: value = {:?}", attr_value);

//     match directive {
//         HtmlAttribute::VDirective(directive) => Ok((
//             input,
//             HtmlAttribute::VDirective(VDirective {
//                 value: Some(attr_value),
//                 ..directive
//             }),
//         )),

//         /* Not possible, because parse_directive returns a directive indeed */
//         _ => Err(nom::Err::Error(nom::error::Error {
//             code: nom::error::ErrorKind::Fail,
//             input,
//         })),
//     }
// }

fn split_itervar_and_iterable<'a>(raw: &'a str) -> Option<(&'a str, &'a str)> {
    // Try guessing: `item in iterable`
    let mut split = raw.splitn(2, " in ");
    if let (Some(itervar), Some(iterable)) = (split.next(), split.next()) {
        return Some((itervar.trim(), iterable.trim()));
    }

    // Try `item of iterable`
    let mut split = raw.splitn(2, " of ");
    if let (Some(itervar), Some(iterable)) = (split.next(), split.next()) {
        return Some((itervar.trim(), iterable.trim()));
    }

    // Not valid
    None
}