Skip to content

Commit

Permalink
fix(swc-plugin-power-assert): store span as offset at the start of Pr…
Browse files Browse the repository at this point in the history
…ogram/Module node due to SWC issue

swc-project/swc#1366
  • Loading branch information
adrianchu0120 committed Dec 29, 2023
1 parent 73fe528 commit 19e1012
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/swc-plugin-power-assert/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ struct ArgumentMetadata {
}

pub struct TransformVisitor {
span_offset: usize,
powered_var_cnt: usize,
argrec_var_cnt: usize,
target_variables: HashSet<JsWord>,
Expand All @@ -109,6 +110,7 @@ pub struct TransformVisitor {
impl Default for TransformVisitor {
fn default() -> Self {
let mut visitor = TransformVisitor {
span_offset: 0,
powered_var_cnt: 0,
argrec_var_cnt: 0,
target_variables: HashSet::new(),
Expand Down Expand Up @@ -474,8 +476,8 @@ impl TransformVisitor {

match self.code {
Some(ref code) => {
let start = (n.span.lo.0 - 1) as usize;
let end = (n.span.hi.0 - 1) as usize;
let start = (n.span.lo.0 as usize) - self.span_offset - 1;
let end = (n.span.hi.0 as usize) - self.span_offset - 1;
let assertion_code = code[start..end].to_string();

self.assertion_metadata = Some(AssertionMetadata {
Expand Down Expand Up @@ -574,6 +576,18 @@ impl VisitMut for TransformVisitor {
// A comprehensive list of possible visitor methods can be found here:
// https://rustdoc.swc.rs/swc_ecma_visit/trait.VisitMut.html

fn visit_mut_program(&mut self, n: &mut Program) {
// store span as offset at the start of Program node due to SWC issue https://github.com/swc-project/swc/issues/1366
self.span_offset = (n.span_lo().0 - 1) as usize;
n.visit_mut_children_with(self);
}

fn visit_mut_module(&mut self, n: &mut swc_core::ecma::ast::Module) {
// store span as offset at the start of Module node due to SWC issue https://github.com/swc-project/swc/issues/1366
self.span_offset = (n.span_lo().0 - 1) as usize;
n.visit_mut_children_with(self);
}

fn visit_mut_import_decl(&mut self, n: &mut ImportDecl) {
if self.target_modules.contains_key(&n.src.value) {
let module_name = &n.src.value;
Expand Down

0 comments on commit 19e1012

Please sign in to comment.