vue_oxc_toolkit 0.1.0

A parser to generate semantically correct AST from .vue file. Good for linting integration
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use std::cell::RefCell;
use std::collections::HashSet;
use std::mem;

use oxc_allocator::{self, Dummy, TakeIn, Vec as ArenaVec};
use oxc_ast::ast::{
  Expression, FormalParameterKind, JSXAttributeItem, JSXChild, JSXExpression, Program,
  PropertyKind, Statement,
};
use oxc_ast::{Comment, CommentKind, NONE};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::{Atom, SPAN, SourceType, Span};
use oxc_syntax::module_record::ModuleRecord;
use vue_compiler_core::SourceLocation;
use vue_compiler_core::parser::{
  AstNode, Directive, DirectiveArg, ElemProp, Element, ParseOption, Parser, SourceNode, TextNode,
  WhitespaceStrategy,
};
use vue_compiler_core::scanner::{ScanOption, Scanner};
use vue_compiler_core::util::find_prop;

use crate::parser::error::OxcErrorHandler;
use crate::parser::modules::Merge;

use super::ParserImpl;
use super::ParserImplReturn;
use super::utils::is_simple_identifier;

pub trait SourceLocatonSpan {
  fn span(&self) -> Span;
}

impl SourceLocatonSpan for SourceLocation {
  fn span(&self) -> Span {
    Span::new(self.start.offset as u32, self.end.offset as u32)
  }
}

impl<'a> ParserImpl<'a> {
  fn get_oxc_parser(
    &self,
    source_text: &'a str,
    source_type: SourceType,
  ) -> oxc_parser::Parser<'a> {
    oxc_parser::Parser::new(self.allocator, source_text, source_type).with_options(self.options)
  }

  /// A workaround
  /// Use comment placeholder to make the location AST returned correct
  /// The start must > 4 in any valid Vue files
  fn pad_source(&self, source: &str, start: usize) -> String {
    format!("/*{}*/{source}", &self.empty_str[..start - 4])
  }
}

impl<'a> ParserImpl<'a> {
  pub fn parse(mut self) -> ParserImplReturn<'a> {
    match self.get_root_children() {
      Some(children) => {
        let span = Span::new(0, self.source_text.len() as u32);
        self.fix_module_records(span);

        ParserImplReturn {
          program: self.ast.program(
            span,
            self.source_type,
            self.source_text,
            self.comments.take_in(self.ast.allocator),
            None, // no hashbang needed for vue files
            self.ast.vec(),
            self.ast.vec1(self.ast.statement_expression(
              SPAN,
              self.ast.expression_jsx_fragment(
                SPAN,
                self.ast.jsx_opening_fragment(SPAN),
                children,
                self.ast.jsx_closing_fragment(SPAN),
              ),
            )),
          ),
          fatal: false,
          errors: self.errors,
          module_record: self.module_records,
        }
      }
      None => ParserImplReturn {
        program: Program::dummy(self.allocator),
        fatal: true,
        errors: self.errors,
        module_record: ModuleRecord::new(self.allocator),
      },
    }
  }

  fn get_root_children(&mut self) -> Option<ArenaVec<'a, JSXChild<'a>>> {
    let parser = Parser::new(ParseOption {
      whitespace: WhitespaceStrategy::Preserve,
      ..Default::default()
    });

    // get ast from vue-compiler-core
    let scanner = Scanner::new(ScanOption::default());
    // error processing
    let errors = RefCell::from(&mut self.errors);
    let panicked = RefCell::from(false);
    let tokens = scanner.scan(self.source_text, OxcErrorHandler::new(&errors, &panicked));
    let result = parser.parse(tokens, OxcErrorHandler::new(&errors, &panicked));

    if *panicked.borrow() {
      return None;
    }

    let mut source_types: HashSet<&str> = HashSet::new();
    let mut children = self.ast.vec();
    for child in result.children {
      match child {
        AstNode::Element(node) => {
          if node.tag_name == "script" {
            let lang = find_prop(&node, "lang")
              .and_then(|p| match p.get_ref() {
                ElemProp::Attr(p) => p.value.as_ref().map(|value| value.content.raw),
                ElemProp::Dir(_) => None,
              })
              .unwrap_or("js");

            source_types.insert(lang);

            if source_types.len() > 1 {
              self.errors.push(OxcDiagnostic::error(format!(
                "Multiple script tags with different languages: {source_types:?}"
              )));

              return None;
            }

            self.source_type = if lang.starts_with("js") {
              SourceType::jsx()
            } else if lang.starts_with("ts") {
              SourceType::tsx()
            } else {
              self.errors.push(OxcDiagnostic::error(format!(
                "Unsupported script language: {lang}"
              )));

              return None;
            };

            let script_block = if let Some(child) = node.children.first() {
              let span = child.get_location().span();
              let source = span.source_text(self.source_text);

              let ret = self
                .get_oxc_parser(
                  self
                    .ast
                    .atom(&self.pad_source(source, span.start as usize))
                    .as_str(),
                  // SAFETY: lang is validated above to be "js" or "ts" based extensions which are valid for from_extension
                  SourceType::from_extension(lang).unwrap(),
                )
                .parse();

              self.errors.extend(ret.errors);
              if ret.panicked {
                return None;
              }

              // Deal with modules record there
              let is_setup = find_prop(&node, "setup").is_some();

              if is_setup {
                // Only merge imports, as exports are not allowed in <script setup>
                self.module_records.merge_imports(ret.module_record);
              } else {
                self.module_records.merge(ret.module_record);
              }

              ret.program.body
            } else {
              self.ast.vec()
            };
            children.push(self.parse_element(
              node,
              Some(self.ast.vec1(self.ast.jsx_child_expression_container(
                SPAN,
                JSXExpression::ArrowFunctionExpression(self.ast.alloc_arrow_function_expression(
                  SPAN,
                  false,
                  false,
                  NONE,
                  self.ast.formal_parameters(
                    SPAN,
                    FormalParameterKind::ArrowFormalParameters,
                    self.ast.vec(),
                    NONE,
                  ),
                  NONE,
                  self.ast.function_body(SPAN, self.ast.vec(), script_block),
                )),
              ))),
            )?);
          } else if node.tag_name == "template" {
            children.push(self.parse_element(node, None)?);
          }
        }
        AstNode::Text(text) => children.push(self.parse_text(&text)),
        AstNode::Comment(comment) => children.push(self.parse_comment(&comment)),
        AstNode::Interpolation(interp) => children.push(self.parse_interpolation(&interp)?),
      }
    }

    Some(children)
  }

  fn parse_children(
    &mut self,
    start: u32,
    end: u32,
    children: Vec<AstNode<'a>>,
  ) -> Option<ArenaVec<'a, JSXChild<'a>>> {
    let ast = self.ast;
    if children.is_empty() {
      return Some(ast.vec());
    }
    let mut result = self.ast.vec_with_capacity(children.len() + 2);

    // Process the whitespaces text there <div>____<br>_____</div>
    if let Some(first) = children.first()
      && matches!(first, AstNode::Element(_) | AstNode::Interpolation(_))
      && start != first.get_location().start.offset as u32
    {
      let span = Span::new(start, first.get_location().start.offset as u32);
      let value = span.source_text(self.source_text);
      result.push(ast.jsx_child_text(span, value, Some(ast.atom(value))));
    }

    let last = if let Some(last) = children.last()
      && matches!(last, AstNode::Element(_) | AstNode::Interpolation(_))
      && end != last.get_location().end.offset as u32
    {
      let span = Span::new(last.get_location().end.offset as u32, end);
      let value = span.source_text(self.source_text);
      Some(ast.jsx_child_text(span, value, Some(ast.atom(value))))
    } else {
      None
    };

    for child in children {
      result.push(match child {
        AstNode::Element(node) => self.parse_element(node, None)?,
        AstNode::Text(text) => self.parse_text(&text),
        AstNode::Comment(comment) => self.parse_comment(&comment),
        AstNode::Interpolation(interp) => self.parse_interpolation(&interp)?,
      });
    }

    if let Some(last) = last {
      result.push(last);
    }

    Some(result)
  }

  fn parse_element(
    &mut self,
    node: Element<'a>,
    children: Option<ArenaVec<'a, JSXChild<'a>>>,
  ) -> Option<JSXChild<'a>> {
    let ast = self.ast;

    let open_element_span = {
      let start = node.location.start.offset;
      let end = if let Some(prop) = node.properties.last() {
        self.offset(match prop {
          ElemProp::Attr(prop) => prop.location.end.offset,
          ElemProp::Dir(prop) => prop.location.end.offset,
        })
      } else {
        start + 1 + node.tag_name.len()
      } + 1;
      Span::new(start as u32, end as u32)
    };

    let location_span = node.location.span();
    let end_element_span = {
      if location_span.source_text(self.source_text).ends_with("/>") {
        node.location.span()
      } else {
        let end = node.location.end.offset;
        let start = self.roffset(end).saturating_sub(node.tag_name.len() + 3) as u32;
        Span::new(start, end as u32)
      }
    };

    let mut attributes = ast.vec();
    for prop in node.properties {
      attributes.push(self.parse_attribute(prop)?);
    }

    Some(ast.jsx_child_element(
      location_span,
      ast.jsx_opening_element(
        open_element_span,
        ast.jsx_element_name_identifier(
          Span::new(
            open_element_span.start + 1,
            open_element_span.start + 1 + node.tag_name.len() as u32,
          ),
          ast.atom(node.tag_name),
        ),
        NONE,
        attributes,
      ),
      if let Some(children) = children {
        children
      } else {
        self.parse_children(open_element_span.end, end_element_span.start, node.children)?
      },
      if end_element_span.eq(&location_span) {
        None
      } else {
        Some(ast.jsx_closing_element(
          end_element_span,
          ast.jsx_element_name_identifier(
            Span::new(
              end_element_span.start + 2,
              end_element_span.start + 2 + node.tag_name.len() as u32,
            ),
            ast.atom(node.tag_name),
          ),
        ))
      },
    ))
  }

  fn parse_attribute(&mut self, prop: ElemProp<'a>) -> Option<JSXAttributeItem<'a>> {
    let ast = self.ast;
    match prop {
      ElemProp::Attr(attr) => {
        let attr_end = self.roffset(attr.location.end.offset) as u32;
        let attr_span = Span::new(attr.location.start.offset as u32, attr_end);
        Some(ast.jsx_attribute_item_attribute(
          attr_span,
          ast.jsx_attribute_name_identifier(attr.name_loc.span(), ast.atom(attr.name)),
          if let Some(value) = attr.value {
            Some(ast.jsx_attribute_value_string_literal(
              Span::new(value.location.span().start + 1, attr_end - 1),
              ast.atom(value.content.raw),
              None,
            ))
          } else {
            None
          },
        ))
      }
      ElemProp::Dir(mut dir) => {
        let dir_start = dir.location.start.offset as u32;
        let dir_end = self.roffset(dir.location.end.offset) as u32;
        let head_name = dir.head_loc.span().source_text(self.source_text);
        let modifiers = mem::take(&mut dir.modifiers);
        Some(ast.jsx_attribute_item_attribute(
          Span::new(dir_start, dir_end),
          match dir.name {
            "bind" => {
              if let Some(argument) = &dir.argument {
                if let DirectiveArg::Dynamic(_) = argument {
                  // :[foo]="bar"
                  ast.jsx_attribute_name_identifier(
                    Span::new(dir_start, dir_start + 1),
                    ast.atom(&format!("v-bind{}", Self::parse_modifiers(&modifiers))),
                  )
                } else if head_name.starts_with(':') {
                  // :foo="bar"
                  ast.jsx_attribute_name_identifier(
                    Span::new(dir_start + 1, dir.head_loc.end.offset as u32),
                    // SAFETY: dir.argument must be Some(DirectiveArg) for :foo shorthand
                    self.parse_argument(dir.argument.as_ref().unwrap(), &modifiers),
                  )
                } else {
                  // v-bind:foo="bar"
                  ast.jsx_attribute_name_namespaced_name(
                    dir.head_loc.span(),
                    ast.jsx_identifier(Span::new(dir_start, dir_start + 6), ast.atom("v-bind")),
                    ast.jsx_identifier(
                      Span::new(dir_start + 7, dir.head_loc.end.offset as u32),
                      // SAFETY: dir.argument must be Some(DirectiveArg) for v-bind:foo
                      self.parse_argument(dir.argument.as_ref().unwrap(), &modifiers),
                    ),
                  )
                }
              } else {
                // v-bind="obj"
                ast.jsx_attribute_name_identifier(
                  dir.head_loc.span(),
                  ast.atom(&format!("v-bind{}", Self::parse_modifiers(&modifiers))),
                )
              }
            }
            _ => {
              if let Some(argument) = &dir.argument {
                let namespace_end = if head_name.starts_with("v-") {
                  dir_start + 2 + dir.name.len() as u32
                } else {
                  dir_start + 1
                };
                match argument {
                  DirectiveArg::Static(arg) => ast.jsx_attribute_name_namespaced_name(
                    dir.head_loc.span(),
                    ast.jsx_identifier(
                      Span::new(dir_start, namespace_end),
                      ast.atom(&format!("v-{}", dir.name)),
                    ),
                    ast.jsx_identifier(
                      if head_name.starts_with("v-") {
                        Span::new(namespace_end + 1, namespace_end + 1 + arg.len() as u32)
                      } else {
                        Span::new(namespace_end, namespace_end + arg.len() as u32)
                      },
                      // SAFETY: dir.argument is checked to be Some(DirectiveArg::Static(arg)) in this match arm
                      self.parse_argument(dir.argument.as_ref().unwrap(), &modifiers),
                    ),
                  ),
                  DirectiveArg::Dynamic(_) => ast.jsx_attribute_name_identifier(
                    Span::new(dir_start, dir_start + 1),
                    ast.atom(&format!(
                      "v-{}{}",
                      dir.name,
                      // SAFETY: dir.argument is checked to be Some(DirectiveArg::Dynamic(_)) in this match arm
                      self.parse_argument(dir.argument.as_ref().unwrap(), &modifiers)
                    )),
                  ),
                }
              } else {
                ast.jsx_attribute_name_identifier(
                  dir.head_loc.span(),
                  self.ast.atom(&format!(
                    "v-{}{}",
                    dir.name,
                    Self::parse_modifiers(&modifiers)
                  )),
                )
              }
            }
          },
          if let Some(expr) = &dir.expression {
            if matches!(dir.name, "for" | "slot") {
              // TODO: Handle for and slot
              None
            } else {
              let expression =
                self.parse_expression(expr.content.raw, expr.location.start.offset)?;

              Some(ast.jsx_attribute_value_expression_container(
                Span::new(expr.location.start.offset as u32 + 1, dir_end - 1),
                self.parse_dynamic_argument(&dir, expression)?.into(),
              ))
            }
          } else if let Some(argument) = &dir.argument
            && let DirectiveArg::Dynamic(_) = argument
          {
            // v-slot:[name]
            Some(
              ast.jsx_attribute_value_expression_container(
                SPAN,
                self
                  .parse_dynamic_argument(&dir, ast.expression_identifier(SPAN, "undefined"))?
                  .into(),
              ),
            )
          } else {
            None
          },
        ))
      }
    }
  }

  fn parse_dynamic_argument(
    &mut self,
    dir: &Directive<'a>,
    expression: Expression<'a>,
  ) -> Option<Expression<'a>> {
    let head_name = dir.head_loc.span().source_text(self.source_text);
    let dir_start = dir.location.start.offset;
    if let Some(argument) = &dir.argument
      && let DirectiveArg::Dynamic(argument_str) = argument
    {
      let dynamic_arg_expression = self.parse_expression(
        argument_str,
        if head_name.starts_with("v-") {
          dir_start + 2 + dir.name.len() + 1
        } else {
          dir_start + 1
        },
      )?;
      Some(self.ast.expression_object(
        SPAN,
        self.ast.vec1(self.ast.object_property_kind_object_property(
          SPAN,
          PropertyKind::Init,
          dynamic_arg_expression.into(),
          expression,
          false,
          false,
          true,
        )),
      ))
    } else {
      Some(expression)
    }
  }

  fn parse_argument(&self, argument: &DirectiveArg, modifiers: &[&'a str]) -> Atom<'a> {
    self.ast.atom(&format!(
      "{}{}",
      match argument {
        DirectiveArg::Static(arg) => arg,
        DirectiveArg::Dynamic(_) => "",
      },
      Self::parse_modifiers(modifiers)
    ))
  }
  fn parse_modifiers(modifiers: &[&str]) -> String {
    if modifiers.is_empty() {
      String::new()
    } else {
      format!("_{}", modifiers.join("_"))
    }
  }

  fn parse_text(&self, text: &TextNode<'a>) -> JSXChild<'a> {
    let raw = self
      .ast
      .atom(&text.text.iter().map(|t| t.raw).collect::<String>());
    self
      .ast
      .jsx_child_text(text.location.span(), raw, Some(raw))
  }

  fn parse_comment(&mut self, comment: &SourceNode<'a>) -> JSXChild<'a> {
    let ast = self.ast;
    let span = comment.location.span();
    self.comments.push(Comment::new(
      span.start + 1,
      span.end - 1,
      if comment.source.contains('\n') {
        CommentKind::MultiLineBlock
      } else {
        CommentKind::SingleLineBlock
      },
    ));
    ast.jsx_child_expression_container(
      span,
      ast.jsx_expression_empty_expression(Span::new(span.start + 1, span.end - 1)),
    )
  }

  fn parse_interpolation(&mut self, introp: &SourceNode<'a>) -> Option<JSXChild<'a>> {
    let ast = self.ast;
    let span = Span::new(
      introp.location.start.offset as u32 + 1,
      introp.location.end.offset as u32 - 1,
    );
    Some(
      ast.jsx_child_expression_container(
        span,
        self
          .parse_expression(introp.source, span.start as usize)?
          .into(),
      ),
    )
  }

  fn parse_expression(&mut self, source: &'a str, start: usize) -> Option<Expression<'a>> {
    let ast = &self.ast;
    if is_simple_identifier(source) {
      return Some(ast.expression_identifier(
        Span::new(start as u32 + 1, (start + source.len() + 1) as u32),
        source,
      ));
    }

    let ret = self
      .get_oxc_parser(
        ast
          .atom(&self.pad_source(&format!("({source})"), start.saturating_sub(1)))
          .as_str(),
        self.source_type,
      )
      .parse();

    self.errors.extend(ret.errors);

    if ret.panicked {
      return None;
    }

    let mut program = ret.program;

    let Some(Statement::ExpressionStatement(stmt)) = program.body.get_mut(0) else {
      // SAFETY: We always wrap the source in parentheses, so it should always be an expression statement
      // if it was valid partially. If it's invalid, the parser might return empty body if it fails early.
      // unreachable!()
      return None;
    };
    let Expression::ParenthesizedExpression(expression) = &mut stmt.expression else {
      // unreachable!()
      return None;
    };
    Some(expression.expression.take_in(self.allocator))
  }

  fn offset(&self, start: usize) -> usize {
    start
      + self.source_text[start..]
        .chars()
        .take_while(|c| c.is_whitespace())
        .count()
  }

  fn roffset(&self, end: usize) -> usize {
    end
      - self.source_text[..end]
        .chars()
        .rev()
        .take_while(|c| c.is_whitespace())
        .count()
  }
}

#[cfg(test)]
mod tests {
  use crate::test_ast;

  #[test]
  fn basic_vue() {
    test_ast!("basic.vue");
    test_ast!("typescript.vue");
  }

  #[test]
  fn errors() {
    test_ast!("error/template.vue", true, true);
    test_ast!("error/interpolation.vue", true, true);
    test_ast!("error/recoverable-script.vue", true, false);
    test_ast!("error/recoverable-directive.vue", true, false);
    test_ast!("error/irrecoverable-script.vue", true, true);
    test_ast!("error/irrecoverable-directive.vue", true, true);
  }
}