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")]
58pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
59
60#[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")]
243 #[must_use]
244 pub fn is_parseable(&self) -> bool {
245 unsafe { ffi::ts_language_is_parseable(self.0) }
246 }
247
248 #[doc(alias = "ts_language_name")]
251 #[must_use]
252 pub fn name(&self) -> Option<&str> {
253 let ptr = unsafe { ffi::ts_language_name(self.0) };
254 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
255 }
256
257 #[doc(alias = "ts_language_abi_version")]
264 #[must_use]
265 pub fn abi_version(&self) -> usize {
266 unsafe { ffi::ts_language_abi_version(self.0) as usize }
267 }
268
269 #[doc(alias = "ts_language_metadata")]
276 #[must_use]
277 pub fn metadata(&self) -> Option<LanguageMetadata> {
278 unsafe {
279 let ptr = ffi::ts_language_metadata(self.0);
280 (!ptr.is_null()).then(|| (*ptr).into())
281 }
282 }
283
284 #[doc(alias = "ts_language_symbol_count")]
286 #[must_use]
287 pub fn node_kind_count(&self) -> usize {
288 unsafe { ffi::ts_language_symbol_count(self.0) as usize }
289 }
290
291 #[doc(alias = "ts_language_state_count")]
293 #[must_use]
294 pub fn parse_state_count(&self) -> usize {
295 unsafe { ffi::ts_language_state_count(self.0) as usize }
296 }
297
298 #[doc(alias = "ts_language_supertypes")]
301 #[must_use]
302 pub fn supertypes(&self) -> &[u16] {
303 let mut length = 0u32;
304 unsafe {
305 let ptr = ffi::ts_language_supertypes(self.0, core::ptr::addr_of_mut!(length));
306 if length == 0 {
307 &[]
308 } else {
309 slice::from_raw_parts(ptr.cast_mut(), length as usize)
310 }
311 }
312 }
313
314 #[doc(alias = "ts_language_supertype_map")]
317 #[must_use]
318 pub fn subtypes_for_supertype(&self, supertype: u16) -> &[u16] {
319 unsafe {
320 let mut length = 0u32;
321 let ptr = ffi::ts_language_subtypes(self.0, supertype, core::ptr::addr_of_mut!(length));
322 if length == 0 {
323 &[]
324 } else {
325 slice::from_raw_parts(ptr.cast_mut(), length as usize)
326 }
327 }
328 }
329
330 #[doc(alias = "ts_language_symbol_name")]
332 #[must_use]
333 pub fn node_kind_for_id(&self, id: u16) -> Option<&str> {
334 let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
335 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
336 }
337
338 #[doc(alias = "ts_language_symbol_for_name")]
340 #[must_use]
341 pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
342 unsafe {
343 ffi::ts_language_symbol_for_name(
344 self.0,
345 kind.as_bytes().as_ptr().cast::<c_char>(),
346 kind.len() as u32,
347 named,
348 )
349 }
350 }
351
352 fn node_kind_id_is_valid(&self, id: u16) -> bool {
359 (id as usize) < self.node_kind_count() || id >= u16::MAX - 1
360 }
361
362 #[must_use]
365 pub fn node_kind_is_named(&self, id: u16) -> bool {
366 self.node_kind_id_is_valid(id)
367 && unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeRegular }
368 }
369
370 #[must_use]
373 pub fn node_kind_is_visible(&self, id: u16) -> bool {
374 self.node_kind_id_is_valid(id)
375 && unsafe { ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolTypeAnonymous }
376 }
377
378 #[must_use]
380 pub fn node_kind_is_supertype(&self, id: u16) -> bool {
381 self.node_kind_id_is_valid(id)
382 && unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeSupertype }
383 }
384
385 #[doc(alias = "ts_language_field_count")]
387 #[must_use]
388 pub fn field_count(&self) -> usize {
389 unsafe { ffi::ts_language_field_count(self.0) as usize }
390 }
391
392 #[doc(alias = "ts_language_field_name_for_id")]
394 #[must_use]
395 pub fn field_name_for_id(&self, field_id: u16) -> Option<&str> {
396 let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
397 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
398 }
399
400 #[doc(alias = "ts_language_field_id_for_name")]
402 #[must_use]
403 pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId> {
404 let field_name = field_name.as_ref();
405 let id = unsafe {
406 ffi::ts_language_field_id_for_name(
407 self.0,
408 field_name.as_ptr().cast::<c_char>(),
409 field_name.len() as u32,
410 )
411 };
412 FieldId::new(id)
413 }
414}
415
416impl From<LanguageFn> for Language {
417 fn from(value: LanguageFn) -> Self {
418 Self::new(value)
419 }
420}
421
422impl Clone for Language {
423 fn clone(&self) -> Self {
424 unsafe { Self(ffi::ts_language_copy(self.0)) }
425 }
426}
427
428impl Drop for Language {
429 fn drop(&mut self) {
430 unsafe { ffi::ts_language_delete(self.0) }
431 }
432}
433
434impl Deref for LanguageRef<'_> {
435 type Target = Language;
436
437 fn deref(&self) -> &Self::Target {
438 unsafe { &*(core::ptr::addr_of!(self.0).cast::<Language>()) }
439 }
440}
441
442impl Default for Parser {
443 fn default() -> Self {
444 Self::new()
445 }
446}
447
448impl Parser {
449 #[doc(alias = "ts_parser_new")]
451 #[must_use]
452 pub fn new() -> Self {
453 unsafe {
454 let parser = ffi::ts_parser_new();
455 Self(NonNull::new_unchecked(parser))
456 }
457 }
458
459 #[doc(alias = "ts_parser_set_language")]
467 pub fn set_language(&mut self, language: &Language) -> Result<(), LanguageError> {
468 let version = language.abi_version();
469 if (MIN_COMPATIBLE_LANGUAGE_VERSION..=LANGUAGE_VERSION).contains(&version) {
470 if !language.is_parseable() {
471 return Err(LanguageError::NotParseable);
472 }
473 #[cfg_attr(
474 not(feature = "wasm"),
475 expect(unused_variables, reason = "only used when wasm feature is enabled")
476 )]
477 let success = unsafe { ffi::ts_parser_set_language(self.0.as_ptr(), language.0) };
478 #[cfg(feature = "wasm")]
479 if !success {
480 return Err(LanguageError::Wasm);
481 }
482 Ok(())
483 } else {
484 Err(LanguageError::Version(version))
485 }
486 }
487
488 #[doc(alias = "ts_parser_language")]
490 #[must_use]
491 pub fn language(&self) -> Option<LanguageRef<'_>> {
492 let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
493 (!ptr.is_null()).then_some(LanguageRef(ptr, PhantomData))
494 }
495
496 #[doc(alias = "ts_parser_logger")]
498 #[must_use]
499 pub fn logger(&self) -> Option<&Logger> {
500 let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
501 unsafe { logger.payload.cast::<Logger>().as_ref() }
502 }
503
504 #[doc(alias = "ts_parser_set_logger")]
509 pub fn set_logger(&mut self, logger: Option<Logger>) {
510 unsafe { self.set_logger_unchecked(logger) };
512 }
513
514 pub unsafe fn set_logger_unchecked(&mut self, logger: Option<UnsafeLogger<'_>>) {
523 let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
524 if !prev_logger.payload.is_null() {
525 drop(unsafe { Box::from_raw(prev_logger.payload.cast::<Logger>()) });
526 }
527
528 let c_logger = if let Some(logger) = logger {
529 let container = Box::new(logger);
530
531 unsafe extern "C" fn log(
532 payload: *mut c_void,
533 c_log_type: ffi::TSLogType,
534 c_message: *const c_char,
535 ) {
536 unsafe {
537 let callback = payload.cast::<Logger>().as_mut().unwrap();
538 if let Ok(message) = CStr::from_ptr(c_message).to_str() {
539 let log_type = if c_log_type == ffi::TSLogTypeParse {
540 LogType::Parse
541 } else {
542 LogType::Lex
543 };
544 callback(log_type, message);
545 }
546 }
547 }
548
549 let raw_container = Box::into_raw(container);
550
551 ffi::TSLogger {
552 payload: raw_container.cast::<c_void>(),
553 log: Some(log),
554 }
555 } else {
556 ffi::TSLogger {
557 payload: ptr::null_mut(),
558 log: None,
559 }
560 };
561
562 unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
563 }
564
565 #[doc(alias = "ts_parser_print_dot_graphs")]
570 #[cfg(not(target_os = "wasi"))]
571 #[cfg(feature = "std")]
572 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
573 pub fn print_dot_graphs(
574 &mut self,
575 #[cfg(unix)] file: &impl AsRawFd,
576 #[cfg(windows)] file: &impl AsRawHandle,
577 ) {
578 #[cfg(unix)]
579 {
580 let fd = file.as_raw_fd();
581 unsafe {
582 ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(fd));
583 }
584 }
585
586 #[cfg(windows)]
587 {
588 let handle = file.as_raw_handle();
589 unsafe {
590 ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(handle));
591 }
592 }
593 }
594
595 #[doc(alias = "ts_parser_print_dot_graphs")]
597 #[cfg(not(target_os = "wasi"))]
598 #[cfg(feature = "std")]
599 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
600 pub fn stop_printing_dot_graphs(&mut self) {
601 unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
602 }
603
604 #[doc(alias = "ts_parser_parse")]
612 pub fn parse(&mut self, text: impl AsRef<[u8]>) -> Option<Tree> {
613 let bytes = text.as_ref();
614 if let Ok(len) = u32::try_from(bytes.len()) {
615 return unsafe {
616 self.parse_raw_bytes(
617 (bytes.as_ptr().cast::<c_char>(), len),
618 ffi::TSInputEncodingUTF8,
619 )
620 };
621 }
622 let len = bytes.len();
623 self.parse_with_options(
624 &mut |i, _| {
625 if i < len {
626 &bytes[i..]
627 } else {
628 Default::default()
629 }
630 },
631 None,
632 )
633 }
634
635 pub fn parse_with_options<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
644 &mut self,
645 callback: &mut F,
646 options: Option<ParseOptions>,
647 ) -> Option<Tree> {
648 self.parse_chunks::<0, u8, T, F>(callback, (options, ffi::TSInputEncodingUTF8, None))
649 }
650
651 pub fn parse_utf16_le(&mut self, input: impl AsRef<[u16]>) -> Option<Tree> {
656 self.parse_utf16_slice::<true>(input.as_ref())
657 }
658
659 pub fn parse_utf16_le_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
668 &mut self,
669 callback: &mut F,
670 options: Option<ParseOptions>,
671 ) -> Option<Tree> {
672 self.parse_utf16_with_options::<true, T, F>(callback, options)
673 }
674
675 pub fn parse_utf16_be(&mut self, input: impl AsRef<[u16]>) -> Option<Tree> {
680 self.parse_utf16_slice::<false>(input.as_ref())
681 }
682
683 pub fn parse_utf16_be_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
692 &mut self,
693 callback: &mut F,
694 options: Option<ParseOptions>,
695 ) -> Option<Tree> {
696 self.parse_utf16_with_options::<false, T, F>(callback, options)
697 }
698
699 pub fn parse_custom_encoding<D: Decode, T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
713 &mut self,
714 callback: &mut F,
715 options: Option<ParseOptions>,
716 ) -> Option<Tree> {
717 unsafe extern "C" fn decode_fn<D: Decode>(
718 data: *const u8,
719 len: u32,
720 code_point: *mut i32,
721 ) -> u32 {
722 unsafe {
723 let (c, len) = D::decode(core::slice::from_raw_parts(data, len as usize));
724 if let Some(code_point) = code_point.as_mut() {
725 *code_point = c;
726 }
727 len
728 }
729 }
730
731 self.parse_chunks::<0, u8, T, F>(
732 callback,
733 (options, ffi::TSInputEncodingCustom, Some(decode_fn::<D>)),
734 )
735 }
736
737 fn parse_utf16_slice<const LE: bool>(&mut self, code_points: &[u16]) -> Option<Tree> {
738 let encoding = if LE {
739 ffi::TSInputEncodingUTF16LE
740 } else {
741 ffi::TSInputEncodingUTF16BE
742 };
743 if let Some(byte_len) = code_points
744 .len()
745 .checked_mul(2)
746 .and_then(|n| u32::try_from(n).ok())
747 {
748 return unsafe {
749 self.parse_raw_bytes((code_points.as_ptr().cast::<c_char>(), byte_len), encoding)
750 };
751 }
752 let len = code_points.len();
753 self.parse_utf16_with_options::<LE, _, _>(
754 &mut |i, _| if i < len { &code_points[i..] } else { &[] },
755 None,
756 )
757 }
758
759 fn parse_utf16_with_options<const LE: bool, T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
760 &mut self,
761 callback: &mut F,
762 options: Option<ParseOptions>,
763 ) -> Option<Tree> {
764 let encoding = if LE {
765 ffi::TSInputEncodingUTF16LE
766 } else {
767 ffi::TSInputEncodingUTF16BE
768 };
769 self.parse_chunks::<1, u16, T, F>(callback, (options, encoding, None))
770 }
771
772 fn parse_chunks<const UNIT_SHIFT: u32, U, T: AsRef<[U]>, F: FnMut(usize, Point) -> T>(
773 &mut self,
774 callback: &mut F,
775 (options, encoding, decode): (
776 Option<ParseOptions>,
777 ffi::TSInputEncoding,
778 ffi::TSDecodeFunction,
779 ),
780 ) -> Option<Tree> {
781 type Payload<'a, F, T> = (&'a mut F, Option<T>);
782
783 unsafe extern "C" fn read<
784 const UNIT_SHIFT: u32,
785 U,
786 T: AsRef<[U]>,
787 F: FnMut(usize, Point) -> T,
788 >(
789 payload: *mut c_void,
790 byte_offset: u32,
791 position: ffi::TSPoint,
792 bytes_read: *mut u32,
793 ) -> *const c_char {
794 unsafe {
795 let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
796 *text = Some(callback(
797 (byte_offset as usize) >> UNIT_SHIFT,
798 Point {
799 row: position.row as usize,
800 column: (position.column as usize) >> UNIT_SHIFT,
801 },
802 ));
803 let slice = text.as_ref().unwrap().as_ref();
804 *bytes_read =
805 (slice.len().min((u32::MAX as usize) >> UNIT_SHIFT) << UNIT_SHIFT) as u32;
806 slice.as_ptr().cast::<c_char>()
807 }
808 }
809
810 let mut payload: Payload<F, T> = (callback, None);
812 let c_input = ffi::TSInput {
813 payload: ptr::addr_of_mut!(payload).cast::<c_void>(),
814 read: Some(read::<UNIT_SHIFT, U, T, F>),
815 encoding,
816 decode,
817 };
818 unsafe { self.parse_c_input(c_input, options) }
819 }
820
821 unsafe fn parse_raw_bytes(
822 &mut self,
823 (bytes, byte_len): (*const c_char, u32),
824 encoding: ffi::TSInputEncoding,
825 ) -> Option<Tree> {
826 let c_new_tree = unsafe {
827 ffi::ts_parser_parse_string_encoding(self.0.as_ptr(), bytes, byte_len, encoding)
828 };
829 NonNull::new(c_new_tree).map(Tree)
830 }
831
832 unsafe fn parse_c_input(
833 &mut self,
834 c_input: ffi::TSInput,
835 options: Option<ParseOptions>,
836 ) -> Option<Tree> {
837 unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
838 unsafe {
839 let callback = (*state)
840 .payload
841 .cast::<ParseProgressCallback>()
842 .as_mut()
843 .unwrap();
844 match callback(&ParseState::from_raw(state)) {
845 ControlFlow::Continue(()) => false,
846 ControlFlow::Break(()) => true,
847 }
848 }
849 }
850
851 let mut callback_ptr;
852 let parse_options = if let Some(cb) = options.and_then(|o| o.progress_callback) {
853 callback_ptr = cb;
854 ffi::TSParseOptions {
855 payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
856 progress_callback: Some(progress),
857 }
858 } else {
859 ffi::TSParseOptions {
860 payload: ptr::null_mut(),
861 progress_callback: None,
862 }
863 };
864
865 let c_new_tree =
866 unsafe { ffi::ts_parser_parse_with_options(self.0.as_ptr(), c_input, parse_options) };
867 NonNull::new(c_new_tree).map(Tree)
868 }
869
870 #[doc(alias = "ts_parser_reset")]
877 pub fn reset(&mut self) {
878 unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
879 }
880
881 #[doc(alias = "ts_parser_set_included_ranges")]
899 pub fn set_included_ranges(&mut self, ranges: &[Range]) -> Result<(), IncludedRangesError> {
900 let ts_ranges = ranges.iter().copied().map(Into::into).collect::<Vec<_>>();
901 let result = unsafe {
902 ffi::ts_parser_set_included_ranges(
903 self.0.as_ptr(),
904 ts_ranges.as_ptr(),
905 ts_ranges.len() as u32,
906 )
907 };
908
909 if result {
910 Ok(())
911 } else {
912 let mut prev_end_byte = 0;
913 for (i, range) in ranges.iter().enumerate() {
914 if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
915 return Err(IncludedRangesError(i));
916 }
917 prev_end_byte = range.end_byte;
918 }
919 Err(IncludedRangesError(0))
920 }
921 }
922
923 #[doc(alias = "ts_parser_included_ranges")]
925 #[must_use]
926 pub fn included_ranges(&self) -> Vec<Range> {
927 let mut count = 0u32;
928 unsafe {
929 let ptr =
930 ffi::ts_parser_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
931 let ranges = slice::from_raw_parts(ptr, count as usize);
932 ranges.iter().copied().map(Into::into).collect()
933 }
934 }
935}
936
937impl Drop for Parser {
938 fn drop(&mut self) {
939 #[cfg(feature = "std")]
940 #[cfg(not(target_os = "wasi"))]
941 {
942 self.stop_printing_dot_graphs();
943 }
944 self.set_logger(None);
945 unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
946 }
947}
948
949#[cfg(windows)]
950unsafe extern "C" {
951 fn _open_osfhandle(osfhandle: isize, flags: core::ffi::c_int) -> core::ffi::c_int;
952}
953
954impl Tree {
955 #[doc(alias = "ts_tree_root_node")]
957 #[must_use]
958 pub fn root_node(&self) -> Node {
959 Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
960 }
961
962 #[doc(alias = "ts_tree_root_node_with_offset")]
965 #[must_use]
966 pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
967 Node::new(unsafe {
968 ffi::ts_tree_root_node_with_offset(
969 self.0.as_ptr(),
970 offset_bytes as u32,
971 offset_extent.into(),
972 )
973 })
974 .unwrap()
975 }
976
977 #[doc(alias = "ts_tree_language")]
984 #[must_use]
985 pub fn language(&self) -> LanguageRef {
986 LanguageRef(
987 unsafe { ffi::ts_tree_language(self.0.as_ptr()) },
988 PhantomData,
989 )
990 }
991
992 #[must_use]
994 pub fn walk(&self) -> TreeCursor {
995 self.root_node().walk()
996 }
997
998 #[doc(alias = "ts_tree_included_ranges")]
1000 #[must_use]
1001 pub fn included_ranges(&self) -> Vec<Range> {
1002 let mut count = 0u32;
1003 unsafe {
1004 let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
1005 let ranges = slice::from_raw_parts(ptr, count as usize);
1006 let result = ranges.iter().copied().map(Into::into).collect();
1007 ts_free(ptr.cast::<c_void>());
1008 result
1009 }
1010 }
1011
1012 #[doc(alias = "ts_tree_print_dot_graph")]
1017 #[cfg(not(target_os = "wasi"))]
1018 #[cfg(feature = "std")]
1019 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1020 pub fn print_dot_graph(
1021 &self,
1022 #[cfg(unix)] file: &impl AsRawFd,
1023 #[cfg(windows)] file: &impl AsRawHandle,
1024 ) {
1025 #[cfg(unix)]
1026 {
1027 let fd = file.as_raw_fd();
1028 unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1029 }
1030
1031 #[cfg(windows)]
1032 {
1033 let handle = file.as_raw_handle();
1034 let fd = unsafe { _open_osfhandle(handle as isize, 0) };
1035 unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1036 }
1037 }
1038}
1039
1040impl fmt::Debug for Tree {
1041 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1042 write!(f, "{{Tree {:?}}}", self.root_node())
1043 }
1044}
1045
1046impl Drop for Tree {
1047 fn drop(&mut self) {
1048 unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
1049 }
1050}
1051
1052impl Clone for Tree {
1053 fn clone(&self) -> Self {
1054 unsafe { Self(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
1055 }
1056}
1057
1058impl<'tree> Node<'tree> {
1059 fn new(node: ffi::TSNode) -> Option<Self> {
1060 (!node.id.is_null()).then_some(Node(node, PhantomData))
1061 }
1062
1063 #[must_use]
1065 pub fn id(&self) -> usize {
1066 self.0.id as usize
1067 }
1068
1069 #[doc(alias = "ts_node_symbol")]
1071 #[must_use]
1072 pub fn kind_id(&self) -> u16 {
1073 unsafe { ffi::ts_node_symbol(self.0) }
1074 }
1075
1076 #[doc(alias = "ts_node_grammar_symbol")]
1079 #[must_use]
1080 pub fn grammar_id(&self) -> u16 {
1081 unsafe { ffi::ts_node_grammar_symbol(self.0) }
1082 }
1083
1084 #[doc(alias = "ts_node_type")]
1086 #[must_use]
1087 pub fn kind(&self) -> &'tree str {
1088 let ptr = unsafe { ffi::ts_node_type(self.0) };
1089 assert!(!ptr.is_null());
1090 unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
1091 }
1092
1093 #[doc(alias = "ts_node_grammar_type")]
1096 #[must_use]
1097 pub fn grammar_name(&self) -> &'tree str {
1098 let ptr = unsafe { ffi::ts_node_grammar_type(self.0) };
1099 assert!(!ptr.is_null());
1100 unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
1101 }
1102
1103 #[doc(alias = "ts_node_language")]
1111 #[must_use]
1112 pub fn language(&self) -> LanguageRef<'tree> {
1113 LanguageRef(unsafe { ffi::ts_node_language(self.0) }, PhantomData)
1114 }
1115
1116 #[doc(alias = "ts_node_is_named")]
1121 #[must_use]
1122 pub fn is_named(&self) -> bool {
1123 unsafe { ffi::ts_node_is_named(self.0) }
1124 }
1125
1126 #[doc(alias = "ts_node_is_extra")]
1131 #[must_use]
1132 pub fn is_extra(&self) -> bool {
1133 unsafe { ffi::ts_node_is_extra(self.0) }
1134 }
1135
1136 #[doc(alias = "ts_node_has_error")]
1139 #[must_use]
1140 pub fn has_error(&self) -> bool {
1141 unsafe { ffi::ts_node_has_error(self.0) }
1142 }
1143
1144 #[doc(alias = "ts_node_is_error")]
1149 #[must_use]
1150 pub fn is_error(&self) -> bool {
1151 unsafe { ffi::ts_node_is_error(self.0) }
1152 }
1153
1154 #[doc(alias = "ts_node_is_missing")]
1159 #[must_use]
1160 pub fn is_missing(&self) -> bool {
1161 unsafe { ffi::ts_node_is_missing(self.0) }
1162 }
1163
1164 #[doc(alias = "ts_node_start_byte")]
1166 #[inline]
1167 #[must_use]
1168 pub const fn start_byte(&self) -> usize {
1169 self.0.context[0] as usize
1170 }
1171
1172 #[doc(alias = "ts_node_end_byte")]
1174 #[must_use]
1175 pub fn end_byte(&self) -> usize {
1176 unsafe { ffi::ts_node_end_byte(self.0) as usize }
1177 }
1178
1179 #[inline]
1181 #[must_use]
1182 pub fn byte_range(&self) -> core::ops::Range<usize> {
1183 self.start_byte()..self.end_byte()
1184 }
1185
1186 #[must_use]
1189 pub fn range(&self) -> Range {
1190 Range {
1191 start_byte: self.start_byte(),
1192 end_byte: self.end_byte(),
1193 start_point: self.start_position(),
1194 end_point: self.end_position(),
1195 }
1196 }
1197
1198 #[doc(alias = "ts_node_start_point")]
1200 #[inline]
1201 #[must_use]
1202 pub const fn start_position(&self) -> Point {
1203 Point {
1204 row: self.0.context[1] as usize,
1205 column: self.0.context[2] as usize,
1206 }
1207 }
1208
1209 #[doc(alias = "ts_node_end_point")]
1211 #[must_use]
1212 pub fn end_position(&self) -> Point {
1213 let result = unsafe { ffi::ts_node_end_point(self.0) };
1214 result.into()
1215 }
1216
1217 #[doc(alias = "ts_node_child")]
1224 #[must_use]
1225 pub fn child(&self, i: u32) -> Option<Self> {
1226 Self::new(unsafe { ffi::ts_node_child(self.0, i) })
1227 }
1228
1229 #[doc(alias = "ts_node_child_count")]
1231 #[must_use]
1232 pub fn child_count(&self) -> u32 {
1233 unsafe { ffi::ts_node_child_count(self.0) }
1234 }
1235
1236 #[doc(alias = "ts_node_named_child")]
1243 #[must_use]
1244 pub fn named_child(&self, i: u32) -> Option<Self> {
1245 Self::new(unsafe { ffi::ts_node_named_child(self.0, i) })
1246 }
1247
1248 #[doc(alias = "ts_node_named_child_count")]
1252 #[must_use]
1253 pub fn named_child_count(&self) -> usize {
1254 unsafe { ffi::ts_node_named_child_count(self.0) as usize }
1255 }
1256
1257 #[doc(alias = "ts_node_child_by_field_name")]
1262 #[must_use]
1263 pub fn child_by_field_name(&self, field_name: impl AsRef<[u8]>) -> Option<Self> {
1264 let field_name = field_name.as_ref();
1265 Self::new(unsafe {
1266 ffi::ts_node_child_by_field_name(
1267 self.0,
1268 field_name.as_ptr().cast::<c_char>(),
1269 field_name.len() as u32,
1270 )
1271 })
1272 }
1273
1274 #[doc(alias = "ts_node_child_by_field_id")]
1279 #[must_use]
1280 pub fn child_by_field_id(&self, field_id: u16) -> Option<Self> {
1281 Self::new(unsafe { ffi::ts_node_child_by_field_id(self.0, field_id) })
1282 }
1283
1284 #[doc(alias = "ts_node_field_name_for_child")]
1286 #[must_use]
1287 pub fn field_name_for_child(&self, child_index: u32) -> Option<&'tree str> {
1288 unsafe {
1289 let ptr = ffi::ts_node_field_name_for_child(self.0, child_index);
1290 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1291 }
1292 }
1293
1294 #[must_use]
1296 pub fn field_name_for_named_child(&self, named_child_index: u32) -> Option<&'tree str> {
1297 unsafe {
1298 let ptr = ffi::ts_node_field_name_for_named_child(self.0, named_child_index);
1299 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1300 }
1301 }
1302
1303 pub fn children<'cursor>(
1313 &self,
1314 cursor: &'cursor mut TreeCursor<'tree>,
1315 ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1316 cursor.reset(*self);
1317 cursor.goto_first_child();
1318 (0..self.child_count()).map(move |_| {
1319 let result = cursor.node();
1320 cursor.goto_next_sibling();
1321 result
1322 })
1323 }
1324
1325 pub fn named_children<'cursor>(
1329 &self,
1330 cursor: &'cursor mut TreeCursor<'tree>,
1331 ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1332 cursor.reset(*self);
1333 cursor.goto_first_child();
1334 (0..self.named_child_count()).map(move |_| {
1335 while !cursor.node().is_named() {
1336 if !cursor.goto_next_sibling() {
1337 break;
1338 }
1339 }
1340 let result = cursor.node();
1341 cursor.goto_next_sibling();
1342 result
1343 })
1344 }
1345
1346 pub fn children_by_field_name<'cursor>(
1350 &self,
1351 field_name: &str,
1352 cursor: &'cursor mut TreeCursor<'tree>,
1353 ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1354 let field_id = self.language().field_id_for_name(field_name);
1355 let mut done = field_id.is_none();
1356 if !done {
1357 cursor.reset(*self);
1358 cursor.goto_first_child();
1359 }
1360 iter::from_fn(move || {
1361 if !done {
1362 while cursor.field_id() != field_id {
1363 if !cursor.goto_next_sibling() {
1364 return None;
1365 }
1366 }
1367 let result = cursor.node();
1368 if !cursor.goto_next_sibling() {
1369 done = true;
1370 }
1371 return Some(result);
1372 }
1373 None
1374 })
1375 }
1376
1377 pub fn children_by_field_id<'cursor>(
1381 &self,
1382 field_id: FieldId,
1383 cursor: &'cursor mut TreeCursor<'tree>,
1384 ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1385 cursor.reset(*self);
1386 cursor.goto_first_child();
1387 let mut done = false;
1388 iter::from_fn(move || {
1389 if !done {
1390 while cursor.field_id() != Some(field_id) {
1391 if !cursor.goto_next_sibling() {
1392 return None;
1393 }
1394 }
1395 let result = cursor.node();
1396 if !cursor.goto_next_sibling() {
1397 done = true;
1398 }
1399 return Some(result);
1400 }
1401 None
1402 })
1403 }
1404
1405 #[doc(alias = "ts_node_parent")]
1409 #[must_use]
1410 pub fn parent(&self) -> Option<Self> {
1411 Self::new(unsafe { ffi::ts_node_parent(self.0) })
1412 }
1413
1414 #[doc(alias = "ts_node_child_with_descendant")]
1418 #[must_use]
1419 pub fn child_with_descendant(&self, descendant: Self) -> Option<Self> {
1420 Self::new(unsafe { ffi::ts_node_child_with_descendant(self.0, descendant.0) })
1421 }
1422
1423 #[doc(alias = "ts_node_next_sibling")]
1425 #[must_use]
1426 pub fn next_sibling(&self) -> Option<Self> {
1427 Self::new(unsafe { ffi::ts_node_next_sibling(self.0) })
1428 }
1429
1430 #[doc(alias = "ts_node_prev_sibling")]
1432 #[must_use]
1433 pub fn prev_sibling(&self) -> Option<Self> {
1434 Self::new(unsafe { ffi::ts_node_prev_sibling(self.0) })
1435 }
1436
1437 #[doc(alias = "ts_node_next_named_sibling")]
1439 #[must_use]
1440 pub fn next_named_sibling(&self) -> Option<Self> {
1441 Self::new(unsafe { ffi::ts_node_next_named_sibling(self.0) })
1442 }
1443
1444 #[doc(alias = "ts_node_prev_named_sibling")]
1446 #[must_use]
1447 pub fn prev_named_sibling(&self) -> Option<Self> {
1448 Self::new(unsafe { ffi::ts_node_prev_named_sibling(self.0) })
1449 }
1450
1451 #[doc(alias = "ts_node_first_child_for_byte")]
1453 #[must_use]
1454 pub fn first_child_for_byte(&self, byte: usize) -> Option<Self> {
1455 Self::new(unsafe { ffi::ts_node_first_child_for_byte(self.0, byte as u32) })
1456 }
1457
1458 #[doc(alias = "ts_node_first_named_child_for_point")]
1460 #[must_use]
1461 pub fn first_named_child_for_byte(&self, byte: usize) -> Option<Self> {
1462 Self::new(unsafe { ffi::ts_node_first_named_child_for_byte(self.0, byte as u32) })
1463 }
1464
1465 #[doc(alias = "ts_node_descendant_count")]
1467 #[must_use]
1468 pub fn descendant_count(&self) -> usize {
1469 unsafe { ffi::ts_node_descendant_count(self.0) as usize }
1470 }
1471
1472 #[doc(alias = "ts_node_descendant_for_byte_range")]
1474 #[must_use]
1475 pub fn descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
1476 Self::new(unsafe {
1477 ffi::ts_node_descendant_for_byte_range(self.0, start as u32, end as u32)
1478 })
1479 }
1480
1481 #[doc(alias = "ts_node_named_descendant_for_byte_range")]
1483 #[must_use]
1484 pub fn named_descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
1485 Self::new(unsafe {
1486 ffi::ts_node_named_descendant_for_byte_range(self.0, start as u32, end as u32)
1487 })
1488 }
1489
1490 #[doc(alias = "ts_node_descendant_for_point_range")]
1492 #[must_use]
1493 pub fn descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
1494 Self::new(unsafe {
1495 ffi::ts_node_descendant_for_point_range(self.0, start.into(), end.into())
1496 })
1497 }
1498
1499 #[doc(alias = "ts_node_named_descendant_for_point_range")]
1501 #[must_use]
1502 pub fn named_descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
1503 Self::new(unsafe {
1504 ffi::ts_node_named_descendant_for_point_range(self.0, start.into(), end.into())
1505 })
1506 }
1507
1508 #[doc(alias = "ts_node_string")]
1510 #[must_use]
1511 pub fn to_sexp(&self) -> String {
1512 let c_string = unsafe { ffi::ts_node_string(self.0) };
1513 let result = unsafe { CStr::from_ptr(c_string) }
1514 .to_str()
1515 .unwrap()
1516 .to_string();
1517 unsafe { ts_free(c_string.cast::<c_void>()) };
1518 result
1519 }
1520
1521 pub fn utf8_text<'a>(&self, source: &'a [u8]) -> Result<&'a str, str::Utf8Error> {
1522 str::from_utf8(&source[self.start_byte()..self.end_byte()])
1523 }
1524
1525 #[must_use]
1526 pub fn utf16_text<'a>(&self, source: &'a [u16]) -> &'a [u16] {
1527 &source[self.start_byte() / 2..self.end_byte() / 2]
1528 }
1529
1530 #[doc(alias = "ts_tree_cursor_new")]
1535 #[must_use]
1536 pub fn walk(&self) -> TreeCursor<'tree> {
1537 TreeCursor(unsafe { ffi::ts_tree_cursor_new(self.0) }, PhantomData)
1538 }
1539}
1540
1541impl PartialEq for Node<'_> {
1542 fn eq(&self, other: &Self) -> bool {
1543 core::ptr::eq(self.0.id, other.0.id)
1544 }
1545}
1546
1547impl Eq for Node<'_> {}
1548
1549impl hash::Hash for Node<'_> {
1550 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1551 self.0.id.hash(state);
1552 self.0.context[0].hash(state);
1553 self.0.context[1].hash(state);
1554 self.0.context[2].hash(state);
1555 self.0.context[3].hash(state);
1556 }
1557}
1558
1559impl fmt::Debug for Node<'_> {
1560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1561 write!(
1562 f,
1563 "{{Node {} {} - {}}}",
1564 self.kind(),
1565 self.start_position(),
1566 self.end_position()
1567 )
1568 }
1569}
1570
1571impl fmt::Display for Node<'_> {
1572 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1573 if !f.alternate() {
1574 return f.write_str(&self.to_sexp());
1575 }
1576 let c_string = unsafe { ts_node_string_pretty(self.0, f.width().unwrap_or(0)) };
1577 let result = unsafe { CStr::from_ptr(c_string) }
1578 .to_str()
1579 .unwrap()
1580 .to_string();
1581 unsafe { ts_free(c_string.cast::<c_void>()) };
1582 f.write_str(&result)
1583 }
1584}
1585
1586impl<'tree> TreeCursor<'tree> {
1587 #[doc(alias = "ts_tree_cursor_current_node")]
1589 #[must_use]
1590 pub fn node(&self) -> Node<'tree> {
1591 Node(
1592 unsafe { ffi::ts_tree_cursor_current_node(&raw const self.0) },
1593 PhantomData,
1594 )
1595 }
1596
1597 #[doc(alias = "ts_tree_cursor_current_field_id")]
1601 #[must_use]
1602 pub fn field_id(&self) -> Option<FieldId> {
1603 let id = unsafe { ffi::ts_tree_cursor_current_field_id(&raw const self.0) };
1604 FieldId::new(id)
1605 }
1606
1607 #[doc(alias = "ts_tree_cursor_current_field_name")]
1609 #[must_use]
1610 pub fn field_name(&self) -> Option<&'tree str> {
1611 unsafe {
1612 let ptr = ffi::ts_tree_cursor_current_field_name(&raw const self.0);
1613 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1614 }
1615 }
1616
1617 #[doc(alias = "ts_tree_cursor_current_depth")]
1620 #[must_use]
1621 pub fn depth(&self) -> u32 {
1622 unsafe { ffi::ts_tree_cursor_current_depth(&raw const self.0) }
1623 }
1624
1625 #[doc(alias = "ts_tree_cursor_current_descendant_index")]
1628 #[must_use]
1629 pub fn descendant_index(&self) -> usize {
1630 unsafe { ffi::ts_tree_cursor_current_descendant_index(&raw const self.0) as usize }
1631 }
1632
1633 #[doc(alias = "ts_tree_cursor_goto_first_child")]
1638 pub fn goto_first_child(&mut self) -> bool {
1639 unsafe { ffi::ts_tree_cursor_goto_first_child(&raw mut self.0) }
1640 }
1641
1642 #[doc(alias = "ts_tree_cursor_goto_last_child")]
1651 pub fn goto_last_child(&mut self) -> bool {
1652 unsafe { ffi::ts_tree_cursor_goto_last_child(&raw mut self.0) }
1653 }
1654
1655 #[doc(alias = "ts_tree_cursor_goto_parent")]
1664 pub fn goto_parent(&mut self) -> bool {
1665 unsafe { ffi::ts_tree_cursor_goto_parent(&raw mut self.0) }
1666 }
1667
1668 #[doc(alias = "ts_tree_cursor_goto_next_sibling")]
1676 pub fn goto_next_sibling(&mut self) -> bool {
1677 unsafe { ffi::ts_tree_cursor_goto_next_sibling(&raw mut self.0) }
1678 }
1679
1680 #[doc(alias = "ts_tree_cursor_goto_descendant")]
1684 pub fn goto_descendant(&mut self, descendant_index: usize) {
1685 unsafe { ffi::ts_tree_cursor_goto_descendant(&raw mut self.0, descendant_index as u32) }
1686 }
1687
1688 #[doc(alias = "ts_tree_cursor_goto_previous_sibling")]
1700 pub fn goto_previous_sibling(&mut self) -> bool {
1701 unsafe { ffi::ts_tree_cursor_goto_previous_sibling(&raw mut self.0) }
1702 }
1703
1704 #[doc(alias = "ts_tree_cursor_goto_first_child_for_byte")]
1710 pub fn goto_first_child_for_byte(&mut self, index: usize) -> Option<usize> {
1711 let result =
1712 unsafe { ffi::ts_tree_cursor_goto_first_child_for_byte(&raw mut self.0, index as u32) };
1713 result.try_into().ok()
1714 }
1715
1716 #[doc(alias = "ts_tree_cursor_goto_first_child_for_point")]
1722 pub fn goto_first_child_for_point(&mut self, point: Point) -> Option<usize> {
1723 let result = unsafe {
1724 ffi::ts_tree_cursor_goto_first_child_for_point(&raw mut self.0, point.into())
1725 };
1726 result.try_into().ok()
1727 }
1728
1729 #[doc(alias = "ts_tree_cursor_reset")]
1732 pub fn reset(&mut self, node: Node<'tree>) {
1733 unsafe { ffi::ts_tree_cursor_reset(&raw mut self.0, node.0) };
1734 }
1735
1736 #[doc(alias = "ts_tree_cursor_reset_to")]
1741 pub fn reset_to(&mut self, cursor: &Self) {
1742 unsafe { ffi::ts_tree_cursor_reset_to(&raw mut self.0, &raw const cursor.0) };
1743 }
1744}
1745
1746impl Clone for TreeCursor<'_> {
1747 fn clone(&self) -> Self {
1748 TreeCursor(
1749 unsafe { ffi::ts_tree_cursor_copy(&raw const self.0) },
1750 PhantomData,
1751 )
1752 }
1753}
1754
1755impl Drop for TreeCursor<'_> {
1756 fn drop(&mut self) {
1757 unsafe { ffi::ts_tree_cursor_delete(&raw mut self.0) }
1758 }
1759}
1760
1761impl Point {
1762 #[must_use]
1763 pub const fn new(row: usize, column: usize) -> Self {
1764 Self { row, column }
1765 }
1766}
1767
1768impl fmt::Display for Point {
1769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1770 write!(f, "({}, {})", self.row, self.column)
1771 }
1772}
1773
1774impl From<Point> for ffi::TSPoint {
1775 fn from(val: Point) -> Self {
1776 Self {
1777 row: val.row as u32,
1778 column: val.column as u32,
1779 }
1780 }
1781}
1782
1783impl From<ffi::TSPoint> for Point {
1784 fn from(point: ffi::TSPoint) -> Self {
1785 Self {
1786 row: point.row as usize,
1787 column: point.column as usize,
1788 }
1789 }
1790}
1791
1792impl From<Range> for ffi::TSRange {
1793 fn from(val: Range) -> Self {
1794 Self {
1795 start_byte: val.start_byte as u32,
1796 end_byte: val.end_byte as u32,
1797 start_point: val.start_point.into(),
1798 end_point: val.end_point.into(),
1799 }
1800 }
1801}
1802
1803impl From<ffi::TSRange> for Range {
1804 fn from(range: ffi::TSRange) -> Self {
1805 Self {
1806 start_byte: range.start_byte as usize,
1807 end_byte: range.end_byte as usize,
1808 start_point: range.start_point.into(),
1809 end_point: range.end_point.into(),
1810 }
1811 }
1812}
1813
1814impl fmt::Display for IncludedRangesError {
1815 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1816 write!(f, "Incorrect range by index: {}", self.0)
1817 }
1818}
1819
1820impl fmt::Display for LanguageError {
1821 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1822 match self {
1823 Self::Version(version) => {
1824 write!(
1825 f,
1826 "Incompatible language version {version:#x}. Expected {LANGUAGE_VERSION:#x}",
1827 )
1828 }
1829 Self::NotParseable => {
1830 write!(f, "Language cannot be used for parsing.")
1831 }
1832 #[cfg(feature = "wasm")]
1833 Self::Wasm => {
1834 write!(f, "Failed to load the Wasm store.")
1835 }
1836 }
1837 }
1838}
1839
1840pub fn wasm_stdlib_symbols() -> impl Iterator<Item = &'static str> {
1841 const WASM_STDLIB_SYMBOLS: &str = include_str!(concat!(env!("OUT_DIR"), "/stdlib-symbols.txt"));
1842
1843 WASM_STDLIB_SYMBOLS
1844 .lines()
1845 .map(|s| s.trim_matches(|c| c == '"' || c == ','))
1846}
1847
1848unsafe extern "C" {
1849 fn ts_node_string_pretty(node: ffi::TSNode, initial_indent_level: usize) -> *mut c_char;
1850 static mut ts_current_free: unsafe extern "C" fn(ptr: *mut c_void);
1851}
1852
1853#[inline]
1856unsafe fn ts_free(ptr: *mut c_void) {
1857 let f = unsafe { core::ptr::addr_of!(ts_current_free).read() };
1858 unsafe { f(ptr) };
1859}
1860
1861#[derive(Copy, Clone)]
1863pub struct Allocator {
1864 pub malloc: unsafe extern "C" fn(size: usize) -> *mut c_void,
1865 pub calloc: unsafe extern "C" fn(nmemb: usize, size: usize) -> *mut c_void,
1866 pub realloc: unsafe extern "C" fn(ptr: *mut c_void, size: usize) -> *mut c_void,
1867 pub free: unsafe extern "C" fn(ptr: *mut c_void),
1868}
1869
1870#[doc(alias = "ts_set_allocator")]
1889pub unsafe fn set_allocator(allocator: Option<Allocator>) {
1890 let (m, c, r, f) = match allocator {
1891 Some(a) => (
1892 Some(a.malloc),
1893 Some(a.calloc),
1894 Some(a.realloc),
1895 Some(a.free),
1896 ),
1897 None => (None, None, None, None),
1898 };
1899 unsafe { ffi::ts_set_allocator(m, c, r, f) };
1900}
1901
1902#[cfg(feature = "std")]
1903#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1904impl error::Error for IncludedRangesError {}
1905#[cfg(feature = "std")]
1906#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1907impl error::Error for LanguageError {}
1908
1909#[cfg(not(target_family = "wasm"))]
1910unsafe impl Send for Language {}
1911#[cfg(not(target_family = "wasm"))]
1912unsafe impl Sync for Language {}
1913
1914unsafe impl Send for Node<'_> {}
1915unsafe impl Sync for Node<'_> {}
1916
1917#[cfg(not(target_family = "wasm"))]
1918unsafe impl Send for Parser {}
1919#[cfg(not(target_family = "wasm"))]
1920unsafe impl Sync for Parser {}
1921
1922unsafe impl Send for Tree {}
1923unsafe impl Sync for Tree {}
1924
1925unsafe impl Send for TreeCursor<'_> {}
1926unsafe impl Sync for TreeCursor<'_> {}