Skip to content

feat: add Syntax::layers_for_byte_range #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
46 changes: 30 additions & 16 deletions highlighter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,24 +170,38 @@ impl Syntax {
.descendant_for_byte_range(start, end)
}

/// # Returns
///
/// The smallest injection layer that fully includes the range `start..=end`.
pub fn layer_for_byte_range(&self, start: u32, end: u32) -> Layer {
let mut cursor = self.root;
loop {
let layer = &self.layers[cursor.idx()];
let Some(start_injection) = layer.injection_at_byte_idx(start) else {
break;
};
self.layers_for_byte_range(start, end)
.last()
.unwrap_or(self.root)
}

/// # Returns
///
/// A iterator of layers which **fully include** the byte range `start..=end`,
/// in decreasing order based on the size of each layer.
///
/// The first layer is the `root` layer.
pub fn layers_for_byte_range(&self, start: u32, end: u32) -> impl Iterator<Item = Layer> {
let mut parent_injection_layer = self.root;

std::iter::from_fn(move || {
let layer = &self.layers[parent_injection_layer.idx()];

let injection_at_start = layer.injection_at_byte_idx(start)?;

// +1 because the end is exclusive.
let Some(end_injection) = layer.injection_at_byte_idx(end + 1) else {
break;
};
if start_injection.layer == end_injection.layer {
cursor = start_injection.layer;
} else {
break;
}
}
cursor
let injection_at_end = layer.injection_at_byte_idx(end + 1)?;

(injection_at_start.layer == injection_at_end.layer).then(|| {
parent_injection_layer = injection_at_start.layer;

injection_at_start.layer
})
})
}

pub fn walk(&self) -> TreeCursor {
Expand Down