Skip to content

Commit

Permalink
fix: memoize pattern positions to prevent recalculating needlesly
Browse files Browse the repository at this point in the history
  • Loading branch information
ErinvanderVeen committed Apr 4, 2024
1 parent e5e19d0 commit ff395ce
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions topiary-core/src/tree_sitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,14 @@ pub fn apply_query(

log::debug!("List of atoms before formatting: {atoms:?}");

// Memoization of the pattern positions
let mut pattern_positions: Vec<Option<Position>> = Vec::new();

// Only reallocate if we are actually going to use the vec
if log::log_enabled!(log::Level::Info) {
pattern_positions.resize(query.query.pattern_count(), None);
}

// If there are more than one capture per match, it generally means that we
// want to use the last capture. For example
// (
Expand All @@ -244,12 +252,15 @@ pub fn apply_query(
// )
// means we want to append a hardline at
// the end, but we don't know if we get a line_comment capture or not.

for m in matches {
// Convert the byte offset given the source to a row, col pair
// NOTE: Only performed if logging is enabled to avoid unnecessary computation
// NOTE: Only performed if logging is enabled to avoid unnecessary computation of Position
if log::log_enabled!(log::Level::Info) {
let pos = query.pattern_position(m.pattern_index as usize);
// Fetch from pattern_positions, otherwise insert
let pos = pattern_positions[m.pattern_index as usize].unwrap_or_else(|| {
let pos = query.pattern_position(m.pattern_index as usize);
pattern_positions[m.pattern_index as usize] = Some(pos);
pos
});

log::info!("Processing match: {m} at location {pos}");
}
Expand Down

0 comments on commit ff395ce

Please sign in to comment.