#![deny(missing_docs)]
use tree_sitter::{Node, Point, Range};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Severity {
Error,
Warning,
Hint,
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let severity = match self {
Self::Error => "error",
Self::Warning => "warning",
Self::Hint => "hint",
};
f.write_str(severity)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextPosition {
pub line: usize,
pub byte: usize,
}
impl TextPosition {
pub fn new(line: usize, byte: usize) -> Self {
Self { line, byte }
}
}
impl From<Point> for TextPosition {
fn from(point: Point) -> Self {
Self {
line: point.row,
byte: point.column,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextRange {
pub start: TextPosition,
pub end: TextPosition,
}
impl TextRange {
pub fn new(start: TextPosition, end: TextPosition) -> Self {
Self { start, end }
}
}
impl From<Range> for TextRange {
fn from(range: Range) -> Self {
Self {
start: range.start_point.into(),
end: range.end_point.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Spanned<T> {
pub value: T,
pub range: TextRange,
}
impl<T> Spanned<T> {
pub fn new(value: T, range: TextRange) -> Self {
Self { value, range }
}
}
impl<T> AsRef<T> for Spanned<T> {
fn as_ref(&self) -> &T {
&self.value
}
}
impl<T> AsMut<T> for Spanned<T> {
fn as_mut(&mut self) -> &mut T {
&mut self.value
}
}
pub fn named_children(node: Node<'_>) -> std::vec::IntoIter<Node<'_>> {
let mut cursor = node.walk();
node.named_children(&mut cursor)
.collect::<Vec<_>>()
.into_iter()
}
pub fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
node.utf8_text(source.as_bytes())
.expect("tree-sitter node byte ranges should be valid utf-8 slices")
}
pub fn text_range_for_node(node: Node<'_>) -> TextRange {
TextRange {
start: node.start_position().into(),
end: node.end_position().into(),
}
}
pub fn is_child_for_field(parent: Node<'_>, node: Node<'_>, field_name: &str) -> bool {
parent
.child_by_field_name(field_name)
.is_some_and(|child| child == node)
}