Skip to main content

achitek_source/
lib.rs

1//! Shared source-analysis primitives for Achitek crates.
2//!
3//! This crate intentionally stays small. It contains cross-language plumbing
4//! such as byte positions, source ranges, spanned values, diagnostic severity,
5//! and Tree-sitter range helpers. Domain-specific models and diagnostic codes
6//! belong in the language crates that define those contracts.
7//!
8//! # Example
9//!
10//! ```
11//! let range = achitek_source::TextRange {
12//!     start: achitek_source::TextPosition { line: 0, byte: 0 },
13//!     end: achitek_source::TextPosition { line: 0, byte: 7 },
14//! };
15//! let spanned = achitek_source::Spanned {
16//!     value: "project",
17//!     range,
18//! };
19//!
20//! assert_eq!(spanned.as_ref(), &"project");
21//! assert_eq!(spanned.range.start.line, 0);
22//! ```
23
24#![deny(missing_docs)]
25
26use tree_sitter::{Node, Point, Range};
27
28/// Severity level for a source diagnostic.
29///
30/// Severity indicates how tools should present a diagnostic. Errors describe
31/// invalid source that should prevent normal execution. Warnings describe
32/// suspicious source that can still be analyzed. Hints provide low-priority
33/// guidance.
34///
35/// ```
36/// let severity = achitek_source::Severity::Warning;
37///
38/// assert_eq!(severity.to_string(), "warning");
39/// ```
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub enum Severity {
43    /// Invalid source that should prevent normal execution.
44    Error,
45    /// Suspicious source that can still be analyzed.
46    Warning,
47    /// Low-priority guidance.
48    Hint,
49}
50
51impl std::fmt::Display for Severity {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        let severity = match self {
54            Self::Error => "error",
55            Self::Warning => "warning",
56            Self::Hint => "hint",
57        };
58
59        f.write_str(severity)
60    }
61}
62
63/// A zero-based byte position in source text.
64///
65/// `line` and `byte` use Tree-sitter's native coordinate system: the line is
66/// zero-based and `byte` is the zero-based UTF-8 byte offset from the beginning
67/// of that line.
68///
69/// ```
70/// let position = achitek_source::TextPosition { line: 2, byte: 4 };
71///
72/// assert_eq!(position.line, 2);
73/// assert_eq!(position.byte, 4);
74/// ```
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
76#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
77pub struct TextPosition {
78    /// Zero-based line number.
79    pub line: usize,
80
81    /// Zero-based UTF-8 byte offset within the line.
82    pub byte: usize,
83}
84
85impl TextPosition {
86    /// Creates a source position from a zero-based line and UTF-8 byte offset.
87    ///
88    /// ```
89    /// let position = achitek_source::TextPosition::new(3, 8);
90    ///
91    /// assert_eq!(position.line, 3);
92    /// assert_eq!(position.byte, 8);
93    /// ```
94    pub fn new(line: usize, byte: usize) -> Self {
95        Self { line, byte }
96    }
97}
98
99impl From<Point> for TextPosition {
100    fn from(point: Point) -> Self {
101        Self {
102            line: point.row,
103            byte: point.column,
104        }
105    }
106}
107
108/// A byte range in source text.
109///
110/// The range starts at `start` and ends at `end`, both expressed as zero-based
111/// line plus UTF-8 byte offset positions. Consumers can convert this into their
112/// presentation protocol's expected position encoding.
113///
114/// ```
115/// let range = achitek_source::TextRange {
116///     start: achitek_source::TextPosition { line: 0, byte: 0 },
117///     end: achitek_source::TextPosition { line: 0, byte: 4 },
118/// };
119///
120/// assert_eq!(range.start.byte, 0);
121/// assert_eq!(range.end.byte, 4);
122/// ```
123#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
124#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
125pub struct TextRange {
126    /// Start position of the range.
127    pub start: TextPosition,
128
129    /// End position of the range.
130    pub end: TextPosition,
131}
132
133impl TextRange {
134    /// Creates a source range from start and end positions.
135    ///
136    /// ```
137    /// let range = achitek_source::TextRange::new(
138    ///     achitek_source::TextPosition::new(0, 0),
139    ///     achitek_source::TextPosition::new(0, 4),
140    /// );
141    ///
142    /// assert_eq!(range.end.byte, 4);
143    /// ```
144    pub fn new(start: TextPosition, end: TextPosition) -> Self {
145        Self { start, end }
146    }
147}
148
149impl From<Range> for TextRange {
150    fn from(range: Range) -> Self {
151        Self {
152            start: range.start_point.into(),
153            end: range.end_point.into(),
154        }
155    }
156}
157
158/// A value paired with the source range that produced it.
159///
160/// Spans let editor-facing consumers connect recovered model values back to the
161/// original source text without exposing Tree-sitter nodes.
162///
163/// ```
164/// let spanned = achitek_source::Spanned {
165///     value: "name",
166///     range: achitek_source::TextRange::default(),
167/// };
168///
169/// assert_eq!(spanned.as_ref(), &"name");
170/// ```
171#[derive(Debug, Clone, PartialEq, Eq, Hash)]
172#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
173pub struct Spanned<T> {
174    /// Recovered model value.
175    pub value: T,
176    /// Source range that produced the value.
177    pub range: TextRange,
178}
179
180impl<T> Spanned<T> {
181    /// Creates a spanned value from a model value and source range.
182    ///
183    /// ```
184    /// let spanned = achitek_source::Spanned::new("name", achitek_source::TextRange::default());
185    ///
186    /// assert_eq!(spanned.value, "name");
187    /// ```
188    pub fn new(value: T, range: TextRange) -> Self {
189        Self { value, range }
190    }
191}
192
193impl<T> AsRef<T> for Spanned<T> {
194    fn as_ref(&self) -> &T {
195        &self.value
196    }
197}
198
199impl<T> AsMut<T> for Spanned<T> {
200    fn as_mut(&mut self) -> &mut T {
201        &mut self.value
202    }
203}
204
205/// Returns named children for a Tree-sitter node.
206///
207/// ```
208/// # fn example(node: tree_sitter::Node<'_>) {
209/// let named_kinds = achitek_source::named_children(node)
210///     .map(|child| child.kind())
211///     .collect::<Vec<_>>();
212/// # let _ = named_kinds;
213/// # }
214/// ```
215pub fn named_children(node: Node<'_>) -> std::vec::IntoIter<Node<'_>> {
216    let mut cursor = node.walk();
217    node.named_children(&mut cursor)
218        .collect::<Vec<_>>()
219        .into_iter()
220}
221
222/// Returns the UTF-8 source text covered by a Tree-sitter node.
223///
224/// Tree-sitter byte ranges are expected to align with the original source text
225/// supplied to the parser. A panic here indicates the parser tree and source
226/// text no longer belong together.
227///
228/// ```
229/// # fn example(node: tree_sitter::Node<'_>, source: &str) {
230/// let source_text = achitek_source::text(node, source);
231/// # let _ = source_text;
232/// # }
233/// ```
234pub fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
235    node.utf8_text(source.as_bytes())
236        .expect("tree-sitter node byte ranges should be valid utf-8 slices")
237}
238
239/// Converts a Tree-sitter node range into a source text range.
240///
241/// ```
242/// # fn example(node: tree_sitter::Node<'_>) {
243/// let range = achitek_source::text_range_for_node(node);
244///
245/// assert!(range.start <= range.end);
246/// # }
247/// ```
248pub fn text_range_for_node(node: Node<'_>) -> TextRange {
249    TextRange {
250        start: node.start_position().into(),
251        end: node.end_position().into(),
252    }
253}
254
255/// Returns true when `node` is the child assigned to `field_name` on `parent`.
256///
257/// ```
258/// # fn example(parent: tree_sitter::Node<'_>, child: tree_sitter::Node<'_>) {
259/// if achitek_source::is_child_for_field(parent, child, "name") {
260///     assert_eq!(parent.child_by_field_name("name"), Some(child));
261/// }
262/// # }
263/// ```
264pub fn is_child_for_field(parent: Node<'_>, node: Node<'_>, field_name: &str) -> bool {
265    parent
266        .child_by_field_name(field_name)
267        .is_some_and(|child| child == node)
268}