Skip to main content

tree_sitter/
lib.rs

1// code-gauge-allow-file fileNcss -- core Parser, Language, Tree, Node, and TreeCursor bindings share private wrappers
2#![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/// The latest ABI version that the current version of the library supports.
51///
52/// The upper 16 bits of each generated language ABI (`0x5742`, "WB") tag the fork and its lower 16 bits count the fork's
53/// ABI revisions, so that it never equals an ABI version of upstream
54/// Tree-sitter: the library rejects languages generated by upstream's CLI, and
55/// upstream's library rejects languages generated by this fork's CLI.
56#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
57pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
58
59/// The earliest ABI version that is supported by the current version of the
60/// library.
61///
62/// Scanners using this ABI read one input character at a time.
63#[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/// An opaque object that defines how to parse a particular language. The code
70/// for each `Language` is generated by the Tree-sitter CLI.
71#[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/// The metadata associated with a language.
82///
83/// Currently, this metadata can be used to check the [Semantic Version](https://semver.org/)
84/// of the language.
85#[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/// A tree that represents the syntactic structure of a source code file.
103#[doc(alias = "TSTree")]
104pub struct Tree(NonNull<ffi::TSTree>);
105
106/// A position in a multi-line text document, in terms of rows and columns.
107///
108/// Rows and columns are zero-based.
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
110pub struct Point {
111    pub row: usize,
112    pub column: usize,
113}
114
115/// A range of positions in a multi-line text document, both in terms of bytes
116/// and of rows and columns.
117#[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/// A single node within a syntax [`Tree`].
126#[doc(alias = "TSNode")]
127#[derive(Clone, Copy)]
128#[repr(transparent)]
129pub struct Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>);
130
131/// A stateful object that this is used to produce a [`Tree`] based on some
132/// source code.
133#[doc(alias = "TSParser")]
134pub struct Parser(NonNull<ffi::TSParser>);
135
136/// A stateful object that is passed into a [`ParseProgressCallback`]
137/// to pass in the current state of the parser.
138pub 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    /// Create a new `ParseOptions` with a shorter lifetime, borrowing from this one.
173    ///
174    /// This is useful when you need to reuse parse options multiple times, e.g., calling
175    /// [`Parser::parse_with_options`] multiple times with the same options.
176    #[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/// A type of log message.
188#[derive(Debug, PartialEq, Eq)]
189pub enum LogType {
190    Parse,
191    Lex,
192}
193
194type FieldId = NonZeroU16;
195
196/// A callback that receives log messages during parsing.
197type Logger = Box<dyn FnMut(LogType, &str) + Send + 'static>;
198
199/// A callback that receives log messages during parsing, with relaxed constraints.
200type UnsafeLogger<'a> = Box<dyn FnMut(LogType, &str) + Send + 'a>;
201
202/// A callback that receives the parse state during parsing.
203type ParseProgressCallback<'a> = &'a mut dyn FnMut(&ParseState) -> ControlFlow<()>;
204
205pub trait Decode {
206    /// A callback that decodes the next code point from the input slice. It should return the code
207    /// point, and how many bytes were decoded.
208    fn decode(bytes: &[u8]) -> (i32, u32);
209}
210
211/// A stateful object for walking a syntax [`Tree`] efficiently.
212#[doc(alias = "TSTreeCursor")]
213pub struct TreeCursor<'tree>(ffi::TSTreeCursor, PhantomData<&'tree ()>);
214
215/// An error that occurred when trying to assign a [`Language`] to a [`Parser`].
216/// If the `wasm` feature is enabled, this can also indicate a failure to load
217/// the Wasm store.
218#[derive(Debug, PartialEq, Eq)]
219pub enum LanguageError {
220    Version(usize),
221    NotParseable,
222    #[cfg(feature = "wasm")]
223    Wasm,
224}
225
226/// An error that occurred in [`Parser::set_included_ranges`].
227#[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    /// Check whether this language has a supported ABI and a lexer available
237    /// in this instance. [`Parser::set_language`] validates generated name-role
238    /// tables during assignment.
239    ///
240    /// When Tree-sitter is compiled to WebAssembly, languages obtained from a
241    /// syntax tree can be used for parsing only within the same WebAssembly
242    /// instance that created the tree. In other instances, such languages can
243    /// still be used to inspect syntax trees.
244    #[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    /// Get the name of this language. This returns `None` for a language with
251    /// another ABI version.
252    #[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    /// Get the ABI version number of this [`Language`].
260    ///
261    /// The library loads only languages whose number is from
262    /// [`MIN_COMPATIBLE_LANGUAGE_VERSION`] to [`LANGUAGE_VERSION`], which the CLI
263    /// of this fork assigns. Any other number comes from a parser
264    /// that another CLI generated.
265    #[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    /// Get the metadata for this language. This information is generated by the
272    /// CLI, and relies on the language author providing the correct metadata in
273    /// the language's `tree-sitter.json` file. This returns `None` for a
274    /// language with another ABI version.
275    ///
276    /// See also [`LanguageMetadata`].
277    #[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    /// Get the number of distinct node types in this language.
287    #[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    /// Get the number of valid states in this language.
294    #[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    /// Get a list of all supertype symbols for the language. The list is empty
301    /// for a language with another ABI version.
302    #[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    /// Get a list of all subtype symbols for a given supertype symbol. The list
317    /// is empty for a language with another ABI version.
318    #[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    /// Get the name of the node kind for the given numerical id.
333    #[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    /// Get the numeric id for the given node kind.
341    #[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    /// Check whether `id` can be used to index this language's symbol tables.
355    ///
356    /// `ts_symbol_metadata` holds one entry per grammar symbol plus one per alias,
357    /// so [`Self::node_kind_count`] is an exact bound. `ERROR` and `_ERROR` sit
358    /// at the top of the `u16` range and are handled by the C library before any
359    /// table lookup.
360    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    /// Check if the node type for the given numerical id is named (as opposed
365    /// to an anonymous node type).
366    #[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    /// Check if the node type for the given numerical id is visible (as opposed
373    /// to a hidden node type).
374    #[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    /// Check if the node type for the given numerical id is a supertype.
381    #[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    /// Get the number of distinct field names in this language.
388    #[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    /// Get the field name for the given numerical id.
395    #[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    /// Get the numerical id for the given field name.
403    #[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    /// Create a new parser.
452    #[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    /// Set the language that the parser should use for parsing.
462    ///
463    /// The language must pass [`Language::is_parseable`]. Assignment also validates
464    /// generated name-role tables and starts the store for a Wasm language.
465    /// If a generated table is incompatible, regenerate the grammar with the CLI
466    /// from the runtime's release and rebuild its native library or Wasm file.
467    #[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    /// Get the parser's current language.
488    #[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    /// Get the parser's current logger.
496    #[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    /// Set the logging callback that the parser should use during parsing.
504    ///
505    /// To log through a callback that borrows non-`'static` data, see
506    /// [`set_logger_unchecked`](Parser::set_logger_unchecked).
507    #[doc(alias = "ts_parser_set_logger")]
508    pub fn set_logger(&mut self, logger: Option<Logger>) {
509        // SAFETY: `Logger` is `Send + 'static`
510        unsafe { self.set_logger_unchecked(logger) };
511    }
512
513    /// Set the logging callback, allowing the callback to borrow non-`'static`
514    /// data. See [`set_logger`](Parser::set_logger).
515    ///
516    /// # Safety
517    ///
518    /// Any data borrowed by `logger` must remain valid until the logger is
519    /// removed. Equivalently, the parser must not be used to parse once the
520    /// borrowed data has gone out of scope.
521    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    /// Set the destination to which the parser should write debugging graphs
565    /// during parsing. The graphs are formatted in the DOT language. You may
566    /// want to pipe these graphs directly to a `dot(1)` process in order to
567    /// generate SVG output.
568    #[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    /// Stop the parser from printing debugging graphs while parsing.
595    #[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    /// Parse a slice of UTF8 text.
604    ///
605    /// # Arguments:
606    /// * `text` The UTF8-encoded text to parse.
607    ///
608    /// Returns a [`Tree`] if parsing succeeded, or `None` if:
609    ///  * The parser has not yet had a language assigned with [`Parser::set_language`]
610    #[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    /// Parse text provided in chunks by a callback.
635    ///
636    /// # Arguments:
637    /// * `callback` A function that takes a byte offset and position and returns a slice of
638    ///   UTF8-encoded text starting at that byte offset and position. The slices can be of any
639    ///   length. If the given position is at the end of the text, the callback should return an
640    ///   empty slice.
641    /// * `options` Options for parsing the text. This can be used to set a progress callback.
642    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    /// Parse a slice of UTF16 little-endian text.
651    ///
652    /// # Arguments:
653    /// * `input` The UTF16-encoded text to parse.
654    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    /// Parse UTF16 little-endian text provided in chunks by a callback.
659    ///
660    /// # Arguments:
661    /// * `callback` A function that takes a code point offset and position and returns a slice of
662    ///   UTF16-encoded text starting at that byte offset and position. The slices can be of any
663    ///   length. If the given position is at the end of the text, the callback should return an
664    ///   empty slice.
665    /// * `options` Options for parsing the text. This can be used to set a progress callback.
666    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    /// Parse a slice of UTF16 big-endian text.
675    ///
676    /// # Arguments:
677    /// * `input` The UTF16-encoded text to parse.
678    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    /// Parse UTF16 big-endian text provided in chunks by a callback.
683    ///
684    /// # Arguments:
685    /// * `callback` A function that takes a code point offset and position and returns a slice of
686    ///   UTF16-encoded text starting at that byte offset and position. The slices can be of any
687    ///   length. If the given position is at the end of the text, the callback should return an
688    ///   empty slice.
689    /// * `options` Options for parsing the text. This can be used to set a progress callback.
690    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    /// Parse text provided in chunks by a callback using a custom encoding.
699    /// This is useful for parsing text in encodings that are not UTF-8 or UTF-16.
700    ///
701    /// # Arguments:
702    /// * `callback` A function that takes a byte offset and position and returns a slice of text
703    ///   starting at that byte offset and position. The slices can be of any length. If the given
704    ///   position is at the end of the text, the callback should return an empty slice.
705    /// * `options` Options for parsing the text. This can be used to set a progress callback.
706    ///
707    /// Additionally, you must set the generic parameter [`D`] to a type that implements the
708    /// [`Decode`] trait. This trait has a single method, [`decode`](Decode::decode), which takes a
709    /// slice of bytes and returns a tuple of the code point and the number of bytes consumed.
710    /// The `decode` method should return `-1` for the code point if decoding fails.
711    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        // Hold the returned chunk in `payload` across the next C read so callbacks may return owned buffers.
810        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    /// Instruct the parser to start the next parse from the beginning.
870    ///
871    /// If the parser previously failed because of a callback, then by default,
872    /// it will resume where it left off on the next call to [`parse`](Parser::parse)
873    /// or other parsing functions. If you don't want to resume, and instead intend to use
874    /// this parser to parse some other document, you must call `reset` first.
875    #[doc(alias = "ts_parser_reset")]
876    pub fn reset(&mut self) {
877        unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
878    }
879
880    /// Set the ranges of text that the parser should include when parsing.
881    ///
882    /// By default, the parser will always include entire documents. This
883    /// function allows you to parse only a *portion* of a document but
884    /// still return a syntax tree whose ranges match up with the document
885    /// as a whole. You can also pass multiple disjoint ranges.
886    ///
887    /// If `ranges` is empty, then the entire document will be parsed.
888    /// Otherwise, the given ranges must be ordered from earliest to latest
889    /// in the document, and they must not overlap. That is, the following
890    /// must hold for all `i` < `length - 1`:
891    /// ```text
892    ///     ranges[i].end_byte <= ranges[i + 1].start_byte
893    /// ```
894    /// If this requirement is not satisfied, method will return
895    /// [`IncludedRangesError`] error with an offset in the passed ranges
896    /// slice pointing to a first incorrect range.
897    #[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    /// Get the ranges of text that the parser will include when parsing.
923    #[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    /// Get the root node of the syntax tree.
955    #[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    /// Get the root node of the syntax tree, but with its position shifted
962    /// forward by the given offset.
963    #[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    /// Get the language that was used to parse the syntax tree.
977    ///
978    /// When Tree-sitter is compiled to WebAssembly, this returns the original
979    /// language if the tree is being accessed from the same WebAssembly
980    /// instance that created it. Otherwise, this returns a copy of the language
981    /// that can be used to inspect the tree but cannot be assigned to a parser.
982    #[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    /// Create a new [`TreeCursor`] starting from the root of the tree.
992    #[must_use]
993    pub fn walk(&self) -> TreeCursor {
994        self.root_node().walk()
995    }
996
997    /// Get the included ranges that were used to parse the syntax tree.
998    #[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    /// Print a graph of the tree to the given file descriptor.
1012    /// The graph is formatted in the DOT language. You may want to pipe this
1013    /// graph directly to a `dot(1)` process in order to generate SVG
1014    /// output.
1015    #[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    /// Get a numeric id for this node that is unique within its syntax tree.
1063    #[must_use]
1064    pub fn id(&self) -> usize {
1065        self.0.id as usize
1066    }
1067
1068    /// Get this node's type as a numerical id.
1069    #[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    /// Get the node's type as a numerical id as it appears in the grammar
1076    /// ignoring aliases.
1077    #[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    /// Get this node's type as a string.
1084    #[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    /// Get this node's symbol name as it appears in the grammar ignoring
1093    /// aliases as a string.
1094    #[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    /// Get the [`Language`] that was used to parse this node's syntax tree.
1103    ///
1104    /// When Tree-sitter is compiled to WebAssembly, this returns the original
1105    /// language if the node is being accessed from the same WebAssembly
1106    /// instance that created its tree. Otherwise, this returns a copy of the
1107    /// language that can be used to inspect the tree but cannot be assigned to
1108    /// a parser.
1109    #[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    /// Check if this node is *named*.
1116    ///
1117    /// Named nodes correspond to named rules in the grammar, whereas
1118    /// *anonymous* nodes correspond to string literals in the grammar.
1119    #[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    /// Check if this node is *extra*.
1126    ///
1127    /// Extra nodes represent things like comments, which are not required by the
1128    /// grammar, but can appear anywhere.
1129    #[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    /// Check if this node represents a syntax error or contains any syntax
1136    /// errors anywhere within it.
1137    #[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    /// Check if this node represents a syntax error.
1144    ///
1145    /// Syntax errors represent parts of the code that could not be incorporated
1146    /// into a valid syntax tree.
1147    #[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    /// Check if this node is *missing*.
1154    ///
1155    /// Missing nodes are inserted by the parser in order to recover from
1156    /// certain kinds of syntax errors.
1157    #[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    /// Get the byte offset where this node starts.
1164    #[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    /// Get the byte offset where this node ends.
1172    #[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    /// Get the byte range of source code that this node represents.
1179    #[inline]
1180    #[must_use]
1181    pub fn byte_range(&self) -> core::ops::Range<usize> {
1182        self.start_byte()..self.end_byte()
1183    }
1184
1185    /// Get the range of source code that this node represents, both in terms of
1186    /// raw bytes and of row/column coordinates.
1187    #[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    /// Get this node's start position in terms of rows and columns.
1198    #[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    /// Get this node's end position in terms of rows and columns.
1209    #[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    /// Get the node's child at the given index, where zero represents the first
1217    /// child.
1218    ///
1219    /// This method is fairly fast, but its cost is technically log(i), so if
1220    /// you might be iterating over a long list of children, you should use
1221    /// [`Node::children`] instead.
1222    #[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    /// Get this node's number of children.
1229    #[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    /// Get this node's *named* child at the given index.
1236    ///
1237    /// See also [`Node::is_named`].
1238    /// This method is fairly fast, but its cost is technically log(i), so if
1239    /// you might be iterating over a long list of children, you should use
1240    /// [`Node::named_children`] instead.
1241    #[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    /// Get this node's number of *named* children.
1248    ///
1249    /// See also [`Node::is_named`].
1250    #[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    /// Get the first child with the given field name.
1257    ///
1258    /// If multiple children may have the same field name, access them using
1259    /// [`children_by_field_name`](Node::children_by_field_name)
1260    #[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    /// Get this node's child with the given numerical field id.
1274    ///
1275    /// See also [`child_by_field_name`](Node::child_by_field_name). You can
1276    /// convert a field name to an id using [`Language::field_id_for_name`].
1277    #[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    /// Get the field name of this node's child at the given index.
1284    #[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    /// Get the field name of this node's named child at the given index.
1294    #[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    /// Iterate over this node's children.
1303    ///
1304    /// A [`TreeCursor`] is used to retrieve the children efficiently. Obtain
1305    /// a [`TreeCursor`] by calling [`Tree::walk`] or [`Node::walk`]. To avoid
1306    /// unnecessary allocations, you should reuse the same cursor for
1307    /// subsequent calls to this method.
1308    ///
1309    /// If you're walking the tree recursively, you may want to use the
1310    /// [`TreeCursor`] APIs directly instead.
1311    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    /// Iterate over this node's named children.
1325    ///
1326    /// See also [`Node::children`].
1327    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    /// Iterate over this node's children with a given field name.
1346    ///
1347    /// See also [`Node::children`].
1348    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    /// Iterate over this node's children with a given field id.
1377    ///
1378    /// See also [`Node::children_by_field_name`].
1379    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    /// Get this node's immediate parent.
1405    /// Prefer [`child_with_descendant`](Node::child_with_descendant)
1406    /// for iterating over this node's ancestors.
1407    #[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    /// Get the node that contains `descendant`.
1414    ///
1415    /// Note that this can return `descendant` itself.
1416    #[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    /// Get this node's next sibling.
1423    #[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    /// Get this node's previous sibling.
1430    #[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    /// Get this node's next named sibling.
1437    #[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    /// Get this node's previous named sibling.
1444    #[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    /// Get this node's first child that contains or starts after the given byte offset.
1451    #[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    /// Get this node's first named child that contains or starts after the given byte offset.
1458    #[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    /// Get the node's number of descendants, including one for the node itself.
1465    #[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    /// Get the smallest node within this node that spans the given byte range.
1472    #[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    /// Get the smallest named node within this node that spans the given byte range.
1481    #[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    /// Get the smallest node within this node that spans the given point range.
1490    #[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    /// Get the smallest named node within this node that spans the given point range.
1499    #[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    /// Get an S-expression representing the node.
1508    #[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    /// Create a new [`TreeCursor`] starting from this node.
1530    ///
1531    /// Note that the given node is considered the root of the cursor,
1532    /// and the cursor cannot walk outside this node.
1533    #[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    /// Get the tree cursor's current [`Node`].
1587    #[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    /// Get the numerical field id of this tree cursor's current node.
1597    ///
1598    /// See also [`field_name`](TreeCursor::field_name).
1599    #[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    /// Get the field name of this tree cursor's current node.
1607    #[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    /// Get the depth of the cursor's current node relative to the original
1617    /// node that the cursor was constructed with.
1618    #[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    /// Get the index of the cursor's current node out of all of the
1625    /// descendants of the original node that the cursor was constructed with
1626    #[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    /// Move this cursor to the first child of its current node.
1633    ///
1634    /// This returns `true` if the cursor successfully moved, and returns
1635    /// `false` if there were no children.
1636    #[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    /// Move this cursor to the last child of its current node.
1642    ///
1643    /// This returns `true` if the cursor successfully moved, and returns
1644    /// `false` if there were no children.
1645    ///
1646    /// Note that this function may be slower than
1647    /// [`goto_first_child`](TreeCursor::goto_first_child) because it needs to
1648    /// iterate through all the children to compute the child's position.
1649    #[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    /// Move this cursor to the parent of its current node.
1655    ///
1656    /// This returns `true` if the cursor successfully moved, and returns
1657    /// `false` if there was no parent node (the cursor was already on the
1658    /// root node).
1659    ///
1660    /// Note that the node the cursor was constructed with is considered the root
1661    /// of the cursor, and the cursor cannot walk outside this node.
1662    #[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    /// Move this cursor to the next sibling of its current node.
1668    ///
1669    /// This returns `true` if the cursor successfully moved, and returns
1670    /// `false` if there was no next sibling node.
1671    ///
1672    /// Note that the node the cursor was constructed with is considered the root
1673    /// of the cursor, and the cursor cannot walk outside this node.
1674    #[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    /// Move the cursor to the node that is the nth descendant of
1680    /// the original node that the cursor was constructed with, where
1681    /// zero represents the original node itself.
1682    #[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    /// Move this cursor to the previous sibling of its current node.
1688    ///
1689    /// This returns `true` if the cursor successfully moved, and returns
1690    /// `false` if there was no previous sibling node.
1691    ///
1692    /// Note, that this function may be slower than
1693    /// [`goto_next_sibling`](TreeCursor::goto_next_sibling) due to how node
1694    /// positions are stored. In the worst case, this will need to iterate
1695    /// through all the children up to the previous sibling node to recalculate
1696    /// its position. Also note that the node the cursor was constructed with is
1697    /// considered the root of the cursor, and the cursor cannot walk outside this node.
1698    #[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    /// Move this cursor to the first child of its current node that contains or
1704    /// starts after the given byte offset.
1705    ///
1706    /// This returns the index of the child node if one was found, and returns
1707    /// `None` if no such child was found.
1708    #[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    /// Move this cursor to the first child of its current node that contains or
1716    /// starts after the given byte offset.
1717    ///
1718    /// This returns the index of the child node if one was found, and returns
1719    /// `None` if no such child was found.
1720    #[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    /// Re-initialize this tree cursor to start at the original node that the
1729    /// cursor was constructed with.
1730    #[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    /// Re-initialize a tree cursor to the same position as another cursor.
1736    ///
1737    /// Unlike [`reset`](TreeCursor::reset), this will not lose parent
1738    /// information and allows reusing already created cursors.
1739    #[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/// Frees a pointer that was returned by a tree-sitter C API using whichever `free`
1855/// function is currently installed via [`set_allocator`] or [`ffi::ts_set_allocator`].
1856#[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/// A complete set of memory allocation functions for the core C library.
1863#[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/// Replaces the memory allocation functions used by the core C library.
1872///
1873/// Pass `Some` to install an allocator, or `None` to restore libc defaults.
1874///
1875/// # Safety
1876///
1877/// All of the following must hold:
1878///
1879/// - The four functions must belong to a single allocator family.
1880///
1881/// - The functions must not return null for non-zero allocs.
1882///
1883/// - Returned pointers must satisfy the alignment that libc `malloc` provides.
1884///
1885/// - Call this before any other tree-sitter API call, and do not call it again
1886///   while live tree-sitter objects exist.
1887///
1888/// - This function is not thread-safe.
1889#[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<'_> {}