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
use fervid_core::{
AttributeOrBinding, FervidAtom, StrOrExpr, VBindDirective, VCustomDirective, VForDirective,
VModelDirective, VOnDirective, VSlotDirective, VueDirectives,
};
use swc_core::{common::{BytePos, Span}, ecma::ast::Expr};
use swc_ecma_parser::Syntax;
use swc_html_ast::Attribute;
use crate::{
error::{ParseError, ParseErrorKind},
SfcParser,
};
impl SfcParser<'_, '_, '_> {
/// Returns `true` when `v-pre` is discovered
pub fn process_element_attributes(
&mut self,
raw_attributes: Vec<Attribute>,
attrs_or_bindings: &mut Vec<AttributeOrBinding>,
vue_directives: &mut Option<Box<VueDirectives>>,
) -> bool {
// Skip any kind of processing for `v-pre` mode
if self.is_pre {
attrs_or_bindings.extend(raw_attributes.into_iter().map(create_regular_attribute));
return false;
}
// Check existence of `v-pre` in attributes
let has_v_pre = raw_attributes.iter().any(|attr| attr.name == "v-pre");
if has_v_pre {
attrs_or_bindings.extend(
raw_attributes
.into_iter()
.filter(|attr| attr.name != "v-pre")
.map(create_regular_attribute),
);
return true;
}
for mut raw_attribute in raw_attributes.into_iter() {
// Use raw names for attributes, otherwise SWC transforms them to lowercase
// `-1` is needed because SWC spans start from 1
let raw_idx_start = raw_attribute.span.lo.0 as usize - 1;
let raw_idx_end = raw_idx_start + raw_attribute.name.len();
raw_attribute.name = FervidAtom::from(&self.input[raw_idx_start..raw_idx_end]);
match self.try_parse_directive(raw_attribute, attrs_or_bindings, vue_directives) {
Ok(()) => {
// do nothing, we are good already
}
// parse as a raw attribute
Err(raw_attribute) => {
attrs_or_bindings.push(create_regular_attribute(raw_attribute))
}
}
}
// No `v-pre` found in attributes
false
}
/// Returns `true` if it was recognized as a directive (regardless if it was successfully parsed)
pub fn try_parse_directive(
&mut self,
raw_attribute: Attribute,
attrs_or_bindings: &mut Vec<AttributeOrBinding>,
vue_directives: &mut Option<Box<VueDirectives>>,
) -> Result<(), Attribute> {
macro_rules! bail {
// Everything is okay, this is just not a directive
() => {
return Err(raw_attribute);
};
// Parsing directive failed
($err_kind: expr) => {
self.errors.push(ParseError {
kind: $err_kind,
span: raw_attribute.span,
});
return Err(raw_attribute);
};
(js, $parse_error: expr) => {
self.errors.push($parse_error);
return Err(raw_attribute);
};
}
macro_rules! ts {
() => {
Syntax::Typescript(Default::default())
};
}
// TODO Fix and test parsing of directives
// TODO Should the span be narrower? (It can be narrowed with lo = lo + name.len() + 1 and hi = hi - 1)
let span = raw_attribute.span;
let raw_name: &str = &raw_attribute.name;
let mut chars_iter = raw_name.chars().enumerate().peekable();
// Every directive starts with a prefix: `@`, `:`, `.`, `#` or `v-`
let Some((_, prefix)) = chars_iter.next() else {
bail!(ParseErrorKind::DirectiveSyntax);
};
// https://vuejs.org/api/built-in-directives.html#v-bind
let mut is_bind_prop = false;
let mut expect_argument = true;
let mut argument_start = 0;
let mut argument_end = raw_name.len();
let directive_name = match prefix {
'@' => "on",
':' => "bind",
'.' => {
is_bind_prop = true;
"bind"
}
'#' => "slot",
'v' if matches!(chars_iter.next(), Some((_, '-'))) => {
// Read directive name
let mut start = 0;
let mut end = raw_name.len();
while let Some((idx, c)) = chars_iter.next() {
if c == '.' {
expect_argument = false;
argument_end = idx;
end = idx;
break;
}
if c == ':' {
end = idx;
break;
}
if start == 0 {
// `idx` is never 0 because zero-th char is `prefix`
start = idx;
}
}
// Directive syntax is bad if we could not read the directive name
if start == 0 {
bail!(ParseErrorKind::DirectiveSyntax);
}
&raw_name[start..end]
}
_ => {
bail!();
}
};
// Try parsing argument (it is optional and may be empty though)
let mut argument: Option<StrOrExpr> = None;
if expect_argument {
while let Some((idx, c)) = chars_iter.next() {
if c == '.' {
argument_end = idx;
break;
}
if argument_start == 0 {
argument_start = idx;
}
}
if argument_start != 0 {
let mut raw_argument = &raw_name[argument_start..argument_end];
let mut is_dynamic_argument = false;
// Dynamic argument: `:[dynamic-argument]`
if raw_argument.starts_with('[') {
// Check syntax
if !raw_argument.ends_with(']') {
bail!(ParseErrorKind::DynamicArgument);
}
raw_argument =
&raw_argument['['.len_utf8()..(raw_argument.len() - ']'.len_utf8())];
if raw_argument.is_empty() {
bail!(ParseErrorKind::DynamicArgument);
}
is_dynamic_argument = true;
}
if is_dynamic_argument {
// TODO Narrower span?
let parsed_argument = match self.parse_expr(raw_argument, ts!(), span) {
Ok(parsed) => parsed,
Err(expr_err) => {
bail!(js, expr_err);
}
};
argument = Some(StrOrExpr::Expr(parsed_argument));
} else {
argument = Some(StrOrExpr::Str(FervidAtom::from(raw_argument)));
}
}
}
// Try parsing modifiers, it is a simple string split
let mut modifiers = Vec::<FervidAtom>::new();
if argument_end != 0 {
for modifier in raw_name[argument_end..]
.split('.')
.filter(|m| !m.is_empty())
{
modifiers.push(FervidAtom::from(modifier));
}
}
/// Unwrapping the value or failing
macro_rules! expect_value {
() => {
if let Some(ref value) = raw_attribute.value {
value
} else {
bail!(ParseErrorKind::DirectiveSyntax);
}
};
}
macro_rules! get_directives {
() => {
vue_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) => {
match self.parse_expr($value, ts!(), span) {
Ok(parsed) => {
let directives = get_directives!();
directives.$key = Some(parsed);
}
Result::Err(expr_err) => self.report_error(expr_err),
}
};
}
// Construct the directives from parts
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!();
let parsed_expr = match self.parse_expr(&value, ts!(), span) {
Ok(parsed) => parsed,
Err(expr_err) => {
bail!(js, expr_err);
}
};
attrs_or_bindings.push(AttributeOrBinding::VBind(VBindDirective {
argument,
value: parsed_expr,
is_camel,
is_prop,
is_attr,
span,
}));
}
"on" => {
let handler = match raw_attribute.value {
Some(ref value) => match self.parse_expr(&value, ts!(), span) {
Ok(parsed) => Some(parsed),
Err(expr_err) => {
bail!(js, expr_err);
}
},
None => None,
};
attrs_or_bindings.push(AttributeOrBinding::VOn(VOnDirective {
event: argument,
handler,
modifiers,
span,
}));
}
"if" => {
let value = expect_value!();
push_directive_js!(v_if, &value);
}
"else-if" => {
let value = expect_value!();
push_directive_js!(v_else_if, &value);
}
"else" => {
push_directive!(v_else, ());
}
"for" => {
let value = expect_value!();
let Some(((itervar, itervar_span), (iterable, iterable_span))) =
split_itervar_and_iterable(&value, span)
else {
bail!(ParseErrorKind::DirectiveSyntax);
};
match self.parse_expr(itervar, ts!(), itervar_span) {
Ok(itervar) => match self.parse_expr(iterable, ts!(), iterable_span) {
Ok(iterable) => {
push_directive!(
v_for,
VForDirective {
iterable,
itervar,
patch_flags: Default::default(),
span
}
);
}
Result::Err(expr_err) => self.report_error(expr_err),
},
Result::Err(expr_err) => self.report_error(expr_err),
};
}
"model" => {
let value = expect_value!();
match self.parse_expr(&value, ts!(), span) {
Ok(model_binding) => {
// v-model value must be a valid JavaScript member expression
if !matches!(*model_binding, Expr::Member(_) | Expr::Ident(_)) {
// TODO Report an error
bail!();
}
let directives = get_directives!();
directives.v_model.push(VModelDirective {
argument,
value: model_binding,
update_handler: None,
modifiers,
span,
});
}
Result::Err(_) => {}
}
}
"slot" => {
let value =
raw_attribute
.value
.and_then(|v| match self.parse_pat(&v, ts!(), span) {
Ok(value) => Some(Box::new(value)),
Result::Err(_) => None,
});
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: {
// If no value, include as is
let Some(value) = raw_attribute.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 self.parse_expr(&value, ts!(), span) {
Ok(parsed) => {
let directives = get_directives!();
directives.custom.push(VCustomDirective {
name: directive_name.into(),
argument,
modifiers,
value: Some(parsed),
});
}
Result::Err(expr_err) => self.report_error(expr_err),
}
}
}
Ok(())
}
}
/// Creates `AttributeOrBinding::RegularAttribute`
#[inline]
pub fn create_regular_attribute(raw_attribute: Attribute) -> AttributeOrBinding {
AttributeOrBinding::RegularAttribute {
name: raw_attribute.name,
value: raw_attribute.value.unwrap_or_default(),
span: raw_attribute.span,
}
}
fn split_itervar_and_iterable<'a>(
raw: &'a str,
original_span: Span,
) -> Option<((&'a str, Span), (&'a str, Span))> {
// `item in iterable` or `item of iterable`
let Some(split_idx) = raw.find(" in ").or_else(|| raw.find(" of ")) else {
return None;
};
const SPLIT_LEN: usize = " in ".len();
// Get the trimmed itervar and its span
let mut offset = original_span.lo.0;
let mut itervar = &raw[..split_idx];
let mut itervar_old_len = itervar.len();
itervar = itervar.trim_start();
let itervar_lo = BytePos(offset + (itervar_old_len - itervar.len()) as u32);
itervar_old_len = itervar.len();
itervar = itervar.trim_end();
let itervar_hi = BytePos(offset + (split_idx - (itervar_old_len - itervar.len())) as u32);
let iterable_start = split_idx + SPLIT_LEN;
offset += iterable_start as u32;
let mut iterable = &raw[iterable_start..];
let iterable_old_len = iterable.len();
iterable = iterable.trim_start();
let iterable_lo = BytePos(offset + (iterable_old_len - iterable.len()) as u32);
iterable = iterable.trim_end();
let iterable_hi = BytePos(iterable_lo.0 + iterable.len() as u32);
if itervar.is_empty() || iterable.is_empty() {
return None;
}
let new_span_itervar = Span {
lo: itervar_lo,
hi: itervar_hi,
ctxt: original_span.ctxt,
};
let new_span_iterable = Span {
lo: iterable_lo,
hi: iterable_hi,
ctxt: original_span.ctxt,
};
Some(((itervar, new_span_itervar), (iterable, new_span_iterable)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_correctly_splits_itervar_iterable() {
macro_rules! check {
($input: expr, $itervar: expr, $itervar_lo: expr, $itervar_hi: expr, $iterable: expr, $iterable_lo: expr, $iterable_hi: expr) => {
let input = $input;
let span = Span {
lo: BytePos(1),
hi: BytePos((input.len() + 1) as u32),
ctxt: Default::default(),
};
let Some(((itervar, itervar_span), (iterable, iterable_span))) =
split_itervar_and_iterable(input, span)
else {
panic!("Did not manage to split")
};
assert_eq!($itervar, itervar);
assert_eq!($itervar_lo, itervar_span.lo.0);
assert_eq!($itervar_hi, itervar_span.hi.0);
assert_eq!($iterable, iterable);
assert_eq!($iterable_lo, iterable_span.lo.0);
assert_eq!($iterable_hi, iterable_span.hi.0);
};
}
// Trivial (all `Span`s start from 1)
check!("item in list", "item", 1, 5, "list", 9, 13);
check!("item of list", "item", 1, 5, "list", 9, 13);
check!("i in 3", "i", 1, 2, "3", 6, 7);
// A bit harder
check!(" item in \n \t list ", "item", 4, 8, "list", 19, 23);
}
}