Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/oxc_transformer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ impl<'a, 'ctx> Traverse<'a> for TransformerImpl<'a, 'ctx> {
}

fn enter_statement(&mut self, stmt: &mut Statement<'a>, ctx: &mut TraverseCtx<'a>) {
println!("index {:?}", ctx.ancestor_index(stmt));
self.x0_typescript.enter_statement(stmt, ctx);
}

Expand Down
32 changes: 31 additions & 1 deletion crates/oxc_traverse/src/context/ancestry.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use std::mem::transmute;

use oxc_ast::ast::Statement;
use oxc_data_structures::stack::NonEmptyStack;

use crate::ancestor::{Ancestor, AncestorType};
use crate::ancestor::{
Ancestor, AncestorType, OFFSET_FUNCTION_BODY_STATEMENTS, OFFSET_PROGRAM_BODY,
};

const INITIAL_STACK_CAPACITY: usize = 64; // 64 entries = 1 KiB

Expand Down Expand Up @@ -88,6 +91,33 @@ impl<'a> TraverseAncestry<'a> {
}
}

#[allow(clippy::cast_ptr_alignment)]
pub fn ancestor_index<'t>(&'t self, statement: &Statement<'a>) -> Option<usize> {
let ancestor = self.ancestor(0);

let node_ptr = statement as *const Statement<'a>;

let base_ptr = match ancestor {
Ancestor::FunctionBodyStatements(container) => unsafe {
&*container
.0
.cast::<u8>()
.add(OFFSET_FUNCTION_BODY_STATEMENTS)
.cast::<oxc_allocator::Vec<'a, Statement<'a>>>()
},
Ancestor::ProgramBody(container) => unsafe {
&*container
.0
.cast::<u8>()
.add(OFFSET_PROGRAM_BODY)
.cast::<oxc_allocator::Vec<'a, Statement<'a>>>()
},
_ => return None,
};

Some(unsafe { node_ptr.offset_from(base_ptr.as_ptr()) as usize })
}

/// Get iterator over ancestors, starting with parent and working up.
///
/// Last `Ancestor` returned will be `Program`. `Ancestor::None` is not included in iteration.
Expand Down
6 changes: 6 additions & 0 deletions crates/oxc_traverse/src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,12 @@ impl<'a> TraverseCtx<'a> {
self.ancestry.ancestor(level)
}

/// Get the index of the current node in `Vec<'a, Statements<'a>>`.
#[inline]
pub fn ancestor_index<'t>(&'t self, statement: &Statement<'a>) -> Option<usize> {
self.ancestry.ancestor_index(statement)
}

/// Get iterator over ancestors, starting with parent and working up.
///
/// Last `Ancestor` returned will be `Program`. `Ancestor::None` is not included in iteration.
Expand Down