Skip to main content

tree_sitter/
lib.rs

1// code-gauge-allow-file fileNcss 852 -- 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 CLI of this fork assigns it to each generated language. Its upper 16
53/// bits (`0x5742`, "WB") tag the fork and its lower 16 bits count the fork's
54/// ABI revisions, so that it never equals an ABI version of upstream
55/// Tree-sitter: the library rejects languages generated by upstream's CLI, and
56/// upstream's library rejects languages generated by this fork's CLI.
57#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
58pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
59
60/// The earliest ABI version that is supported by the current version of the
61/// library. Its parse tables are a subset of those of [`LANGUAGE_VERSION`], so
62/// the library loads both.
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 can be assigned to a parser.
237    ///
238    /// When Tree-sitter is compiled to WebAssembly, languages obtained from a
239    /// syntax tree can be used for parsing only within the same WebAssembly
240    /// instance that created the tree. In other instances, such languages can
241    /// still be used to inspect syntax trees.
242    #[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    /// Get the name of this language. This returns `None` for a language with
249    /// another ABI version.
250    #[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    /// Get the ABI version number of this [`Language`].
258    ///
259    /// The library loads only languages whose number is from
260    /// [`MIN_COMPATIBLE_LANGUAGE_VERSION`] to [`LANGUAGE_VERSION`], which the CLI
261    /// of this fork assigns. Any other number comes from a parser
262    /// that another CLI generated.
263    #[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    /// Get the metadata for this language. This information is generated by the
270    /// CLI, and relies on the language author providing the correct metadata in
271    /// the language's `tree-sitter.json` file. This returns `None` for a
272    /// language with another ABI version.
273    ///
274    /// See also [`LanguageMetadata`].
275    #[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    /// Get the number of distinct node types in this language.
285    #[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    /// Get the number of valid states in this language.
292    #[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    /// Get a list of all supertype symbols for the language. The list is empty
299    /// for a language with another ABI version.
300    #[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    /// Get a list of all subtype symbols for a given supertype symbol. The list
315    /// is empty for a language with another ABI version.
316    #[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    /// Get the name of the node kind for the given numerical id.
331    #[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    /// Get the numeric id for the given node kind.
339    #[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    /// Check whether `id` can be used to index this language's symbol tables.
353    ///
354    /// `ts_symbol_metadata` holds one entry per grammar symbol plus one per alias,
355    /// so [`Self::node_kind_count`] is an exact bound. `ERROR` and `_ERROR` sit
356    /// at the top of the `u16` range and are handled by the C library before any
357    /// table lookup.
358    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    /// Check if the node type for the given numerical id is named (as opposed
363    /// to an anonymous node type).
364    #[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    /// Check if the node type for the given numerical id is visible (as opposed
371    /// to a hidden node type).
372    #[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    /// Check if the node type for the given numerical id is a supertype.
379    #[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    /// Get the number of distinct field names in this language.
386    #[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    /// Get the field name for the given numerical id.
393    #[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    /// Get the numerical id for the given field name.
401    #[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    /// Create a new parser.
450    #[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    /// Set the language that the parser should use for parsing.
460    ///
461    /// Returns a Result indicating whether or not the language was successfully
462    /// assigned. Assignment fails if the language cannot be used for parsing,
463    /// or if it was generated with an incompatible version of the Tree-sitter
464    /// CLI. Check this using [`Language::is_parseable`] and
465    /// [`Language::abi_version`].
466    #[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    /// Get the parser's current language.
489    #[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    /// Get the parser's current logger.
497    #[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    /// Set the logging callback that the parser should use during parsing.
505    ///
506    /// To log through a callback that borrows non-`'static` data, see
507    /// [`set_logger_unchecked`](Parser::set_logger_unchecked).
508    #[doc(alias = "ts_parser_set_logger")]
509    pub fn set_logger(&mut self, logger: Option<Logger>) {
510        // SAFETY: `Logger` is `Send + 'static`
511        unsafe { self.set_logger_unchecked(logger) };
512    }
513
514    /// Set the logging callback, allowing the callback to borrow non-`'static`
515    /// data. See [`set_logger`](Parser::set_logger).
516    ///
517    /// # Safety
518    ///
519    /// Any data borrowed by `logger` must remain valid until the logger is
520    /// removed. Equivalently, the parser must not be used to parse once the
521    /// borrowed data has gone out of scope.
522    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    /// Set the destination to which the parser should write debugging graphs
566    /// during parsing. The graphs are formatted in the DOT language. You may
567    /// want to pipe these graphs directly to a `dot(1)` process in order to
568    /// generate SVG output.
569    #[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    /// Stop the parser from printing debugging graphs while parsing.
596    #[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    /// Parse a slice of UTF8 text.
605    ///
606    /// # Arguments:
607    /// * `text` The UTF8-encoded text to parse.
608    ///
609    /// Returns a [`Tree`] if parsing succeeded, or `None` if:
610    ///  * The parser has not yet had a language assigned with [`Parser::set_language`]
611    #[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    /// Parse text provided in chunks by a callback.
636    ///
637    /// # Arguments:
638    /// * `callback` A function that takes a byte offset and position and returns a slice of
639    ///   UTF8-encoded text starting at that byte offset and position. The slices can be of any
640    ///   length. If the given position is at the end of the text, the callback should return an
641    ///   empty slice.
642    /// * `options` Options for parsing the text. This can be used to set a progress callback.
643    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    /// Parse a slice of UTF16 little-endian text.
652    ///
653    /// # Arguments:
654    /// * `input` The UTF16-encoded text to parse.
655    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    /// Parse UTF16 little-endian text provided in chunks by a callback.
660    ///
661    /// # Arguments:
662    /// * `callback` A function that takes a code point offset and position and returns a slice of
663    ///   UTF16-encoded text starting at that byte offset and position. The slices can be of any
664    ///   length. If the given position is at the end of the text, the callback should return an
665    ///   empty slice.
666    /// * `options` Options for parsing the text. This can be used to set a progress callback.
667    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    /// Parse a slice of UTF16 big-endian text.
676    ///
677    /// # Arguments:
678    /// * `input` The UTF16-encoded text to parse.
679    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    /// Parse UTF16 big-endian text provided in chunks by a callback.
684    ///
685    /// # Arguments:
686    /// * `callback` A function that takes a code point offset and position and returns a slice of
687    ///   UTF16-encoded text starting at that byte offset and position. The slices can be of any
688    ///   length. If the given position is at the end of the text, the callback should return an
689    ///   empty slice.
690    /// * `options` Options for parsing the text. This can be used to set a progress callback.
691    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    /// Parse text provided in chunks by a callback using a custom encoding.
700    /// This is useful for parsing text in encodings that are not UTF-8 or UTF-16.
701    ///
702    /// # Arguments:
703    /// * `callback` A function that takes a byte offset and position and returns a slice of text
704    ///   starting at that byte offset and position. The slices can be of any length. If the given
705    ///   position is at the end of the text, the callback should return an empty slice.
706    /// * `options` Options for parsing the text. This can be used to set a progress callback.
707    ///
708    /// Additionally, you must set the generic parameter [`D`] to a type that implements the
709    /// [`Decode`] trait. This trait has a single method, [`decode`](Decode::decode), which takes a
710    /// slice of bytes and returns a tuple of the code point and the number of bytes consumed.
711    /// The `decode` method should return `-1` for the code point if decoding fails.
712    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        // Hold the returned chunk in `payload` across the next C read so callbacks may return owned buffers.
811        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    /// Instruct the parser to start the next parse from the beginning.
871    ///
872    /// If the parser previously failed because of a callback, then by default,
873    /// it will resume where it left off on the next call to [`parse`](Parser::parse)
874    /// or other parsing functions. If you don't want to resume, and instead intend to use
875    /// this parser to parse some other document, you must call `reset` first.
876    #[doc(alias = "ts_parser_reset")]
877    pub fn reset(&mut self) {
878        unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
879    }
880
881    /// Set the ranges of text that the parser should include when parsing.
882    ///
883    /// By default, the parser will always include entire documents. This
884    /// function allows you to parse only a *portion* of a document but
885    /// still return a syntax tree whose ranges match up with the document
886    /// as a whole. You can also pass multiple disjoint ranges.
887    ///
888    /// If `ranges` is empty, then the entire document will be parsed.
889    /// Otherwise, the given ranges must be ordered from earliest to latest
890    /// in the document, and they must not overlap. That is, the following
891    /// must hold for all `i` < `length - 1`:
892    /// ```text
893    ///     ranges[i].end_byte <= ranges[i + 1].start_byte
894    /// ```
895    /// If this requirement is not satisfied, method will return
896    /// [`IncludedRangesError`] error with an offset in the passed ranges
897    /// slice pointing to a first incorrect range.
898    #[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    /// Get the ranges of text that the parser will include when parsing.
924    #[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    /// Get the root node of the syntax tree.
956    #[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    /// Get the root node of the syntax tree, but with its position shifted
963    /// forward by the given offset.
964    #[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    /// Get the language that was used to parse the syntax tree.
978    ///
979    /// When Tree-sitter is compiled to WebAssembly, this returns the original
980    /// language if the tree is being accessed from the same WebAssembly
981    /// instance that created it. Otherwise, this returns a copy of the language
982    /// that can be used to inspect the tree but cannot be assigned to a parser.
983    #[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    /// Create a new [`TreeCursor`] starting from the root of the tree.
993    #[must_use]
994    pub fn walk(&self) -> TreeCursor {
995        self.root_node().walk()
996    }
997
998    /// Get the included ranges that were used to parse the syntax tree.
999    #[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    /// Print a graph of the tree to the given file descriptor.
1013    /// The graph is formatted in the DOT language. You may want to pipe this
1014    /// graph directly to a `dot(1)` process in order to generate SVG
1015    /// output.
1016    #[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    /// Get a numeric id for this node that is unique within its syntax tree.
1064    #[must_use]
1065    pub fn id(&self) -> usize {
1066        self.0.id as usize
1067    }
1068
1069    /// Get this node's type as a numerical id.
1070    #[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    /// Get the node's type as a numerical id as it appears in the grammar
1077    /// ignoring aliases.
1078    #[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    /// Get this node's type as a string.
1085    #[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    /// Get this node's symbol name as it appears in the grammar ignoring
1094    /// aliases as a string.
1095    #[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    /// Get the [`Language`] that was used to parse this node's syntax tree.
1104    ///
1105    /// When Tree-sitter is compiled to WebAssembly, this returns the original
1106    /// language if the node is being accessed from the same WebAssembly
1107    /// instance that created its tree. Otherwise, this returns a copy of the
1108    /// language that can be used to inspect the tree but cannot be assigned to
1109    /// a parser.
1110    #[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    /// Check if this node is *named*.
1117    ///
1118    /// Named nodes correspond to named rules in the grammar, whereas
1119    /// *anonymous* nodes correspond to string literals in the grammar.
1120    #[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    /// Check if this node is *extra*.
1127    ///
1128    /// Extra nodes represent things like comments, which are not required by the
1129    /// grammar, but can appear anywhere.
1130    #[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    /// Check if this node represents a syntax error or contains any syntax
1137    /// errors anywhere within it.
1138    #[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    /// Check if this node represents a syntax error.
1145    ///
1146    /// Syntax errors represent parts of the code that could not be incorporated
1147    /// into a valid syntax tree.
1148    #[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    /// Check if this node is *missing*.
1155    ///
1156    /// Missing nodes are inserted by the parser in order to recover from
1157    /// certain kinds of syntax errors.
1158    #[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    /// Get the byte offset where this node starts.
1165    #[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    /// Get the byte offset where this node ends.
1173    #[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    /// Get the byte range of source code that this node represents.
1180    #[inline]
1181    #[must_use]
1182    pub fn byte_range(&self) -> core::ops::Range<usize> {
1183        self.start_byte()..self.end_byte()
1184    }
1185
1186    /// Get the range of source code that this node represents, both in terms of
1187    /// raw bytes and of row/column coordinates.
1188    #[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    /// Get this node's start position in terms of rows and columns.
1199    #[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    /// Get this node's end position in terms of rows and columns.
1210    #[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    /// Get the node's child at the given index, where zero represents the first
1218    /// child.
1219    ///
1220    /// This method is fairly fast, but its cost is technically log(i), so if
1221    /// you might be iterating over a long list of children, you should use
1222    /// [`Node::children`] instead.
1223    #[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    /// Get this node's number of children.
1230    #[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    /// Get this node's *named* child at the given index.
1237    ///
1238    /// See also [`Node::is_named`].
1239    /// This method is fairly fast, but its cost is technically log(i), so if
1240    /// you might be iterating over a long list of children, you should use
1241    /// [`Node::named_children`] instead.
1242    #[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    /// Get this node's number of *named* children.
1249    ///
1250    /// See also [`Node::is_named`].
1251    #[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    /// Get the first child with the given field name.
1258    ///
1259    /// If multiple children may have the same field name, access them using
1260    /// [`children_by_field_name`](Node::children_by_field_name)
1261    #[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    /// Get this node's child with the given numerical field id.
1275    ///
1276    /// See also [`child_by_field_name`](Node::child_by_field_name). You can
1277    /// convert a field name to an id using [`Language::field_id_for_name`].
1278    #[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    /// Get the field name of this node's child at the given index.
1285    #[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    /// Get the field name of this node's named child at the given index.
1295    #[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    /// Iterate over this node's children.
1304    ///
1305    /// A [`TreeCursor`] is used to retrieve the children efficiently. Obtain
1306    /// a [`TreeCursor`] by calling [`Tree::walk`] or [`Node::walk`]. To avoid
1307    /// unnecessary allocations, you should reuse the same cursor for
1308    /// subsequent calls to this method.
1309    ///
1310    /// If you're walking the tree recursively, you may want to use the
1311    /// [`TreeCursor`] APIs directly instead.
1312    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    /// Iterate over this node's named children.
1326    ///
1327    /// See also [`Node::children`].
1328    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    /// Iterate over this node's children with a given field name.
1347    ///
1348    /// See also [`Node::children`].
1349    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    /// Iterate over this node's children with a given field id.
1378    ///
1379    /// See also [`Node::children_by_field_name`].
1380    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    /// Get this node's immediate parent.
1406    /// Prefer [`child_with_descendant`](Node::child_with_descendant)
1407    /// for iterating over this node's ancestors.
1408    #[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    /// Get the node that contains `descendant`.
1415    ///
1416    /// Note that this can return `descendant` itself.
1417    #[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    /// Get this node's next sibling.
1424    #[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    /// Get this node's previous sibling.
1431    #[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    /// Get this node's next named sibling.
1438    #[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    /// Get this node's previous named sibling.
1445    #[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    /// Get this node's first child that contains or starts after the given byte offset.
1452    #[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    /// Get this node's first named child that contains or starts after the given byte offset.
1459    #[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    /// Get the node's number of descendants, including one for the node itself.
1466    #[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    /// Get the smallest node within this node that spans the given byte range.
1473    #[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    /// Get the smallest named node within this node that spans the given byte range.
1482    #[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    /// Get the smallest node within this node that spans the given point range.
1491    #[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    /// Get the smallest named node within this node that spans the given point range.
1500    #[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    /// Get an S-expression representing the node.
1509    #[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    /// Create a new [`TreeCursor`] starting from this node.
1531    ///
1532    /// Note that the given node is considered the root of the cursor,
1533    /// and the cursor cannot walk outside this node.
1534    #[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    /// Get the tree cursor's current [`Node`].
1588    #[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    /// Get the numerical field id of this tree cursor's current node.
1598    ///
1599    /// See also [`field_name`](TreeCursor::field_name).
1600    #[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    /// Get the field name of this tree cursor's current node.
1608    #[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    /// Get the depth of the cursor's current node relative to the original
1618    /// node that the cursor was constructed with.
1619    #[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    /// Get the index of the cursor's current node out of all of the
1626    /// descendants of the original node that the cursor was constructed with
1627    #[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    /// Move this cursor to the first child of its current node.
1634    ///
1635    /// This returns `true` if the cursor successfully moved, and returns
1636    /// `false` if there were no children.
1637    #[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    /// Move this cursor to the last child of its current node.
1643    ///
1644    /// This returns `true` if the cursor successfully moved, and returns
1645    /// `false` if there were no children.
1646    ///
1647    /// Note that this function may be slower than
1648    /// [`goto_first_child`](TreeCursor::goto_first_child) because it needs to
1649    /// iterate through all the children to compute the child's position.
1650    #[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    /// Move this cursor to the parent of its current node.
1656    ///
1657    /// This returns `true` if the cursor successfully moved, and returns
1658    /// `false` if there was no parent node (the cursor was already on the
1659    /// root node).
1660    ///
1661    /// Note that the node the cursor was constructed with is considered the root
1662    /// of the cursor, and the cursor cannot walk outside this node.
1663    #[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    /// Move this cursor to the next sibling of its current node.
1669    ///
1670    /// This returns `true` if the cursor successfully moved, and returns
1671    /// `false` if there was no next sibling node.
1672    ///
1673    /// Note that the node the cursor was constructed with is considered the root
1674    /// of the cursor, and the cursor cannot walk outside this node.
1675    #[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    /// Move the cursor to the node that is the nth descendant of
1681    /// the original node that the cursor was constructed with, where
1682    /// zero represents the original node itself.
1683    #[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    /// Move this cursor to the previous sibling of its current node.
1689    ///
1690    /// This returns `true` if the cursor successfully moved, and returns
1691    /// `false` if there was no previous sibling node.
1692    ///
1693    /// Note, that this function may be slower than
1694    /// [`goto_next_sibling`](TreeCursor::goto_next_sibling) due to how node
1695    /// positions are stored. In the worst case, this will need to iterate
1696    /// through all the children up to the previous sibling node to recalculate
1697    /// its position. Also note that the node the cursor was constructed with is
1698    /// considered the root of the cursor, and the cursor cannot walk outside this node.
1699    #[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    /// Move this cursor to the first child of its current node that contains or
1705    /// starts after the given byte offset.
1706    ///
1707    /// This returns the index of the child node if one was found, and returns
1708    /// `None` if no such child was found.
1709    #[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    /// Move this cursor to the first child of its current node that contains or
1717    /// starts after the given byte offset.
1718    ///
1719    /// This returns the index of the child node if one was found, and returns
1720    /// `None` if no such child was found.
1721    #[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    /// Re-initialize this tree cursor to start at the original node that the
1730    /// cursor was constructed with.
1731    #[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    /// Re-initialize a tree cursor to the same position as another cursor.
1737    ///
1738    /// Unlike [`reset`](TreeCursor::reset), this will not lose parent
1739    /// information and allows reusing already created cursors.
1740    #[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/// Frees a pointer that was returned by a tree-sitter C API using whichever `free`
1854/// function is currently installed via [`set_allocator`] or [`ffi::ts_set_allocator`].
1855#[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/// A complete set of memory allocation functions for the core C library.
1862#[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/// Replaces the memory allocation functions used by the core C library.
1871///
1872/// Pass `Some` to install an allocator, or `None` to restore libc defaults.
1873///
1874/// # Safety
1875///
1876/// All of the following must hold:
1877///
1878/// - The four functions must belong to a single allocator family.
1879///
1880/// - The functions must not return null for non-zero allocs.
1881///
1882/// - Returned pointers must satisfy the alignment that libc `malloc` provides.
1883///
1884/// - Call this before any other tree-sitter API call, and do not call it again
1885///   while live tree-sitter objects exist.
1886///
1887/// - This function is not thread-safe.
1888#[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<'_> {}