1#![cfg_attr(not(any(test, doctest)), doc = include_str!("./README.md"))]
3#![cfg_attr(not(feature = "std"), no_std)]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5
6pub mod ffi;
7mod sexp;
8
9#[doc(hidden)]
10pub use sexp::format_sexp;
11
12#[cfg(any(
13 not(feature = "std"),
14 all(target_arch = "wasm32", target_os = "unknown")
15))]
16extern crate alloc;
17#[cfg(not(feature = "std"))]
18use alloc::{
19 boxed::Box,
20 string::{String, ToString},
21 vec::Vec,
22};
23use core::{
24 ffi::{CStr, c_char, c_void},
25 fmt, hash, iter,
26 marker::PhantomData,
27 num::NonZeroU16,
28 ops::{ControlFlow, Deref},
29 ptr::{self, NonNull},
30 slice, str,
31};
32#[cfg(feature = "std")]
33use std::error;
34#[cfg(all(unix, feature = "std"))]
35use std::os::fd::AsRawFd;
36#[cfg(all(windows, feature = "std"))]
37use std::os::windows::io::AsRawHandle;
38
39use tree_sitter_language::LanguageFn;
40
41#[cfg(feature = "wasm")]
42mod wasm_language;
43#[cfg(feature = "wasm")]
44#[cfg_attr(docsrs, doc(cfg(feature = "wasm")))]
45pub use wasm_language::*;
46
47#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
48mod wasm_allocator;
49
50#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
57pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
58
59#[doc(alias = "TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION")]
64pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize =
65 ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION as usize;
66
67pub const PARSER_HEADER: &str = include_str!("../src/parser.h");
68
69#[doc(alias = "TSLanguage")]
72#[derive(Debug, PartialEq, Eq, Hash)]
73#[repr(transparent)]
74pub struct Language(pub(crate) *const ffi::TSLanguage);
75
76pub struct LanguageRef<'a>(
77 pub(crate) *const ffi::TSLanguage,
78 pub(crate) PhantomData<&'a ()>,
79);
80
81#[doc(alias = "TSLanguageMetadata")]
86pub struct LanguageMetadata {
87 pub major_version: u8,
88 pub minor_version: u8,
89 pub patch_version: u8,
90}
91
92impl From<ffi::TSLanguageMetadata> for LanguageMetadata {
93 fn from(val: ffi::TSLanguageMetadata) -> Self {
94 Self {
95 major_version: val.major_version,
96 minor_version: val.minor_version,
97 patch_version: val.patch_version,
98 }
99 }
100}
101
102#[doc(alias = "TSTree")]
104pub struct Tree(NonNull<ffi::TSTree>);
105
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
110pub struct Point {
111 pub row: usize,
112 pub column: usize,
113}
114
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
118pub struct Range {
119 pub start_byte: usize,
120 pub end_byte: usize,
121 pub start_point: Point,
122 pub end_point: Point,
123}
124
125#[doc(alias = "TSNode")]
127#[derive(Clone, Copy)]
128#[repr(transparent)]
129pub struct Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>);
130
131#[doc(alias = "TSParser")]
134pub struct Parser(NonNull<ffi::TSParser>);
135
136pub struct ParseState(NonNull<ffi::TSParseState>);
139
140impl ParseState {
141 #[must_use]
142 pub const fn current_byte_offset(&self) -> usize {
143 unsafe { self.0.as_ref() }.current_byte_offset as usize
144 }
145
146 #[must_use]
147 pub const fn has_error(&self) -> bool {
148 unsafe { self.0.as_ref() }.has_error
149 }
150}
151
152#[derive(Default)]
153pub struct ParseOptions<'a> {
154 pub progress_callback: Option<ParseProgressCallback<'a>>,
155}
156
157impl<'a> ParseOptions<'a> {
158 #[must_use]
159 pub fn new() -> Self {
160 Self::default()
161 }
162
163 #[must_use]
164 pub fn progress_callback<F: FnMut(&ParseState) -> ControlFlow<()>>(
165 mut self,
166 callback: &'a mut F,
167 ) -> Self {
168 self.progress_callback = Some(callback);
169 self
170 }
171
172 #[must_use]
177 pub fn reborrow(&mut self) -> ParseOptions {
178 ParseOptions {
179 progress_callback: match &mut self.progress_callback {
180 Some(cb) => Some(*cb),
181 None => None,
182 },
183 }
184 }
185}
186
187#[derive(Debug, PartialEq, Eq)]
189pub enum LogType {
190 Parse,
191 Lex,
192}
193
194type FieldId = NonZeroU16;
195
196type Logger = Box<dyn FnMut(LogType, &str) + Send + 'static>;
198
199type UnsafeLogger<'a> = Box<dyn FnMut(LogType, &str) + Send + 'a>;
201
202type ParseProgressCallback<'a> = &'a mut dyn FnMut(&ParseState) -> ControlFlow<()>;
204
205pub trait Decode {
206 fn decode(bytes: &[u8]) -> (i32, u32);
209}
210
211#[doc(alias = "TSTreeCursor")]
213pub struct TreeCursor<'tree>(ffi::TSTreeCursor, PhantomData<&'tree ()>);
214
215#[derive(Debug, PartialEq, Eq)]
219pub enum LanguageError {
220 Version(usize),
221 NotParseable,
222 #[cfg(feature = "wasm")]
223 Wasm,
224}
225
226#[derive(Debug, PartialEq, Eq)]
228pub struct IncludedRangesError(pub usize);
229
230impl Language {
231 #[must_use]
232 pub fn new(builder: LanguageFn) -> Self {
233 Self(unsafe { builder.into_raw()().cast() })
234 }
235
236 #[doc(alias = "ts_language_is_parseable")]
245 #[must_use]
246 pub fn is_parseable(&self) -> bool {
247 unsafe { ffi::ts_language_is_parseable(self.0) }
248 }
249
250 #[doc(alias = "ts_language_name")]
253 #[must_use]
254 pub fn name(&self) -> Option<&str> {
255 let ptr = unsafe { ffi::ts_language_name(self.0) };
256 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
257 }
258
259 #[doc(alias = "ts_language_abi_version")]
266 #[must_use]
267 pub fn abi_version(&self) -> usize {
268 unsafe { ffi::ts_language_abi_version(self.0) as usize }
269 }
270
271 #[doc(alias = "ts_language_metadata")]
278 #[must_use]
279 pub fn metadata(&self) -> Option<LanguageMetadata> {
280 unsafe {
281 let ptr = ffi::ts_language_metadata(self.0);
282 (!ptr.is_null()).then(|| (*ptr).into())
283 }
284 }
285
286 #[doc(alias = "ts_language_symbol_count")]
288 #[must_use]
289 pub fn node_kind_count(&self) -> usize {
290 unsafe { ffi::ts_language_symbol_count(self.0) as usize }
291 }
292
293 #[doc(alias = "ts_language_state_count")]
295 #[must_use]
296 pub fn parse_state_count(&self) -> usize {
297 unsafe { ffi::ts_language_state_count(self.0) as usize }
298 }
299
300 #[doc(alias = "ts_language_supertypes")]
303 #[must_use]
304 pub fn supertypes(&self) -> &[u16] {
305 let mut length = 0u32;
306 unsafe {
307 let ptr = ffi::ts_language_supertypes(self.0, core::ptr::addr_of_mut!(length));
308 if length == 0 {
309 &[]
310 } else {
311 slice::from_raw_parts(ptr.cast_mut(), length as usize)
312 }
313 }
314 }
315
316 #[doc(alias = "ts_language_supertype_map")]
319 #[must_use]
320 pub fn subtypes_for_supertype(&self, supertype: u16) -> &[u16] {
321 unsafe {
322 let mut length = 0u32;
323 let ptr = ffi::ts_language_subtypes(self.0, supertype, core::ptr::addr_of_mut!(length));
324 if length == 0 {
325 &[]
326 } else {
327 slice::from_raw_parts(ptr.cast_mut(), length as usize)
328 }
329 }
330 }
331
332 #[doc(alias = "ts_language_symbol_name")]
334 #[must_use]
335 pub fn node_kind_for_id(&self, id: u16) -> Option<&str> {
336 let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
337 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
338 }
339
340 #[doc(alias = "ts_language_symbol_for_name")]
342 #[must_use]
343 pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
344 unsafe {
345 ffi::ts_language_symbol_for_name(
346 self.0,
347 kind.as_bytes().as_ptr().cast::<c_char>(),
348 kind.len() as u32,
349 named,
350 )
351 }
352 }
353
354 fn node_kind_id_is_valid(&self, id: u16) -> bool {
361 (id as usize) < self.node_kind_count() || id >= u16::MAX - 1
362 }
363
364 #[must_use]
367 pub fn node_kind_is_named(&self, id: u16) -> bool {
368 self.node_kind_id_is_valid(id)
369 && unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeRegular }
370 }
371
372 #[must_use]
375 pub fn node_kind_is_visible(&self, id: u16) -> bool {
376 self.node_kind_id_is_valid(id)
377 && unsafe { ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolTypeAnonymous }
378 }
379
380 #[must_use]
382 pub fn node_kind_is_supertype(&self, id: u16) -> bool {
383 self.node_kind_id_is_valid(id)
384 && unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeSupertype }
385 }
386
387 #[doc(alias = "ts_language_field_count")]
389 #[must_use]
390 pub fn field_count(&self) -> usize {
391 unsafe { ffi::ts_language_field_count(self.0) as usize }
392 }
393
394 #[doc(alias = "ts_language_field_name_for_id")]
396 #[must_use]
397 pub fn field_name_for_id(&self, field_id: u16) -> Option<&str> {
398 let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
399 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
400 }
401
402 #[doc(alias = "ts_language_field_id_for_name")]
404 #[must_use]
405 pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId> {
406 let field_name = field_name.as_ref();
407 let id = unsafe {
408 ffi::ts_language_field_id_for_name(
409 self.0,
410 field_name.as_ptr().cast::<c_char>(),
411 field_name.len() as u32,
412 )
413 };
414 FieldId::new(id)
415 }
416}
417
418impl From<LanguageFn> for Language {
419 fn from(value: LanguageFn) -> Self {
420 Self::new(value)
421 }
422}
423
424impl Clone for Language {
425 fn clone(&self) -> Self {
426 unsafe { Self(ffi::ts_language_copy(self.0)) }
427 }
428}
429
430impl Drop for Language {
431 fn drop(&mut self) {
432 unsafe { ffi::ts_language_delete(self.0) }
433 }
434}
435
436impl Deref for LanguageRef<'_> {
437 type Target = Language;
438
439 fn deref(&self) -> &Self::Target {
440 unsafe { &*(core::ptr::addr_of!(self.0).cast::<Language>()) }
441 }
442}
443
444impl Default for Parser {
445 fn default() -> Self {
446 Self::new()
447 }
448}
449
450impl Parser {
451 #[doc(alias = "ts_parser_new")]
453 #[must_use]
454 pub fn new() -> Self {
455 unsafe {
456 let parser = ffi::ts_parser_new();
457 Self(NonNull::new_unchecked(parser))
458 }
459 }
460
461 #[doc(alias = "ts_parser_set_language")]
468 pub fn set_language(&mut self, language: &Language) -> Result<(), LanguageError> {
469 let version = language.abi_version();
470 if (MIN_COMPATIBLE_LANGUAGE_VERSION..=LANGUAGE_VERSION).contains(&version) {
471 if !language.is_parseable() {
472 return Err(LanguageError::NotParseable);
473 }
474 if !unsafe { ffi::ts_parser_set_language(self.0.as_ptr(), language.0) } {
475 #[cfg(feature = "wasm")]
476 if language.is_wasm() {
477 return Err(LanguageError::Wasm);
478 }
479 return Err(LanguageError::NotParseable);
480 }
481 Ok(())
482 } else {
483 Err(LanguageError::Version(version))
484 }
485 }
486
487 #[doc(alias = "ts_parser_language")]
489 #[must_use]
490 pub fn language(&self) -> Option<LanguageRef<'_>> {
491 let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
492 (!ptr.is_null()).then_some(LanguageRef(ptr, PhantomData))
493 }
494
495 #[doc(alias = "ts_parser_logger")]
497 #[must_use]
498 pub fn logger(&self) -> Option<&Logger> {
499 let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
500 unsafe { logger.payload.cast::<Logger>().as_ref() }
501 }
502
503 #[doc(alias = "ts_parser_set_logger")]
508 pub fn set_logger(&mut self, logger: Option<Logger>) {
509 unsafe { self.set_logger_unchecked(logger) };
511 }
512
513 pub unsafe fn set_logger_unchecked(&mut self, logger: Option<UnsafeLogger<'_>>) {
522 let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
523 if !prev_logger.payload.is_null() {
524 drop(unsafe { Box::from_raw(prev_logger.payload.cast::<Logger>()) });
525 }
526
527 let c_logger = if let Some(logger) = logger {
528 let container = Box::new(logger);
529
530 unsafe extern "C" fn log(
531 payload: *mut c_void,
532 c_log_type: ffi::TSLogType,
533 c_message: *const c_char,
534 ) {
535 unsafe {
536 let callback = payload.cast::<Logger>().as_mut().unwrap();
537 if let Ok(message) = CStr::from_ptr(c_message).to_str() {
538 let log_type = if c_log_type == ffi::TSLogTypeParse {
539 LogType::Parse
540 } else {
541 LogType::Lex
542 };
543 callback(log_type, message);
544 }
545 }
546 }
547
548 let raw_container = Box::into_raw(container);
549
550 ffi::TSLogger {
551 payload: raw_container.cast::<c_void>(),
552 log: Some(log),
553 }
554 } else {
555 ffi::TSLogger {
556 payload: ptr::null_mut(),
557 log: None,
558 }
559 };
560
561 unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
562 }
563
564 #[doc(alias = "ts_parser_print_dot_graphs")]
569 #[cfg(not(target_os = "wasi"))]
570 #[cfg(feature = "std")]
571 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
572 pub fn print_dot_graphs(
573 &mut self,
574 #[cfg(unix)] file: &impl AsRawFd,
575 #[cfg(windows)] file: &impl AsRawHandle,
576 ) {
577 #[cfg(unix)]
578 {
579 let fd = file.as_raw_fd();
580 unsafe {
581 ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(fd));
582 }
583 }
584
585 #[cfg(windows)]
586 {
587 let handle = file.as_raw_handle();
588 unsafe {
589 ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(handle));
590 }
591 }
592 }
593
594 #[doc(alias = "ts_parser_print_dot_graphs")]
596 #[cfg(not(target_os = "wasi"))]
597 #[cfg(feature = "std")]
598 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
599 pub fn stop_printing_dot_graphs(&mut self) {
600 unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
601 }
602
603 #[doc(alias = "ts_parser_parse")]
611 pub fn parse(&mut self, text: impl AsRef<[u8]>) -> Option<Tree> {
612 let bytes = text.as_ref();
613 if let Ok(len) = u32::try_from(bytes.len()) {
614 return unsafe {
615 self.parse_raw_bytes(
616 (bytes.as_ptr().cast::<c_char>(), len),
617 ffi::TSInputEncodingUTF8,
618 )
619 };
620 }
621 let len = bytes.len();
622 self.parse_with_options(
623 &mut |i, _| {
624 if i < len {
625 &bytes[i..]
626 } else {
627 Default::default()
628 }
629 },
630 None,
631 )
632 }
633
634 pub fn parse_with_options<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
643 &mut self,
644 callback: &mut F,
645 options: Option<ParseOptions>,
646 ) -> Option<Tree> {
647 self.parse_chunks::<0, u8, T, F>(callback, (options, ffi::TSInputEncodingUTF8, None))
648 }
649
650 pub fn parse_utf16_le(&mut self, input: impl AsRef<[u16]>) -> Option<Tree> {
655 self.parse_utf16_slice::<true>(input.as_ref())
656 }
657
658 pub fn parse_utf16_le_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
667 &mut self,
668 callback: &mut F,
669 options: Option<ParseOptions>,
670 ) -> Option<Tree> {
671 self.parse_utf16_with_options::<true, T, F>(callback, options)
672 }
673
674 pub fn parse_utf16_be(&mut self, input: impl AsRef<[u16]>) -> Option<Tree> {
679 self.parse_utf16_slice::<false>(input.as_ref())
680 }
681
682 pub fn parse_utf16_be_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
691 &mut self,
692 callback: &mut F,
693 options: Option<ParseOptions>,
694 ) -> Option<Tree> {
695 self.parse_utf16_with_options::<false, T, F>(callback, options)
696 }
697
698 pub fn parse_custom_encoding<D: Decode, T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
712 &mut self,
713 callback: &mut F,
714 options: Option<ParseOptions>,
715 ) -> Option<Tree> {
716 unsafe extern "C" fn decode_fn<D: Decode>(
717 data: *const u8,
718 len: u32,
719 code_point: *mut i32,
720 ) -> u32 {
721 unsafe {
722 let (c, len) = D::decode(core::slice::from_raw_parts(data, len as usize));
723 if let Some(code_point) = code_point.as_mut() {
724 *code_point = c;
725 }
726 len
727 }
728 }
729
730 self.parse_chunks::<0, u8, T, F>(
731 callback,
732 (options, ffi::TSInputEncodingCustom, Some(decode_fn::<D>)),
733 )
734 }
735
736 fn parse_utf16_slice<const LE: bool>(&mut self, code_points: &[u16]) -> Option<Tree> {
737 let encoding = if LE {
738 ffi::TSInputEncodingUTF16LE
739 } else {
740 ffi::TSInputEncodingUTF16BE
741 };
742 if let Some(byte_len) = code_points
743 .len()
744 .checked_mul(2)
745 .and_then(|n| u32::try_from(n).ok())
746 {
747 return unsafe {
748 self.parse_raw_bytes((code_points.as_ptr().cast::<c_char>(), byte_len), encoding)
749 };
750 }
751 let len = code_points.len();
752 self.parse_utf16_with_options::<LE, _, _>(
753 &mut |i, _| if i < len { &code_points[i..] } else { &[] },
754 None,
755 )
756 }
757
758 fn parse_utf16_with_options<const LE: bool, T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
759 &mut self,
760 callback: &mut F,
761 options: Option<ParseOptions>,
762 ) -> Option<Tree> {
763 let encoding = if LE {
764 ffi::TSInputEncodingUTF16LE
765 } else {
766 ffi::TSInputEncodingUTF16BE
767 };
768 self.parse_chunks::<1, u16, T, F>(callback, (options, encoding, None))
769 }
770
771 fn parse_chunks<const UNIT_SHIFT: u32, U, T: AsRef<[U]>, F: FnMut(usize, Point) -> T>(
772 &mut self,
773 callback: &mut F,
774 (options, encoding, decode): (
775 Option<ParseOptions>,
776 ffi::TSInputEncoding,
777 ffi::TSDecodeFunction,
778 ),
779 ) -> Option<Tree> {
780 type Payload<'a, F, T> = (&'a mut F, Option<T>);
781
782 unsafe extern "C" fn read<
783 const UNIT_SHIFT: u32,
784 U,
785 T: AsRef<[U]>,
786 F: FnMut(usize, Point) -> T,
787 >(
788 payload: *mut c_void,
789 byte_offset: u32,
790 position: ffi::TSPoint,
791 bytes_read: *mut u32,
792 ) -> *const c_char {
793 unsafe {
794 let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
795 *text = Some(callback(
796 (byte_offset as usize) >> UNIT_SHIFT,
797 Point {
798 row: position.row as usize,
799 column: (position.column as usize) >> UNIT_SHIFT,
800 },
801 ));
802 let slice = text.as_ref().unwrap().as_ref();
803 *bytes_read =
804 (slice.len().min((u32::MAX as usize) >> UNIT_SHIFT) << UNIT_SHIFT) as u32;
805 slice.as_ptr().cast::<c_char>()
806 }
807 }
808
809 let mut payload: Payload<F, T> = (callback, None);
811 let c_input = ffi::TSInput {
812 payload: ptr::addr_of_mut!(payload).cast::<c_void>(),
813 read: Some(read::<UNIT_SHIFT, U, T, F>),
814 encoding,
815 decode,
816 };
817 unsafe { self.parse_c_input(c_input, options) }
818 }
819
820 unsafe fn parse_raw_bytes(
821 &mut self,
822 (bytes, byte_len): (*const c_char, u32),
823 encoding: ffi::TSInputEncoding,
824 ) -> Option<Tree> {
825 let c_new_tree = unsafe {
826 ffi::ts_parser_parse_string_encoding(self.0.as_ptr(), bytes, byte_len, encoding)
827 };
828 NonNull::new(c_new_tree).map(Tree)
829 }
830
831 unsafe fn parse_c_input(
832 &mut self,
833 c_input: ffi::TSInput,
834 options: Option<ParseOptions>,
835 ) -> Option<Tree> {
836 unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
837 unsafe {
838 let callback = (*state)
839 .payload
840 .cast::<ParseProgressCallback>()
841 .as_mut()
842 .unwrap();
843 match callback(&ParseState::from_raw(state)) {
844 ControlFlow::Continue(()) => false,
845 ControlFlow::Break(()) => true,
846 }
847 }
848 }
849
850 let mut callback_ptr;
851 let parse_options = if let Some(cb) = options.and_then(|o| o.progress_callback) {
852 callback_ptr = cb;
853 ffi::TSParseOptions {
854 payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
855 progress_callback: Some(progress),
856 }
857 } else {
858 ffi::TSParseOptions {
859 payload: ptr::null_mut(),
860 progress_callback: None,
861 }
862 };
863
864 let c_new_tree =
865 unsafe { ffi::ts_parser_parse_with_options(self.0.as_ptr(), c_input, parse_options) };
866 NonNull::new(c_new_tree).map(Tree)
867 }
868
869 #[doc(alias = "ts_parser_reset")]
876 pub fn reset(&mut self) {
877 unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
878 }
879
880 #[doc(alias = "ts_parser_set_included_ranges")]
898 pub fn set_included_ranges(&mut self, ranges: &[Range]) -> Result<(), IncludedRangesError> {
899 let ts_ranges = ranges.iter().copied().map(Into::into).collect::<Vec<_>>();
900 let result = unsafe {
901 ffi::ts_parser_set_included_ranges(
902 self.0.as_ptr(),
903 ts_ranges.as_ptr(),
904 ts_ranges.len() as u32,
905 )
906 };
907
908 if result {
909 Ok(())
910 } else {
911 let mut prev_end_byte = 0;
912 for (i, range) in ranges.iter().enumerate() {
913 if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
914 return Err(IncludedRangesError(i));
915 }
916 prev_end_byte = range.end_byte;
917 }
918 Err(IncludedRangesError(0))
919 }
920 }
921
922 #[doc(alias = "ts_parser_included_ranges")]
924 #[must_use]
925 pub fn included_ranges(&self) -> Vec<Range> {
926 let mut count = 0u32;
927 unsafe {
928 let ptr =
929 ffi::ts_parser_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
930 let ranges = slice::from_raw_parts(ptr, count as usize);
931 ranges.iter().copied().map(Into::into).collect()
932 }
933 }
934}
935
936impl Drop for Parser {
937 fn drop(&mut self) {
938 #[cfg(feature = "std")]
939 #[cfg(not(target_os = "wasi"))]
940 {
941 self.stop_printing_dot_graphs();
942 }
943 self.set_logger(None);
944 unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
945 }
946}
947
948#[cfg(windows)]
949unsafe extern "C" {
950 fn _open_osfhandle(osfhandle: isize, flags: core::ffi::c_int) -> core::ffi::c_int;
951}
952
953impl Tree {
954 #[doc(alias = "ts_tree_root_node")]
956 #[must_use]
957 pub fn root_node(&self) -> Node {
958 Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
959 }
960
961 #[doc(alias = "ts_tree_root_node_with_offset")]
964 #[must_use]
965 pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
966 Node::new(unsafe {
967 ffi::ts_tree_root_node_with_offset(
968 self.0.as_ptr(),
969 offset_bytes as u32,
970 offset_extent.into(),
971 )
972 })
973 .unwrap()
974 }
975
976 #[doc(alias = "ts_tree_language")]
983 #[must_use]
984 pub fn language(&self) -> LanguageRef {
985 LanguageRef(
986 unsafe { ffi::ts_tree_language(self.0.as_ptr()) },
987 PhantomData,
988 )
989 }
990
991 #[must_use]
993 pub fn walk(&self) -> TreeCursor {
994 self.root_node().walk()
995 }
996
997 #[doc(alias = "ts_tree_included_ranges")]
999 #[must_use]
1000 pub fn included_ranges(&self) -> Vec<Range> {
1001 let mut count = 0u32;
1002 unsafe {
1003 let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
1004 let ranges = slice::from_raw_parts(ptr, count as usize);
1005 let result = ranges.iter().copied().map(Into::into).collect();
1006 ts_free(ptr.cast::<c_void>());
1007 result
1008 }
1009 }
1010
1011 #[doc(alias = "ts_tree_print_dot_graph")]
1016 #[cfg(not(target_os = "wasi"))]
1017 #[cfg(feature = "std")]
1018 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1019 pub fn print_dot_graph(
1020 &self,
1021 #[cfg(unix)] file: &impl AsRawFd,
1022 #[cfg(windows)] file: &impl AsRawHandle,
1023 ) {
1024 #[cfg(unix)]
1025 {
1026 let fd = file.as_raw_fd();
1027 unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1028 }
1029
1030 #[cfg(windows)]
1031 {
1032 let handle = file.as_raw_handle();
1033 let fd = unsafe { _open_osfhandle(handle as isize, 0) };
1034 unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1035 }
1036 }
1037}
1038
1039impl fmt::Debug for Tree {
1040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041 write!(f, "{{Tree {:?}}}", self.root_node())
1042 }
1043}
1044
1045impl Drop for Tree {
1046 fn drop(&mut self) {
1047 unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
1048 }
1049}
1050
1051impl Clone for Tree {
1052 fn clone(&self) -> Self {
1053 unsafe { Self(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
1054 }
1055}
1056
1057impl<'tree> Node<'tree> {
1058 fn new(node: ffi::TSNode) -> Option<Self> {
1059 (!node.id.is_null()).then_some(Node(node, PhantomData))
1060 }
1061
1062 #[must_use]
1064 pub fn id(&self) -> usize {
1065 self.0.id as usize
1066 }
1067
1068 #[doc(alias = "ts_node_symbol")]
1070 #[must_use]
1071 pub fn kind_id(&self) -> u16 {
1072 unsafe { ffi::ts_node_symbol(self.0) }
1073 }
1074
1075 #[doc(alias = "ts_node_grammar_symbol")]
1078 #[must_use]
1079 pub fn grammar_id(&self) -> u16 {
1080 unsafe { ffi::ts_node_grammar_symbol(self.0) }
1081 }
1082
1083 #[doc(alias = "ts_node_type")]
1085 #[must_use]
1086 pub fn kind(&self) -> &'tree str {
1087 let ptr = unsafe { ffi::ts_node_type(self.0) };
1088 assert!(!ptr.is_null());
1089 unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
1090 }
1091
1092 #[doc(alias = "ts_node_grammar_type")]
1095 #[must_use]
1096 pub fn grammar_name(&self) -> &'tree str {
1097 let ptr = unsafe { ffi::ts_node_grammar_type(self.0) };
1098 assert!(!ptr.is_null());
1099 unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
1100 }
1101
1102 #[doc(alias = "ts_node_language")]
1110 #[must_use]
1111 pub fn language(&self) -> LanguageRef<'tree> {
1112 LanguageRef(unsafe { ffi::ts_node_language(self.0) }, PhantomData)
1113 }
1114
1115 #[doc(alias = "ts_node_is_named")]
1120 #[must_use]
1121 pub fn is_named(&self) -> bool {
1122 unsafe { ffi::ts_node_is_named(self.0) }
1123 }
1124
1125 #[doc(alias = "ts_node_is_extra")]
1130 #[must_use]
1131 pub fn is_extra(&self) -> bool {
1132 unsafe { ffi::ts_node_is_extra(self.0) }
1133 }
1134
1135 #[doc(alias = "ts_node_has_error")]
1138 #[must_use]
1139 pub fn has_error(&self) -> bool {
1140 unsafe { ffi::ts_node_has_error(self.0) }
1141 }
1142
1143 #[doc(alias = "ts_node_is_error")]
1148 #[must_use]
1149 pub fn is_error(&self) -> bool {
1150 unsafe { ffi::ts_node_is_error(self.0) }
1151 }
1152
1153 #[doc(alias = "ts_node_is_missing")]
1158 #[must_use]
1159 pub fn is_missing(&self) -> bool {
1160 unsafe { ffi::ts_node_is_missing(self.0) }
1161 }
1162
1163 #[doc(alias = "ts_node_start_byte")]
1165 #[inline]
1166 #[must_use]
1167 pub const fn start_byte(&self) -> usize {
1168 self.0.context[0] as usize
1169 }
1170
1171 #[doc(alias = "ts_node_end_byte")]
1173 #[must_use]
1174 pub fn end_byte(&self) -> usize {
1175 unsafe { ffi::ts_node_end_byte(self.0) as usize }
1176 }
1177
1178 #[inline]
1180 #[must_use]
1181 pub fn byte_range(&self) -> core::ops::Range<usize> {
1182 self.start_byte()..self.end_byte()
1183 }
1184
1185 #[must_use]
1188 pub fn range(&self) -> Range {
1189 Range {
1190 start_byte: self.start_byte(),
1191 end_byte: self.end_byte(),
1192 start_point: self.start_position(),
1193 end_point: self.end_position(),
1194 }
1195 }
1196
1197 #[doc(alias = "ts_node_start_point")]
1199 #[inline]
1200 #[must_use]
1201 pub const fn start_position(&self) -> Point {
1202 Point {
1203 row: self.0.context[1] as usize,
1204 column: self.0.context[2] as usize,
1205 }
1206 }
1207
1208 #[doc(alias = "ts_node_end_point")]
1210 #[must_use]
1211 pub fn end_position(&self) -> Point {
1212 let result = unsafe { ffi::ts_node_end_point(self.0) };
1213 result.into()
1214 }
1215
1216 #[doc(alias = "ts_node_child")]
1223 #[must_use]
1224 pub fn child(&self, i: u32) -> Option<Self> {
1225 Self::new(unsafe { ffi::ts_node_child(self.0, i) })
1226 }
1227
1228 #[doc(alias = "ts_node_child_count")]
1230 #[must_use]
1231 pub fn child_count(&self) -> u32 {
1232 unsafe { ffi::ts_node_child_count(self.0) }
1233 }
1234
1235 #[doc(alias = "ts_node_named_child")]
1242 #[must_use]
1243 pub fn named_child(&self, i: u32) -> Option<Self> {
1244 Self::new(unsafe { ffi::ts_node_named_child(self.0, i) })
1245 }
1246
1247 #[doc(alias = "ts_node_named_child_count")]
1251 #[must_use]
1252 pub fn named_child_count(&self) -> usize {
1253 unsafe { ffi::ts_node_named_child_count(self.0) as usize }
1254 }
1255
1256 #[doc(alias = "ts_node_child_by_field_name")]
1261 #[must_use]
1262 pub fn child_by_field_name(&self, field_name: impl AsRef<[u8]>) -> Option<Self> {
1263 let field_name = field_name.as_ref();
1264 Self::new(unsafe {
1265 ffi::ts_node_child_by_field_name(
1266 self.0,
1267 field_name.as_ptr().cast::<c_char>(),
1268 field_name.len() as u32,
1269 )
1270 })
1271 }
1272
1273 #[doc(alias = "ts_node_child_by_field_id")]
1278 #[must_use]
1279 pub fn child_by_field_id(&self, field_id: u16) -> Option<Self> {
1280 Self::new(unsafe { ffi::ts_node_child_by_field_id(self.0, field_id) })
1281 }
1282
1283 #[doc(alias = "ts_node_field_name_for_child")]
1285 #[must_use]
1286 pub fn field_name_for_child(&self, child_index: u32) -> Option<&'tree str> {
1287 unsafe {
1288 let ptr = ffi::ts_node_field_name_for_child(self.0, child_index);
1289 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1290 }
1291 }
1292
1293 #[must_use]
1295 pub fn field_name_for_named_child(&self, named_child_index: u32) -> Option<&'tree str> {
1296 unsafe {
1297 let ptr = ffi::ts_node_field_name_for_named_child(self.0, named_child_index);
1298 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1299 }
1300 }
1301
1302 pub fn children<'cursor>(
1312 &self,
1313 cursor: &'cursor mut TreeCursor<'tree>,
1314 ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1315 cursor.reset(*self);
1316 cursor.goto_first_child();
1317 (0..self.child_count()).map(move |_| {
1318 let result = cursor.node();
1319 cursor.goto_next_sibling();
1320 result
1321 })
1322 }
1323
1324 pub fn named_children<'cursor>(
1328 &self,
1329 cursor: &'cursor mut TreeCursor<'tree>,
1330 ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1331 cursor.reset(*self);
1332 cursor.goto_first_child();
1333 (0..self.named_child_count()).map(move |_| {
1334 while !cursor.node().is_named() {
1335 if !cursor.goto_next_sibling() {
1336 break;
1337 }
1338 }
1339 let result = cursor.node();
1340 cursor.goto_next_sibling();
1341 result
1342 })
1343 }
1344
1345 pub fn children_by_field_name<'cursor>(
1349 &self,
1350 field_name: &str,
1351 cursor: &'cursor mut TreeCursor<'tree>,
1352 ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1353 let field_id = self.language().field_id_for_name(field_name);
1354 let mut done = field_id.is_none();
1355 if !done {
1356 cursor.reset(*self);
1357 cursor.goto_first_child();
1358 }
1359 iter::from_fn(move || {
1360 if !done {
1361 while cursor.field_id() != field_id {
1362 if !cursor.goto_next_sibling() {
1363 return None;
1364 }
1365 }
1366 let result = cursor.node();
1367 if !cursor.goto_next_sibling() {
1368 done = true;
1369 }
1370 return Some(result);
1371 }
1372 None
1373 })
1374 }
1375
1376 pub fn children_by_field_id<'cursor>(
1380 &self,
1381 field_id: FieldId,
1382 cursor: &'cursor mut TreeCursor<'tree>,
1383 ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1384 cursor.reset(*self);
1385 cursor.goto_first_child();
1386 let mut done = false;
1387 iter::from_fn(move || {
1388 if !done {
1389 while cursor.field_id() != Some(field_id) {
1390 if !cursor.goto_next_sibling() {
1391 return None;
1392 }
1393 }
1394 let result = cursor.node();
1395 if !cursor.goto_next_sibling() {
1396 done = true;
1397 }
1398 return Some(result);
1399 }
1400 None
1401 })
1402 }
1403
1404 #[doc(alias = "ts_node_parent")]
1408 #[must_use]
1409 pub fn parent(&self) -> Option<Self> {
1410 Self::new(unsafe { ffi::ts_node_parent(self.0) })
1411 }
1412
1413 #[doc(alias = "ts_node_child_with_descendant")]
1417 #[must_use]
1418 pub fn child_with_descendant(&self, descendant: Self) -> Option<Self> {
1419 Self::new(unsafe { ffi::ts_node_child_with_descendant(self.0, descendant.0) })
1420 }
1421
1422 #[doc(alias = "ts_node_next_sibling")]
1424 #[must_use]
1425 pub fn next_sibling(&self) -> Option<Self> {
1426 Self::new(unsafe { ffi::ts_node_next_sibling(self.0) })
1427 }
1428
1429 #[doc(alias = "ts_node_prev_sibling")]
1431 #[must_use]
1432 pub fn prev_sibling(&self) -> Option<Self> {
1433 Self::new(unsafe { ffi::ts_node_prev_sibling(self.0) })
1434 }
1435
1436 #[doc(alias = "ts_node_next_named_sibling")]
1438 #[must_use]
1439 pub fn next_named_sibling(&self) -> Option<Self> {
1440 Self::new(unsafe { ffi::ts_node_next_named_sibling(self.0) })
1441 }
1442
1443 #[doc(alias = "ts_node_prev_named_sibling")]
1445 #[must_use]
1446 pub fn prev_named_sibling(&self) -> Option<Self> {
1447 Self::new(unsafe { ffi::ts_node_prev_named_sibling(self.0) })
1448 }
1449
1450 #[doc(alias = "ts_node_first_child_for_byte")]
1452 #[must_use]
1453 pub fn first_child_for_byte(&self, byte: usize) -> Option<Self> {
1454 Self::new(unsafe { ffi::ts_node_first_child_for_byte(self.0, byte as u32) })
1455 }
1456
1457 #[doc(alias = "ts_node_first_named_child_for_point")]
1459 #[must_use]
1460 pub fn first_named_child_for_byte(&self, byte: usize) -> Option<Self> {
1461 Self::new(unsafe { ffi::ts_node_first_named_child_for_byte(self.0, byte as u32) })
1462 }
1463
1464 #[doc(alias = "ts_node_descendant_count")]
1466 #[must_use]
1467 pub fn descendant_count(&self) -> usize {
1468 unsafe { ffi::ts_node_descendant_count(self.0) as usize }
1469 }
1470
1471 #[doc(alias = "ts_node_descendant_for_byte_range")]
1473 #[must_use]
1474 pub fn descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
1475 Self::new(unsafe {
1476 ffi::ts_node_descendant_for_byte_range(self.0, start as u32, end as u32)
1477 })
1478 }
1479
1480 #[doc(alias = "ts_node_named_descendant_for_byte_range")]
1482 #[must_use]
1483 pub fn named_descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
1484 Self::new(unsafe {
1485 ffi::ts_node_named_descendant_for_byte_range(self.0, start as u32, end as u32)
1486 })
1487 }
1488
1489 #[doc(alias = "ts_node_descendant_for_point_range")]
1491 #[must_use]
1492 pub fn descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
1493 Self::new(unsafe {
1494 ffi::ts_node_descendant_for_point_range(self.0, start.into(), end.into())
1495 })
1496 }
1497
1498 #[doc(alias = "ts_node_named_descendant_for_point_range")]
1500 #[must_use]
1501 pub fn named_descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
1502 Self::new(unsafe {
1503 ffi::ts_node_named_descendant_for_point_range(self.0, start.into(), end.into())
1504 })
1505 }
1506
1507 #[doc(alias = "ts_node_string")]
1509 #[must_use]
1510 pub fn to_sexp(&self) -> String {
1511 let c_string = unsafe { ffi::ts_node_string(self.0) };
1512 let result = unsafe { CStr::from_ptr(c_string) }
1513 .to_str()
1514 .unwrap()
1515 .to_string();
1516 unsafe { ts_free(c_string.cast::<c_void>()) };
1517 result
1518 }
1519
1520 pub fn utf8_text<'a>(&self, source: &'a [u8]) -> Result<&'a str, str::Utf8Error> {
1521 str::from_utf8(&source[self.start_byte()..self.end_byte()])
1522 }
1523
1524 #[must_use]
1525 pub fn utf16_text<'a>(&self, source: &'a [u16]) -> &'a [u16] {
1526 &source[self.start_byte() / 2..self.end_byte() / 2]
1527 }
1528
1529 #[doc(alias = "ts_tree_cursor_new")]
1534 #[must_use]
1535 pub fn walk(&self) -> TreeCursor<'tree> {
1536 TreeCursor(unsafe { ffi::ts_tree_cursor_new(self.0) }, PhantomData)
1537 }
1538}
1539
1540impl PartialEq for Node<'_> {
1541 fn eq(&self, other: &Self) -> bool {
1542 core::ptr::eq(self.0.id, other.0.id)
1543 }
1544}
1545
1546impl Eq for Node<'_> {}
1547
1548impl hash::Hash for Node<'_> {
1549 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1550 self.0.id.hash(state);
1551 self.0.context[0].hash(state);
1552 self.0.context[1].hash(state);
1553 self.0.context[2].hash(state);
1554 self.0.context[3].hash(state);
1555 }
1556}
1557
1558impl fmt::Debug for Node<'_> {
1559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1560 write!(
1561 f,
1562 "{{Node {} {} - {}}}",
1563 self.kind(),
1564 self.start_position(),
1565 self.end_position()
1566 )
1567 }
1568}
1569
1570impl fmt::Display for Node<'_> {
1571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1572 if !f.alternate() {
1573 return f.write_str(&self.to_sexp());
1574 }
1575 let c_string = unsafe { ts_node_string_pretty(self.0, f.width().unwrap_or(0)) };
1576 let result = unsafe { CStr::from_ptr(c_string) }
1577 .to_str()
1578 .unwrap()
1579 .to_string();
1580 unsafe { ts_free(c_string.cast::<c_void>()) };
1581 f.write_str(&result)
1582 }
1583}
1584
1585impl<'tree> TreeCursor<'tree> {
1586 #[doc(alias = "ts_tree_cursor_current_node")]
1588 #[must_use]
1589 pub fn node(&self) -> Node<'tree> {
1590 Node(
1591 unsafe { ffi::ts_tree_cursor_current_node(&raw const self.0) },
1592 PhantomData,
1593 )
1594 }
1595
1596 #[doc(alias = "ts_tree_cursor_current_field_id")]
1600 #[must_use]
1601 pub fn field_id(&self) -> Option<FieldId> {
1602 let id = unsafe { ffi::ts_tree_cursor_current_field_id(&raw const self.0) };
1603 FieldId::new(id)
1604 }
1605
1606 #[doc(alias = "ts_tree_cursor_current_field_name")]
1608 #[must_use]
1609 pub fn field_name(&self) -> Option<&'tree str> {
1610 unsafe {
1611 let ptr = ffi::ts_tree_cursor_current_field_name(&raw const self.0);
1612 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1613 }
1614 }
1615
1616 #[doc(alias = "ts_tree_cursor_current_depth")]
1619 #[must_use]
1620 pub fn depth(&self) -> u32 {
1621 unsafe { ffi::ts_tree_cursor_current_depth(&raw const self.0) }
1622 }
1623
1624 #[doc(alias = "ts_tree_cursor_current_descendant_index")]
1627 #[must_use]
1628 pub fn descendant_index(&self) -> usize {
1629 unsafe { ffi::ts_tree_cursor_current_descendant_index(&raw const self.0) as usize }
1630 }
1631
1632 #[doc(alias = "ts_tree_cursor_goto_first_child")]
1637 pub fn goto_first_child(&mut self) -> bool {
1638 unsafe { ffi::ts_tree_cursor_goto_first_child(&raw mut self.0) }
1639 }
1640
1641 #[doc(alias = "ts_tree_cursor_goto_last_child")]
1650 pub fn goto_last_child(&mut self) -> bool {
1651 unsafe { ffi::ts_tree_cursor_goto_last_child(&raw mut self.0) }
1652 }
1653
1654 #[doc(alias = "ts_tree_cursor_goto_parent")]
1663 pub fn goto_parent(&mut self) -> bool {
1664 unsafe { ffi::ts_tree_cursor_goto_parent(&raw mut self.0) }
1665 }
1666
1667 #[doc(alias = "ts_tree_cursor_goto_next_sibling")]
1675 pub fn goto_next_sibling(&mut self) -> bool {
1676 unsafe { ffi::ts_tree_cursor_goto_next_sibling(&raw mut self.0) }
1677 }
1678
1679 #[doc(alias = "ts_tree_cursor_goto_descendant")]
1683 pub fn goto_descendant(&mut self, descendant_index: usize) {
1684 unsafe { ffi::ts_tree_cursor_goto_descendant(&raw mut self.0, descendant_index as u32) }
1685 }
1686
1687 #[doc(alias = "ts_tree_cursor_goto_previous_sibling")]
1699 pub fn goto_previous_sibling(&mut self) -> bool {
1700 unsafe { ffi::ts_tree_cursor_goto_previous_sibling(&raw mut self.0) }
1701 }
1702
1703 #[doc(alias = "ts_tree_cursor_goto_first_child_for_byte")]
1709 pub fn goto_first_child_for_byte(&mut self, index: usize) -> Option<usize> {
1710 let result =
1711 unsafe { ffi::ts_tree_cursor_goto_first_child_for_byte(&raw mut self.0, index as u32) };
1712 result.try_into().ok()
1713 }
1714
1715 #[doc(alias = "ts_tree_cursor_goto_first_child_for_point")]
1721 pub fn goto_first_child_for_point(&mut self, point: Point) -> Option<usize> {
1722 let result = unsafe {
1723 ffi::ts_tree_cursor_goto_first_child_for_point(&raw mut self.0, point.into())
1724 };
1725 result.try_into().ok()
1726 }
1727
1728 #[doc(alias = "ts_tree_cursor_reset")]
1731 pub fn reset(&mut self, node: Node<'tree>) {
1732 unsafe { ffi::ts_tree_cursor_reset(&raw mut self.0, node.0) };
1733 }
1734
1735 #[doc(alias = "ts_tree_cursor_reset_to")]
1740 pub fn reset_to(&mut self, cursor: &Self) {
1741 unsafe { ffi::ts_tree_cursor_reset_to(&raw mut self.0, &raw const cursor.0) };
1742 }
1743}
1744
1745impl Clone for TreeCursor<'_> {
1746 fn clone(&self) -> Self {
1747 TreeCursor(
1748 unsafe { ffi::ts_tree_cursor_copy(&raw const self.0) },
1749 PhantomData,
1750 )
1751 }
1752}
1753
1754impl Drop for TreeCursor<'_> {
1755 fn drop(&mut self) {
1756 unsafe { ffi::ts_tree_cursor_delete(&raw mut self.0) }
1757 }
1758}
1759
1760impl Point {
1761 #[must_use]
1762 pub const fn new(row: usize, column: usize) -> Self {
1763 Self { row, column }
1764 }
1765}
1766
1767impl fmt::Display for Point {
1768 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1769 write!(f, "({}, {})", self.row, self.column)
1770 }
1771}
1772
1773impl From<Point> for ffi::TSPoint {
1774 fn from(val: Point) -> Self {
1775 Self {
1776 row: val.row as u32,
1777 column: val.column as u32,
1778 }
1779 }
1780}
1781
1782impl From<ffi::TSPoint> for Point {
1783 fn from(point: ffi::TSPoint) -> Self {
1784 Self {
1785 row: point.row as usize,
1786 column: point.column as usize,
1787 }
1788 }
1789}
1790
1791impl From<Range> for ffi::TSRange {
1792 fn from(val: Range) -> Self {
1793 Self {
1794 start_byte: val.start_byte as u32,
1795 end_byte: val.end_byte as u32,
1796 start_point: val.start_point.into(),
1797 end_point: val.end_point.into(),
1798 }
1799 }
1800}
1801
1802impl From<ffi::TSRange> for Range {
1803 fn from(range: ffi::TSRange) -> Self {
1804 Self {
1805 start_byte: range.start_byte as usize,
1806 end_byte: range.end_byte as usize,
1807 start_point: range.start_point.into(),
1808 end_point: range.end_point.into(),
1809 }
1810 }
1811}
1812
1813impl fmt::Display for IncludedRangesError {
1814 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1815 write!(f, "Incorrect range by index: {}", self.0)
1816 }
1817}
1818
1819impl fmt::Display for LanguageError {
1820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1821 match self {
1822 Self::Version(version) => {
1823 write!(
1824 f,
1825 "Incompatible language version {version:#x}. Expected {MIN_COMPATIBLE_LANGUAGE_VERSION:#x} to {LANGUAGE_VERSION:#x}",
1826 )
1827 }
1828 Self::NotParseable => {
1829 write!(f, "Language cannot be used for parsing.")
1830 }
1831 #[cfg(feature = "wasm")]
1832 Self::Wasm => {
1833 write!(f, "Failed to load the Wasm store.")
1834 }
1835 }
1836 }
1837}
1838
1839pub fn wasm_stdlib_symbols() -> impl Iterator<Item = &'static str> {
1840 const WASM_STDLIB_SYMBOLS: &str = include_str!(concat!(env!("OUT_DIR"), "/stdlib-symbols.txt"));
1841
1842 WASM_STDLIB_SYMBOLS
1843 .lines()
1844 .map(|s| s.trim_matches(|c| c == '"' || c == ','))
1845}
1846
1847unsafe extern "C" {
1848 #[link_name = "wb_ts_node_string_pretty"]
1849 fn ts_node_string_pretty(node: ffi::TSNode, initial_indent_level: usize) -> *mut c_char;
1850 #[link_name = "wb_ts_current_free"]
1851 static mut ts_current_free: unsafe extern "C" fn(ptr: *mut c_void);
1852}
1853
1854#[inline]
1857unsafe fn ts_free(ptr: *mut c_void) {
1858 let f = unsafe { core::ptr::addr_of!(ts_current_free).read() };
1859 unsafe { f(ptr) };
1860}
1861
1862#[derive(Copy, Clone)]
1864pub struct Allocator {
1865 pub malloc: unsafe extern "C" fn(size: usize) -> *mut c_void,
1866 pub calloc: unsafe extern "C" fn(nmemb: usize, size: usize) -> *mut c_void,
1867 pub realloc: unsafe extern "C" fn(ptr: *mut c_void, size: usize) -> *mut c_void,
1868 pub free: unsafe extern "C" fn(ptr: *mut c_void),
1869}
1870
1871#[doc(alias = "ts_set_allocator")]
1890pub unsafe fn set_allocator(allocator: Option<Allocator>) {
1891 let (m, c, r, f) = match allocator {
1892 Some(a) => (
1893 Some(a.malloc),
1894 Some(a.calloc),
1895 Some(a.realloc),
1896 Some(a.free),
1897 ),
1898 None => (None, None, None, None),
1899 };
1900 unsafe { ffi::ts_set_allocator(m, c, r, f) };
1901}
1902
1903#[cfg(feature = "std")]
1904#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1905impl error::Error for IncludedRangesError {}
1906#[cfg(feature = "std")]
1907#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1908impl error::Error for LanguageError {}
1909
1910#[cfg(not(target_family = "wasm"))]
1911unsafe impl Send for Language {}
1912#[cfg(not(target_family = "wasm"))]
1913unsafe impl Sync for Language {}
1914
1915unsafe impl Send for Node<'_> {}
1916unsafe impl Sync for Node<'_> {}
1917
1918#[cfg(not(target_family = "wasm"))]
1919unsafe impl Send for Parser {}
1920#[cfg(not(target_family = "wasm"))]
1921unsafe impl Sync for Parser {}
1922
1923unsafe impl Send for Tree {}
1924unsafe impl Sync for Tree {}
1925
1926unsafe impl Send for TreeCursor<'_> {}
1927unsafe impl Sync for TreeCursor<'_> {}