Skip to main content

tree_sitter/
lib.rs

1#![cfg_attr(not(any(test, doctest)), doc = include_str!("./README.md"))]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5pub mod ffi;
6mod util;
7
8#[cfg(any(
9    not(feature = "std"),
10    all(target_arch = "wasm32", target_os = "unknown")
11))]
12extern crate alloc;
13#[cfg(not(feature = "std"))]
14use alloc::{boxed::Box, format, string::String, string::ToString, vec::Vec};
15use core::{
16    ffi::{CStr, c_char, c_void},
17    fmt::{self, Write},
18    hash, iter,
19    marker::PhantomData,
20    mem::MaybeUninit,
21    num::NonZeroU16,
22    ops::{self, ControlFlow, Deref},
23    ptr::{self, NonNull},
24    slice, str,
25};
26#[cfg(feature = "std")]
27use std::error;
28#[cfg(all(unix, feature = "std"))]
29use std::os::fd::AsRawFd;
30#[cfg(all(windows, feature = "std"))]
31use std::os::windows::io::AsRawHandle;
32
33pub use streaming_iterator::{StreamingIterator, StreamingIteratorMut};
34use tree_sitter_language::LanguageFn;
35
36#[cfg(feature = "wasm")]
37mod wasm_language;
38#[cfg(feature = "wasm")]
39#[cfg_attr(docsrs, doc(cfg(feature = "wasm")))]
40pub use wasm_language::*;
41
42#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
43mod wasm_allocator;
44
45/// The latest ABI version that the current version of the library supports.
46///
47/// The CLI of this fork assigns it to each generated language. Its upper 16
48/// bits (`0x5742`, "WB") tag the fork and its lower 16 bits count the fork's
49/// ABI revisions, so that it never equals an ABI version of upstream
50/// Tree-sitter: the library rejects languages generated by upstream's CLI, and
51/// upstream's library rejects languages generated by this fork's CLI.
52#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
53pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
54
55/// The earliest ABI version that is supported by the current version of the
56/// library. Its parse tables are a subset of those of [`LANGUAGE_VERSION`], so
57/// the library loads both.
58#[doc(alias = "TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION")]
59pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize =
60    ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION as usize;
61
62pub const PARSER_HEADER: &str = include_str!("../src/parser.h");
63
64/// An opaque object that defines how to parse a particular language. The code
65/// for each `Language` is generated by the Tree-sitter CLI.
66#[doc(alias = "TSLanguage")]
67#[derive(Debug, PartialEq, Eq, Hash)]
68#[repr(transparent)]
69pub struct Language(*const ffi::TSLanguage);
70
71pub struct LanguageRef<'a>(*const ffi::TSLanguage, PhantomData<&'a ()>);
72
73/// The metadata associated with a language.
74///
75/// Currently, this metadata can be used to check the [Semantic Version](https://semver.org/)
76/// of the language. This version information should be used to signal if a given parser might
77/// be incompatible with existing queries when upgrading between major versions, or minor versions
78/// if it's in zerover.
79#[doc(alias = "TSLanguageMetadata")]
80pub struct LanguageMetadata {
81    pub major_version: u8,
82    pub minor_version: u8,
83    pub patch_version: u8,
84}
85
86impl From<ffi::TSLanguageMetadata> for LanguageMetadata {
87    fn from(val: ffi::TSLanguageMetadata) -> Self {
88        Self {
89            major_version: val.major_version,
90            minor_version: val.minor_version,
91            patch_version: val.patch_version,
92        }
93    }
94}
95
96/// A tree that represents the syntactic structure of a source code file.
97#[doc(alias = "TSTree")]
98pub struct Tree(NonNull<ffi::TSTree>);
99
100/// A position in a multi-line text document, in terms of rows and columns.
101///
102/// Rows and columns are zero-based.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
104pub struct Point {
105    pub row: usize,
106    pub column: usize,
107}
108
109/// A range of positions in a multi-line text document, both in terms of bytes
110/// and of rows and columns.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
112pub struct Range {
113    pub start_byte: usize,
114    pub end_byte: usize,
115    pub start_point: Point,
116    pub end_point: Point,
117}
118
119/// A summary of a change to a text document.
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub struct InputEdit {
122    pub start_byte: usize,
123    pub old_end_byte: usize,
124    pub new_end_byte: usize,
125    pub start_position: Point,
126    pub old_end_position: Point,
127    pub new_end_position: Point,
128}
129
130impl InputEdit {
131    /// Edit a point to keep it in-sync with source code that has been edited.
132    ///
133    /// This function updates a single point's byte offset and row/column position
134    /// based on this edit operation. This is useful for editing points without
135    /// requiring a tree or node instance.
136    #[doc(alias = "ts_point_edit")]
137    pub fn edit_point(&self, point: &mut Point, byte: &mut usize) {
138        let edit = self.into();
139        let mut ts_point = (*point).into();
140        let mut ts_byte = *byte as u32;
141
142        unsafe {
143            ffi::ts_point_edit(
144                core::ptr::addr_of_mut!(ts_point),
145                core::ptr::addr_of_mut!(ts_byte),
146                &raw const edit,
147            );
148        }
149
150        *point = ts_point.into();
151        *byte = ts_byte as usize;
152    }
153
154    /// Edit a range to keep it in-sync with source code that has been edited.
155    ///
156    /// This function updates a range's start and end positions based on this edit
157    /// operation. This is useful for editing ranges without requiring a tree
158    /// or node instance.
159    #[doc(alias = "ts_range_edit")]
160    pub fn edit_range(&self, range: &mut Range) {
161        let edit = self.into();
162        let mut ts_range = (*range).into();
163
164        unsafe {
165            ffi::ts_range_edit(core::ptr::addr_of_mut!(ts_range), &raw const edit);
166        }
167
168        *range = ts_range.into();
169    }
170}
171
172/// A single node within a syntax [`Tree`].
173#[doc(alias = "TSNode")]
174#[derive(Clone, Copy)]
175#[repr(transparent)]
176pub struct Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>);
177
178/// A stateful object that this is used to produce a [`Tree`] based on some
179/// source code.
180#[doc(alias = "TSParser")]
181pub struct Parser(NonNull<ffi::TSParser>);
182
183/// A stateful object that is used to look up symbols valid in a specific parse
184/// state
185#[doc(alias = "TSLookaheadIterator")]
186pub struct LookaheadIterator(NonNull<ffi::TSLookaheadIterator>);
187struct LookaheadNamesIterator<'a>(&'a mut LookaheadIterator);
188
189/// A stateful object that is passed into a [`ParseProgressCallback`]
190/// to pass in the current state of the parser.
191pub struct ParseState(NonNull<ffi::TSParseState>);
192
193impl ParseState {
194    #[must_use]
195    pub const fn current_byte_offset(&self) -> usize {
196        unsafe { self.0.as_ref() }.current_byte_offset as usize
197    }
198
199    #[must_use]
200    pub const fn has_error(&self) -> bool {
201        unsafe { self.0.as_ref() }.has_error
202    }
203}
204
205/// A stateful object that is passed into a [`QueryProgressCallback`]
206/// to pass in the current state of the query execution.
207pub struct QueryCursorState(NonNull<ffi::TSQueryCursorState>);
208
209impl QueryCursorState {
210    #[must_use]
211    pub const fn current_byte_offset(&self) -> usize {
212        unsafe { self.0.as_ref() }.current_byte_offset as usize
213    }
214}
215
216#[derive(Default)]
217pub struct ParseOptions<'a> {
218    pub progress_callback: Option<ParseProgressCallback<'a>>,
219}
220
221impl<'a> ParseOptions<'a> {
222    #[must_use]
223    pub fn new() -> Self {
224        Self::default()
225    }
226
227    #[must_use]
228    pub fn progress_callback<F: FnMut(&ParseState) -> ControlFlow<()>>(
229        mut self,
230        callback: &'a mut F,
231    ) -> Self {
232        self.progress_callback = Some(callback);
233        self
234    }
235
236    /// Create a new `ParseOptions` with a shorter lifetime, borrowing from this one.
237    ///
238    /// This is useful when you need to reuse parse options multiple times, e.g., calling
239    /// [`Parser::parse_with_options`] multiple times with the same options.
240    #[must_use]
241    pub fn reborrow(&mut self) -> ParseOptions {
242        ParseOptions {
243            progress_callback: match &mut self.progress_callback {
244                Some(cb) => Some(*cb),
245                None => None,
246            },
247        }
248    }
249}
250
251#[derive(Default)]
252pub struct QueryCursorOptions<'a> {
253    pub progress_callback: Option<QueryProgressCallback<'a>>,
254}
255
256impl<'a> QueryCursorOptions<'a> {
257    #[must_use]
258    pub fn new() -> Self {
259        Self::default()
260    }
261
262    #[must_use]
263    pub fn progress_callback<F: FnMut(&QueryCursorState) -> ControlFlow<()>>(
264        mut self,
265        callback: &'a mut F,
266    ) -> Self {
267        self.progress_callback = Some(callback);
268        self
269    }
270
271    /// Create a new `QueryCursorOptions` with a shorter lifetime, borrowing from this one.
272    ///
273    /// This is useful when you need to reuse query cursor options multiple times, e.g., calling
274    /// [`QueryCursor::matches`] multiple times with the same options.
275    #[must_use]
276    pub fn reborrow(&mut self) -> QueryCursorOptions {
277        QueryCursorOptions {
278            progress_callback: match &mut self.progress_callback {
279                Some(cb) => Some(*cb),
280                None => None,
281            },
282        }
283    }
284}
285
286struct QueryCursorOptionsDrop<'options>(
287    *mut ffi::TSQueryCursorOptions,
288    PhantomData<QueryProgressCallback<'options>>,
289);
290
291impl Drop for QueryCursorOptionsDrop<'_> {
292    fn drop(&mut self) {
293        unsafe {
294            if !(*self.0).payload.is_null() {
295                drop(Box::from_raw(
296                    (*self.0).payload.cast::<QueryProgressCallback>(),
297                ));
298            }
299            drop(Box::from_raw(self.0));
300        }
301    }
302}
303
304/// A type of log message.
305#[derive(Debug, PartialEq, Eq)]
306pub enum LogType {
307    Parse,
308    Lex,
309}
310
311type FieldId = NonZeroU16;
312
313/// A callback that receives log messages during parsing.
314type Logger = Box<dyn FnMut(LogType, &str) + Send + 'static>;
315
316/// A callback that receives log messages during parsing, with relaxed constraints.
317type UnsafeLogger<'a> = Box<dyn FnMut(LogType, &str) + Send + 'a>;
318
319/// A callback that receives the parse state during parsing.
320type ParseProgressCallback<'a> = &'a mut dyn FnMut(&ParseState) -> ControlFlow<()>;
321
322/// A callback that receives the query state during query execution.
323type QueryProgressCallback<'a> = &'a mut dyn FnMut(&QueryCursorState) -> ControlFlow<()>;
324
325pub trait Decode {
326    /// A callback that decodes the next code point from the input slice. It should return the code
327    /// point, and how many bytes were decoded.
328    fn decode(bytes: &[u8]) -> (i32, u32);
329}
330
331/// A stateful object for walking a syntax [`Tree`] efficiently.
332#[doc(alias = "TSTreeCursor")]
333pub struct TreeCursor<'tree>(ffi::TSTreeCursor, PhantomData<&'tree ()>);
334
335/// A set of patterns that match nodes in a syntax tree.
336#[doc(alias = "TSQuery")]
337#[derive(Debug)]
338#[expect(
339    clippy::type_complexity,
340    reason = "complex nested types are inherent to the query data model"
341)]
342pub struct Query {
343    ptr: NonNull<ffi::TSQuery>,
344    capture_names: Box<[&'static str]>,
345    capture_quantifiers: Box<[Box<[CaptureQuantifier]>]>,
346    text_predicates: Box<[Box<[TextPredicateCapture]>]>,
347    property_settings: Box<[Box<[QueryProperty]>]>,
348    property_predicates: Box<[Box<[(QueryProperty, bool)]>]>,
349    general_predicates: Box<[Box<[QueryPredicate]>]>,
350}
351
352/// A quantifier for captures
353#[derive(Debug, PartialEq, Eq, Clone, Copy)]
354pub enum CaptureQuantifier {
355    Zero,
356    ZeroOrOne,
357    ZeroOrMore,
358    One,
359    OneOrMore,
360}
361
362impl From<ffi::TSQuantifier> for CaptureQuantifier {
363    fn from(value: ffi::TSQuantifier) -> Self {
364        match value {
365            ffi::TSQuantifierZero => Self::Zero,
366            ffi::TSQuantifierZeroOrOne => Self::ZeroOrOne,
367            ffi::TSQuantifierZeroOrMore => Self::ZeroOrMore,
368            ffi::TSQuantifierOne => Self::One,
369            ffi::TSQuantifierOneOrMore => Self::OneOrMore,
370            _ => unreachable!(),
371        }
372    }
373}
374
375/// A stateful object for executing a [`Query`] on a syntax [`Tree`].
376#[doc(alias = "TSQueryCursor")]
377pub struct QueryCursor {
378    ptr: NonNull<ffi::TSQueryCursor>,
379}
380
381/// A key-value pair associated with a particular pattern in a [`Query`].
382#[derive(Debug, PartialEq, Eq)]
383pub struct QueryProperty {
384    pub key: Box<str>,
385    pub value: Option<Box<str>>,
386    pub capture_id: Option<usize>,
387}
388
389#[derive(Debug, PartialEq, Eq)]
390pub enum QueryPredicateArg {
391    Capture(u32),
392    String(Box<str>),
393}
394
395/// A key-value pair associated with a particular pattern in a [`Query`].
396#[derive(Debug, PartialEq, Eq)]
397pub struct QueryPredicate {
398    pub operator: Box<str>,
399    pub args: Box<[QueryPredicateArg]>,
400}
401
402/// A match of a [`Query`] to a particular set of [`Node`]s.
403pub struct QueryMatch<'cursor, 'tree> {
404    pub pattern_index: usize,
405    captures: &'cursor [QueryCapture<'tree>],
406    id: u32,
407    cursor: *mut ffi::TSQueryCursor,
408}
409
410/// A sequence of [`QueryMatch`]es associated with a given [`QueryCursor`].
411pub struct QueryMatches<'query, 'tree, 'options, T: TextProvider<I>, I: AsRef<[u8]>> {
412    ptr: *mut ffi::TSQueryCursor,
413    query: &'query Query,
414    text_provider: T,
415    buffer1: Vec<u8>,
416    buffer2: Vec<u8>,
417    current_match: Option<QueryMatch<'query, 'tree>>,
418    _options: Option<QueryCursorOptionsDrop<'options>>,
419    _phantom: PhantomData<(&'tree (), I)>,
420}
421
422/// A sequence of [`QueryCapture`]s associated with a given [`QueryCursor`].
423///
424/// During iteration, each element contains a [`QueryMatch`] and index. The index can
425/// be used to access the new capture inside of the [`QueryMatch::captures`]'s [`captures`].
426pub struct QueryCaptures<'query, 'tree, 'options, T: TextProvider<I>, I: AsRef<[u8]>> {
427    ptr: *mut ffi::TSQueryCursor,
428    query: &'query Query,
429    text_provider: T,
430    buffer1: Vec<u8>,
431    buffer2: Vec<u8>,
432    current_match: Option<(QueryMatch<'query, 'tree>, usize)>,
433    _options: Option<QueryCursorOptionsDrop<'options>>,
434    _phantom: PhantomData<(&'tree (), I)>,
435}
436
437pub trait TextProvider<I>
438where
439    I: AsRef<[u8]>,
440{
441    type I: Iterator<Item = I>;
442    fn text(&mut self, node: Node) -> Self::I;
443}
444
445/// A particular [`Node`] that has been captured with a particular name within a
446/// [`Query`].
447#[derive(Clone, Copy, Debug)]
448#[repr(C)]
449pub struct QueryCapture<'tree> {
450    pub node: Node<'tree>,
451    pub index: u32,
452}
453
454/// An error that occurred when trying to assign a [`Language`] to a [`Parser`].
455/// If the `wasm` feature is enabled, this can also indicate a failure to load
456/// the Wasm store.
457#[derive(Debug, PartialEq, Eq)]
458pub enum LanguageError {
459    Version(usize),
460    NotParseable,
461    #[cfg(feature = "wasm")]
462    Wasm,
463}
464
465/// An error that occurred in [`Parser::set_included_ranges`].
466#[derive(Debug, PartialEq, Eq)]
467pub struct IncludedRangesError(pub usize);
468
469/// An error that occurred when trying to create a [`Query`].
470#[derive(Debug, PartialEq, Eq)]
471pub struct QueryError {
472    pub row: usize,
473    pub column: usize,
474    pub offset: usize,
475    pub message: String,
476    pub kind: QueryErrorKind,
477}
478
479#[derive(Debug, PartialEq, Eq)]
480pub enum QueryErrorKind {
481    Syntax,
482    NodeType,
483    Field,
484    Capture,
485    Predicate,
486    Structure,
487    Language,
488}
489
490#[derive(Debug)]
491/// The first item is the capture index
492/// The next is capture specific, depending on what item is expected
493/// The first bool is if the capture is positive
494/// The last item is a bool signifying whether or not it's meant to match
495/// any or all captures
496enum TextPredicateCapture {
497    EqString(u32, Box<str>, bool, bool),
498    EqCapture(u32, u32, bool, bool),
499    MatchString(u32, regex::bytes::Regex, bool, bool),
500    AnyString(u32, Box<[Box<str>]>, bool),
501}
502
503// TODO: Remove this struct at some point. If `core::str::lossy::Utf8Lossy`
504// is ever stabilized.
505pub struct LossyUtf8<'a> {
506    bytes: &'a [u8],
507    in_replacement: bool,
508}
509
510impl Language {
511    #[must_use]
512    pub fn new(builder: LanguageFn) -> Self {
513        Self(unsafe { builder.into_raw()().cast() })
514    }
515
516    /// Check whether this language can be assigned to a parser.
517    ///
518    /// When Tree-sitter is compiled to WebAssembly, languages obtained from a
519    /// syntax tree can be used for parsing only within the same WebAssembly
520    /// instance that created the tree. In other instances, such languages can
521    /// still be used to inspect syntax trees.
522    #[doc(alias = "ts_language_is_parseable")]
523    #[must_use]
524    pub fn is_parseable(&self) -> bool {
525        unsafe { ffi::ts_language_is_parseable(self.0) }
526    }
527
528    /// Get the name of this language. This returns `None` for a language with
529    /// another ABI version.
530    #[doc(alias = "ts_language_name")]
531    #[must_use]
532    pub fn name(&self) -> Option<&str> {
533        let ptr = unsafe { ffi::ts_language_name(self.0) };
534        (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
535    }
536
537    /// Get the ABI version number of this [`Language`].
538    ///
539    /// The library loads only languages whose number is from
540    /// [`MIN_COMPATIBLE_LANGUAGE_VERSION`] to [`LANGUAGE_VERSION`], which the CLI
541    /// of this fork assigns. Any other number comes from a parser
542    /// that another CLI generated.
543    #[doc(alias = "ts_language_abi_version")]
544    #[must_use]
545    pub fn abi_version(&self) -> usize {
546        unsafe { ffi::ts_language_abi_version(self.0) as usize }
547    }
548
549    /// Get the metadata for this language. This information is generated by the
550    /// CLI, and relies on the language author providing the correct metadata in
551    /// the language's `tree-sitter.json` file. This returns `None` for a
552    /// language with another ABI version.
553    ///
554    /// See also [`LanguageMetadata`].
555    #[doc(alias = "ts_language_metadata")]
556    #[must_use]
557    pub fn metadata(&self) -> Option<LanguageMetadata> {
558        unsafe {
559            let ptr = ffi::ts_language_metadata(self.0);
560            (!ptr.is_null()).then(|| (*ptr).into())
561        }
562    }
563
564    /// Get the number of distinct node types in this language.
565    #[doc(alias = "ts_language_symbol_count")]
566    #[must_use]
567    pub fn node_kind_count(&self) -> usize {
568        unsafe { ffi::ts_language_symbol_count(self.0) as usize }
569    }
570
571    /// Get the number of valid states in this language.
572    #[doc(alias = "ts_language_state_count")]
573    #[must_use]
574    pub fn parse_state_count(&self) -> usize {
575        unsafe { ffi::ts_language_state_count(self.0) as usize }
576    }
577
578    /// Get a list of all supertype symbols for the language. The list is empty
579    /// for a language with another ABI version.
580    #[doc(alias = "ts_language_supertypes")]
581    #[must_use]
582    pub fn supertypes(&self) -> &[u16] {
583        let mut length = 0u32;
584        unsafe {
585            let ptr = ffi::ts_language_supertypes(self.0, core::ptr::addr_of_mut!(length));
586            if length == 0 {
587                &[]
588            } else {
589                slice::from_raw_parts(ptr.cast_mut(), length as usize)
590            }
591        }
592    }
593
594    /// Get a list of all subtype symbols for a given supertype symbol. The list
595    /// is empty for a language with another ABI version.
596    #[doc(alias = "ts_language_supertype_map")]
597    #[must_use]
598    pub fn subtypes_for_supertype(&self, supertype: u16) -> &[u16] {
599        unsafe {
600            let mut length = 0u32;
601            let ptr = ffi::ts_language_subtypes(self.0, supertype, core::ptr::addr_of_mut!(length));
602            if length == 0 {
603                &[]
604            } else {
605                slice::from_raw_parts(ptr.cast_mut(), length as usize)
606            }
607        }
608    }
609
610    /// Get the name of the node kind for the given numerical id.
611    #[doc(alias = "ts_language_symbol_name")]
612    #[must_use]
613    pub fn node_kind_for_id(&self, id: u16) -> Option<&str> {
614        let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
615        (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
616    }
617
618    /// Get the numeric id for the given node kind.
619    #[doc(alias = "ts_language_symbol_for_name")]
620    #[must_use]
621    pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
622        unsafe {
623            ffi::ts_language_symbol_for_name(
624                self.0,
625                kind.as_bytes().as_ptr().cast::<c_char>(),
626                kind.len() as u32,
627                named,
628            )
629        }
630    }
631
632    /// Check whether `id` can be used to index this language's symbol tables.
633    ///
634    /// `ts_symbol_metadata` holds one entry per grammar symbol plus one per alias,
635    /// so [`Self::node_kind_count`] is an exact bound. `ERROR` and `_ERROR` sit
636    /// at the top of the `u16` range and are handled by the C library before any
637    /// table lookup.
638    fn node_kind_id_is_valid(&self, id: u16) -> bool {
639        (id as usize) < self.node_kind_count() || id >= u16::MAX - 1
640    }
641
642    /// Check if the node type for the given numerical id is named (as opposed
643    /// to an anonymous node type).
644    #[must_use]
645    pub fn node_kind_is_named(&self, id: u16) -> bool {
646        self.node_kind_id_is_valid(id)
647            && unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeRegular }
648    }
649
650    /// Check if the node type for the given numerical id is visible (as opposed
651    /// to a hidden node type).
652    #[must_use]
653    pub fn node_kind_is_visible(&self, id: u16) -> bool {
654        self.node_kind_id_is_valid(id)
655            && unsafe { ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolTypeAnonymous }
656    }
657
658    /// Check if the node type for the given numerical id is a supertype.
659    #[must_use]
660    pub fn node_kind_is_supertype(&self, id: u16) -> bool {
661        self.node_kind_id_is_valid(id)
662            && unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeSupertype }
663    }
664
665    /// Get the number of distinct field names in this language.
666    #[doc(alias = "ts_language_field_count")]
667    #[must_use]
668    pub fn field_count(&self) -> usize {
669        unsafe { ffi::ts_language_field_count(self.0) as usize }
670    }
671
672    /// Get the field name for the given numerical id.
673    #[doc(alias = "ts_language_field_name_for_id")]
674    #[must_use]
675    pub fn field_name_for_id(&self, field_id: u16) -> Option<&str> {
676        let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
677        (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
678    }
679
680    /// Get the numerical id for the given field name.
681    #[doc(alias = "ts_language_field_id_for_name")]
682    #[must_use]
683    pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId> {
684        let field_name = field_name.as_ref();
685        let id = unsafe {
686            ffi::ts_language_field_id_for_name(
687                self.0,
688                field_name.as_ptr().cast::<c_char>(),
689                field_name.len() as u32,
690            )
691        };
692        FieldId::new(id)
693    }
694
695    /// Get the next parse state. Combine this with
696    /// [`lookahead_iterator`](Language::lookahead_iterator) to
697    /// generate completion suggestions or valid symbols in error nodes.
698    ///
699    /// Example:
700    /// ```ignore
701    /// let state = language.next_state(node.parse_state(), node.grammar_id());
702    /// ```
703    #[doc(alias = "ts_language_next_state")]
704    #[must_use]
705    pub fn next_state(&self, state: u16, id: u16) -> u16 {
706        unsafe { ffi::ts_language_next_state(self.0, state, id) }
707    }
708
709    /// Create a new lookahead iterator for this language and parse state.
710    ///
711    /// This returns `None` if state is invalid for this language.
712    ///
713    /// Iterating [`LookaheadIterator`] will yield valid symbols in the given
714    /// parse state. A newly created iterator is not positioned on a symbol, so
715    /// [`LookaheadIterator::current_symbol`] returns `None` until the first
716    /// [`Iterator::next`] call.
717    ///
718    /// The iterator retains the language, so the language may be dropped while
719    /// the iterator is still in use.
720    ///
721    /// Lookahead iterators can be useful to generate suggestions and improve
722    /// syntax error diagnostics. To get symbols valid in an `ERROR` node, use the
723    /// lookahead iterator on its first leaf node state. For a missing node, use
724    /// the node's [`parse_state`](Node::parse_state). Keep in mind that lookahead
725    /// symbols are valid in that parse state, but are not necessarily valid
726    /// continuations in the context of the actual following token or guaranteed
727    /// to be considered during error recovery.
728    #[doc(alias = "ts_lookahead_iterator_new")]
729    #[must_use]
730    pub fn lookahead_iterator(&self, state: u16) -> Option<LookaheadIterator> {
731        let ptr = unsafe { ffi::ts_lookahead_iterator_new(self.0, state) };
732        (!ptr.is_null()).then(|| unsafe { LookaheadIterator::from_raw(ptr) })
733    }
734}
735
736impl From<LanguageFn> for Language {
737    fn from(value: LanguageFn) -> Self {
738        Self::new(value)
739    }
740}
741
742impl Clone for Language {
743    fn clone(&self) -> Self {
744        unsafe { Self(ffi::ts_language_copy(self.0)) }
745    }
746}
747
748impl Drop for Language {
749    fn drop(&mut self) {
750        unsafe { ffi::ts_language_delete(self.0) }
751    }
752}
753
754impl Deref for LanguageRef<'_> {
755    type Target = Language;
756
757    fn deref(&self) -> &Self::Target {
758        unsafe { &*(core::ptr::addr_of!(self.0).cast::<Language>()) }
759    }
760}
761
762impl Default for Parser {
763    fn default() -> Self {
764        Self::new()
765    }
766}
767
768impl Parser {
769    /// Create a new parser.
770    #[doc(alias = "ts_parser_new")]
771    #[must_use]
772    pub fn new() -> Self {
773        unsafe {
774            let parser = ffi::ts_parser_new();
775            Self(NonNull::new_unchecked(parser))
776        }
777    }
778
779    /// Set the language that the parser should use for parsing.
780    ///
781    /// Returns a Result indicating whether or not the language was successfully
782    /// assigned. Assignment fails if the language cannot be used for parsing,
783    /// or if it was generated with an incompatible version of the Tree-sitter
784    /// CLI. Check this using [`Language::is_parseable`] and
785    /// [`Language::abi_version`].
786    #[doc(alias = "ts_parser_set_language")]
787    pub fn set_language(&mut self, language: &Language) -> Result<(), LanguageError> {
788        let version = language.abi_version();
789        if (MIN_COMPATIBLE_LANGUAGE_VERSION..=LANGUAGE_VERSION).contains(&version) {
790            if !language.is_parseable() {
791                return Err(LanguageError::NotParseable);
792            }
793            #[cfg_attr(
794                not(feature = "wasm"),
795                expect(unused_variables, reason = "only used when wasm feature is enabled")
796            )]
797            let success = unsafe { ffi::ts_parser_set_language(self.0.as_ptr(), language.0) };
798            #[cfg(feature = "wasm")]
799            if !success {
800                return Err(LanguageError::Wasm);
801            }
802            Ok(())
803        } else {
804            Err(LanguageError::Version(version))
805        }
806    }
807
808    /// Get the parser's current language.
809    #[doc(alias = "ts_parser_language")]
810    #[must_use]
811    pub fn language(&self) -> Option<LanguageRef<'_>> {
812        let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
813        (!ptr.is_null()).then_some(LanguageRef(ptr, PhantomData))
814    }
815
816    /// Get the parser's current logger.
817    #[doc(alias = "ts_parser_logger")]
818    #[must_use]
819    pub fn logger(&self) -> Option<&Logger> {
820        let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
821        unsafe { logger.payload.cast::<Logger>().as_ref() }
822    }
823
824    /// Set the logging callback that the parser should use during parsing.
825    ///
826    /// To log through a callback that borrows non-`'static` data, see
827    /// [`set_logger_unchecked`](Parser::set_logger_unchecked).
828    #[doc(alias = "ts_parser_set_logger")]
829    pub fn set_logger(&mut self, logger: Option<Logger>) {
830        // SAFETY: `Logger` is `Send + 'static`
831        unsafe { self.set_logger_unchecked(logger) };
832    }
833
834    /// Set the logging callback, allowing the callback to borrow non-`'static`
835    /// data. See [`set_logger`](Parser::set_logger).
836    ///
837    /// # Safety
838    ///
839    /// Any data borrowed by `logger` must remain valid until the logger is
840    /// removed. Equivalently, the parser must not be used to parse once the
841    /// borrowed data has gone out of scope.
842    pub unsafe fn set_logger_unchecked(&mut self, logger: Option<UnsafeLogger<'_>>) {
843        let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
844        if !prev_logger.payload.is_null() {
845            drop(unsafe { Box::from_raw(prev_logger.payload.cast::<Logger>()) });
846        }
847
848        let c_logger = if let Some(logger) = logger {
849            let container = Box::new(logger);
850
851            unsafe extern "C" fn log(
852                payload: *mut c_void,
853                c_log_type: ffi::TSLogType,
854                c_message: *const c_char,
855            ) {
856                unsafe {
857                    let callback = payload.cast::<Logger>().as_mut().unwrap();
858                    if let Ok(message) = CStr::from_ptr(c_message).to_str() {
859                        let log_type = if c_log_type == ffi::TSLogTypeParse {
860                            LogType::Parse
861                        } else {
862                            LogType::Lex
863                        };
864                        callback(log_type, message);
865                    }
866                }
867            }
868
869            let raw_container = Box::into_raw(container);
870
871            ffi::TSLogger {
872                payload: raw_container.cast::<c_void>(),
873                log: Some(log),
874            }
875        } else {
876            ffi::TSLogger {
877                payload: ptr::null_mut(),
878                log: None,
879            }
880        };
881
882        unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
883    }
884
885    /// Set the destination to which the parser should write debugging graphs
886    /// during parsing. The graphs are formatted in the DOT language. You may
887    /// want to pipe these graphs directly to a `dot(1)` process in order to
888    /// generate SVG output.
889    #[doc(alias = "ts_parser_print_dot_graphs")]
890    #[cfg(not(target_os = "wasi"))]
891    #[cfg(feature = "std")]
892    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
893    pub fn print_dot_graphs(
894        &mut self,
895        #[cfg(unix)] file: &impl AsRawFd,
896        #[cfg(windows)] file: &impl AsRawHandle,
897    ) {
898        #[cfg(unix)]
899        {
900            let fd = file.as_raw_fd();
901            unsafe {
902                ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(fd));
903            }
904        }
905
906        #[cfg(windows)]
907        {
908            let handle = file.as_raw_handle();
909            unsafe {
910                ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(handle));
911            }
912        }
913    }
914
915    /// Stop the parser from printing debugging graphs while parsing.
916    #[doc(alias = "ts_parser_print_dot_graphs")]
917    #[cfg(not(target_os = "wasi"))]
918    #[cfg(feature = "std")]
919    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
920    pub fn stop_printing_dot_graphs(&mut self) {
921        unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
922    }
923
924    /// Parse a slice of UTF8 text.
925    ///
926    /// # Arguments:
927    /// * `text` The UTF8-encoded text to parse.
928    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
929    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
930    ///   the new text using [`Tree::edit`].
931    ///
932    /// Returns a [`Tree`] if parsing succeeded, or `None` if:
933    ///  * The parser has not yet had a language assigned with [`Parser::set_language`]
934    #[doc(alias = "ts_parser_parse")]
935    pub fn parse(&mut self, text: impl AsRef<[u8]>, old_tree: Option<&Tree>) -> Option<Tree> {
936        let bytes = text.as_ref();
937        let len = bytes.len();
938        self.parse_with_options(
939            &mut |i, _| {
940                if i < len {
941                    &bytes[i..]
942                } else {
943                    Default::default()
944                }
945            },
946            old_tree,
947            None,
948        )
949    }
950
951    /// Parse text provided in chunks by a callback.
952    ///
953    /// # Arguments:
954    /// * `callback` A function that takes a byte offset and position and returns a slice of
955    ///   UTF8-encoded text starting at that byte offset and position. The slices can be of any
956    ///   length. If the given position is at the end of the text, the callback should return an
957    ///   empty slice.
958    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
959    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
960    ///   the new text using [`Tree::edit`].
961    /// * `options` Options for parsing the text. This can be used to set a progress callback.
962    pub fn parse_with_options<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
963        &mut self,
964        callback: &mut F,
965        old_tree: Option<&Tree>,
966        options: Option<ParseOptions>,
967    ) -> Option<Tree> {
968        type Payload<'a, F, T> = (&'a mut F, Option<T>);
969
970        // This C function is passed to Tree-sitter as the progress callback.
971        unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
972            unsafe {
973                let callback = (*state)
974                    .payload
975                    .cast::<ParseProgressCallback>()
976                    .as_mut()
977                    .unwrap();
978                match callback(&ParseState::from_raw(state)) {
979                    ControlFlow::Continue(()) => false,
980                    ControlFlow::Break(()) => true,
981                }
982            }
983        }
984
985        // This C function is passed to Tree-sitter as the input callback.
986        unsafe extern "C" fn read<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
987            payload: *mut c_void,
988            byte_offset: u32,
989            position: ffi::TSPoint,
990            bytes_read: *mut u32,
991        ) -> *const c_char {
992            unsafe {
993                let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
994                *text = Some(callback(byte_offset as usize, position.into()));
995                let slice = text.as_ref().unwrap().as_ref();
996                *bytes_read = slice.len() as u32;
997                slice.as_ptr().cast::<c_char>()
998            }
999        }
1000
1001        let empty_options = ffi::TSParseOptions {
1002            payload: ptr::null_mut(),
1003            progress_callback: None,
1004        };
1005
1006        let mut callback_ptr;
1007        let parse_options = if let Some(options) = options {
1008            if let Some(cb) = options.progress_callback {
1009                callback_ptr = cb;
1010                ffi::TSParseOptions {
1011                    payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1012                    progress_callback: Some(progress),
1013                }
1014            } else {
1015                empty_options
1016            }
1017        } else {
1018            empty_options
1019        };
1020
1021        // A pointer to this payload is passed on every call to the `read` C function.
1022        // The payload contains two things:
1023        // 1. A reference to the rust `callback`.
1024        // 2. The text that was returned from the previous call to `callback`. This allows the
1025        //    callback to return owned values like vectors.
1026        let mut payload: Payload<F, T> = (callback, None);
1027
1028        let c_input = ffi::TSInput {
1029            payload: ptr::addr_of_mut!(payload).cast::<c_void>(),
1030            read: Some(read::<T, F>),
1031            encoding: ffi::TSInputEncodingUTF8,
1032            decode: None,
1033        };
1034
1035        let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1036        unsafe {
1037            let c_new_tree = ffi::ts_parser_parse_with_options(
1038                self.0.as_ptr(),
1039                c_old_tree,
1040                c_input,
1041                parse_options,
1042            );
1043
1044            NonNull::new(c_new_tree).map(Tree)
1045        }
1046    }
1047
1048    /// Parse a slice of UTF16 little-endian text.
1049    ///
1050    /// # Arguments:
1051    /// * `text` The UTF16-encoded text to parse.
1052    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
1053    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
1054    ///   the new text using [`Tree::edit`].
1055    pub fn parse_utf16_le(
1056        &mut self,
1057        input: impl AsRef<[u16]>,
1058        old_tree: Option<&Tree>,
1059    ) -> Option<Tree> {
1060        let code_points = input.as_ref();
1061        let len = code_points.len();
1062        self.parse_utf16_le_with_options(
1063            &mut |i, _| {
1064                if i < len {
1065                    &code_points[i..]
1066                } else {
1067                    Default::default()
1068                }
1069            },
1070            old_tree,
1071            None,
1072        )
1073    }
1074
1075    /// Parse UTF16 little-endian text provided in chunks by a callback.
1076    ///
1077    /// # Arguments:
1078    /// * `callback` A function that takes a code point offset and position and returns a slice of
1079    ///   UTF16-encoded text starting at that byte offset and position. The slices can be of any
1080    ///   length. If the given position is at the end of the text, the callback should return an
1081    ///   empty slice.
1082    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
1083    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
1084    ///   the new text using [`Tree::edit`].
1085    /// * `options` Options for parsing the text. This can be used to set a progress callback.
1086    pub fn parse_utf16_le_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1087        &mut self,
1088        callback: &mut F,
1089        old_tree: Option<&Tree>,
1090        options: Option<ParseOptions>,
1091    ) -> Option<Tree> {
1092        type Payload<'a, F, T> = (&'a mut F, Option<T>);
1093
1094        unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
1095            unsafe {
1096                let callback = (*state)
1097                    .payload
1098                    .cast::<ParseProgressCallback>()
1099                    .as_mut()
1100                    .unwrap();
1101                match callback(&ParseState::from_raw(state)) {
1102                    ControlFlow::Continue(()) => false,
1103                    ControlFlow::Break(()) => true,
1104                }
1105            }
1106        }
1107
1108        // This C function is passed to Tree-sitter as the input callback.
1109        unsafe extern "C" fn read<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1110            payload: *mut c_void,
1111            byte_offset: u32,
1112            position: ffi::TSPoint,
1113            bytes_read: *mut u32,
1114        ) -> *const c_char {
1115            unsafe {
1116                let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
1117                *text = Some(callback(
1118                    (byte_offset / 2) as usize,
1119                    Point {
1120                        row: position.row as usize,
1121                        column: position.column as usize / 2,
1122                    },
1123                ));
1124                let slice = text.as_ref().unwrap().as_ref();
1125                *bytes_read = slice.len() as u32 * 2;
1126                slice.as_ptr().cast::<c_char>()
1127            }
1128        }
1129
1130        let empty_options = ffi::TSParseOptions {
1131            payload: ptr::null_mut(),
1132            progress_callback: None,
1133        };
1134
1135        let mut callback_ptr;
1136        let parse_options = if let Some(options) = options {
1137            if let Some(cb) = options.progress_callback {
1138                callback_ptr = cb;
1139                ffi::TSParseOptions {
1140                    payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1141                    progress_callback: Some(progress),
1142                }
1143            } else {
1144                empty_options
1145            }
1146        } else {
1147            empty_options
1148        };
1149
1150        // A pointer to this payload is passed on every call to the `read` C function.
1151        // The payload contains two things:
1152        // 1. A reference to the rust `callback`.
1153        // 2. The text that was returned from the previous call to `callback`. This allows the
1154        //    callback to return owned values like vectors.
1155        let mut payload: Payload<F, T> = (callback, None);
1156
1157        let c_input = ffi::TSInput {
1158            payload: core::ptr::addr_of_mut!(payload).cast::<c_void>(),
1159            read: Some(read::<T, F>),
1160            encoding: ffi::TSInputEncodingUTF16LE,
1161            decode: None,
1162        };
1163
1164        let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1165        unsafe {
1166            let c_new_tree = ffi::ts_parser_parse_with_options(
1167                self.0.as_ptr(),
1168                c_old_tree,
1169                c_input,
1170                parse_options,
1171            );
1172
1173            NonNull::new(c_new_tree).map(Tree)
1174        }
1175    }
1176
1177    /// Parse a slice of UTF16 big-endian text.
1178    ///
1179    /// # Arguments:
1180    /// * `text` The UTF16-encoded text to parse.
1181    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
1182    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
1183    ///   the new text using [`Tree::edit`].
1184    pub fn parse_utf16_be(
1185        &mut self,
1186        input: impl AsRef<[u16]>,
1187        old_tree: Option<&Tree>,
1188    ) -> Option<Tree> {
1189        let code_points = input.as_ref();
1190        let len = code_points.len();
1191        self.parse_utf16_be_with_options(
1192            &mut |i, _| if i < len { &code_points[i..] } else { &[] },
1193            old_tree,
1194            None,
1195        )
1196    }
1197
1198    /// Parse UTF16 big-endian text provided in chunks by a callback.
1199    ///
1200    /// # Arguments:
1201    /// * `callback` A function that takes a code point offset and position and returns a slice of
1202    ///   UTF16-encoded text starting at that byte offset and position. The slices can be of any
1203    ///   length. If the given position is at the end of the text, the callback should return an
1204    ///   empty slice.
1205    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
1206    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
1207    ///   the new text using [`Tree::edit`].
1208    /// * `options` Options for parsing the text. This can be used to set a progress callback.
1209    pub fn parse_utf16_be_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1210        &mut self,
1211        callback: &mut F,
1212        old_tree: Option<&Tree>,
1213        options: Option<ParseOptions>,
1214    ) -> Option<Tree> {
1215        type Payload<'a, F, T> = (&'a mut F, Option<T>);
1216
1217        // This C function is passed to Tree-sitter as the progress callback.
1218        unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
1219            unsafe {
1220                let callback = (*state)
1221                    .payload
1222                    .cast::<ParseProgressCallback>()
1223                    .as_mut()
1224                    .unwrap();
1225                match callback(&ParseState::from_raw(state)) {
1226                    ControlFlow::Continue(()) => false,
1227                    ControlFlow::Break(()) => true,
1228                }
1229            }
1230        }
1231
1232        // This C function is passed to Tree-sitter as the input callback.
1233        unsafe extern "C" fn read<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1234            payload: *mut c_void,
1235            byte_offset: u32,
1236            position: ffi::TSPoint,
1237            bytes_read: *mut u32,
1238        ) -> *const c_char {
1239            unsafe {
1240                let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
1241                *text = Some(callback(
1242                    (byte_offset / 2) as usize,
1243                    Point {
1244                        row: position.row as usize,
1245                        column: position.column as usize / 2,
1246                    },
1247                ));
1248                let slice = text.as_ref().unwrap().as_ref();
1249                *bytes_read = slice.len() as u32 * 2;
1250                slice.as_ptr().cast::<c_char>()
1251            }
1252        }
1253
1254        let empty_options = ffi::TSParseOptions {
1255            payload: ptr::null_mut(),
1256            progress_callback: None,
1257        };
1258
1259        let mut callback_ptr;
1260        let parse_options = if let Some(options) = options {
1261            if let Some(cb) = options.progress_callback {
1262                callback_ptr = cb;
1263                ffi::TSParseOptions {
1264                    payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1265                    progress_callback: Some(progress),
1266                }
1267            } else {
1268                empty_options
1269            }
1270        } else {
1271            empty_options
1272        };
1273
1274        // A pointer to this payload is passed on every call to the `read` C function.
1275        // The payload contains two things:
1276        // 1. A reference to the rust `callback`.
1277        // 2. The text that was returned from the previous call to `callback`. This allows the
1278        //    callback to return owned values like vectors.
1279        let mut payload: Payload<F, T> = (callback, None);
1280
1281        let c_input = ffi::TSInput {
1282            payload: core::ptr::addr_of_mut!(payload).cast::<c_void>(),
1283            read: Some(read::<T, F>),
1284            encoding: ffi::TSInputEncodingUTF16BE,
1285            decode: None,
1286        };
1287
1288        let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1289        unsafe {
1290            let c_new_tree = ffi::ts_parser_parse_with_options(
1291                self.0.as_ptr(),
1292                c_old_tree,
1293                c_input,
1294                parse_options,
1295            );
1296
1297            NonNull::new(c_new_tree).map(Tree)
1298        }
1299    }
1300
1301    /// Parse text provided in chunks by a callback using a custom encoding.
1302    /// This is useful for parsing text in encodings that are not UTF-8 or UTF-16.
1303    ///
1304    /// # Arguments:
1305    /// * `callback` A function that takes a byte offset and position and returns a slice of text
1306    ///   starting at that byte offset and position. The slices can be of any length. If the given
1307    ///   position is at the end of the text, the callback should return an empty slice.
1308    /// * `old_tree` A previous syntax tree parsed from the same document. If the text of the
1309    ///   document has changed since `old_tree` was created, then you must edit `old_tree` to match
1310    ///   the new text using [`Tree::edit`].
1311    /// * `options` Options for parsing the text. This can be used to set a progress callback.
1312    ///
1313    /// Additionally, you must set the generic parameter [`D`] to a type that implements the
1314    /// [`Decode`] trait. This trait has a single method, [`decode`](Decode::decode), which takes a
1315    /// slice of bytes and returns a tuple of the code point and the number of bytes consumed.
1316    /// The `decode` method should return `-1` for the code point if decoding fails.
1317    pub fn parse_custom_encoding<D: Decode, T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
1318        &mut self,
1319        callback: &mut F,
1320        old_tree: Option<&Tree>,
1321        options: Option<ParseOptions>,
1322    ) -> Option<Tree> {
1323        type Payload<'a, F, T> = (&'a mut F, Option<T>);
1324
1325        unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
1326            unsafe {
1327                let callback = (*state)
1328                    .payload
1329                    .cast::<ParseProgressCallback>()
1330                    .as_mut()
1331                    .unwrap();
1332                match callback(&ParseState::from_raw(state)) {
1333                    ControlFlow::Continue(()) => false,
1334                    ControlFlow::Break(()) => true,
1335                }
1336            }
1337        }
1338
1339        // At compile time, create a C-compatible callback that calls the custom `decode` method.
1340        unsafe extern "C" fn decode_fn<D: Decode>(
1341            data: *const u8,
1342            len: u32,
1343            code_point: *mut i32,
1344        ) -> u32 {
1345            unsafe {
1346                let (c, len) = D::decode(core::slice::from_raw_parts(data, len as usize));
1347                if let Some(code_point) = code_point.as_mut() {
1348                    *code_point = c;
1349                }
1350                len
1351            }
1352        }
1353
1354        // This C function is passed to Tree-sitter as the input callback.
1355        unsafe extern "C" fn read<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
1356            payload: *mut c_void,
1357            byte_offset: u32,
1358            position: ffi::TSPoint,
1359            bytes_read: *mut u32,
1360        ) -> *const c_char {
1361            unsafe {
1362                let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
1363                *text = Some(callback(byte_offset as usize, position.into()));
1364                let slice = text.as_ref().unwrap().as_ref();
1365                *bytes_read = slice.len() as u32;
1366                slice.as_ptr().cast::<c_char>()
1367            }
1368        }
1369
1370        let empty_options = ffi::TSParseOptions {
1371            payload: ptr::null_mut(),
1372            progress_callback: None,
1373        };
1374
1375        let mut callback_ptr;
1376        let parse_options = if let Some(options) = options {
1377            if let Some(cb) = options.progress_callback {
1378                callback_ptr = cb;
1379                ffi::TSParseOptions {
1380                    payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1381                    progress_callback: Some(progress),
1382                }
1383            } else {
1384                empty_options
1385            }
1386        } else {
1387            empty_options
1388        };
1389
1390        // A pointer to this payload is passed on every call to the `read` C function.
1391        // The payload contains two things:
1392        // 1. A reference to the rust `callback`.
1393        // 2. The text that was returned from the previous call to `callback`. This allows the
1394        //    callback to return owned values like vectors.
1395        let mut payload: Payload<F, T> = (callback, None);
1396
1397        let c_input = ffi::TSInput {
1398            payload: core::ptr::addr_of_mut!(payload).cast::<c_void>(),
1399            read: Some(read::<T, F>),
1400            encoding: ffi::TSInputEncodingCustom,
1401            // Use this custom decode callback
1402            decode: Some(decode_fn::<D>),
1403        };
1404
1405        let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1406        unsafe {
1407            let c_new_tree = ffi::ts_parser_parse_with_options(
1408                self.0.as_ptr(),
1409                c_old_tree,
1410                c_input,
1411                parse_options,
1412            );
1413
1414            NonNull::new(c_new_tree).map(Tree)
1415        }
1416    }
1417
1418    /// Instruct the parser to start the next parse from the beginning.
1419    ///
1420    /// If the parser previously failed because of a callback, then by default,
1421    /// it will resume where it left off on the next call to [`parse`](Parser::parse)
1422    /// or other parsing functions. If you don't want to resume, and instead intend to use
1423    /// this parser to parse some other document, you must call `reset` first.
1424    #[doc(alias = "ts_parser_reset")]
1425    pub fn reset(&mut self) {
1426        unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
1427    }
1428
1429    /// Set the ranges of text that the parser should include when parsing.
1430    ///
1431    /// By default, the parser will always include entire documents. This
1432    /// function allows you to parse only a *portion* of a document but
1433    /// still return a syntax tree whose ranges match up with the document
1434    /// as a whole. You can also pass multiple disjoint ranges.
1435    ///
1436    /// If `ranges` is empty, then the entire document will be parsed.
1437    /// Otherwise, the given ranges must be ordered from earliest to latest
1438    /// in the document, and they must not overlap. That is, the following
1439    /// must hold for all `i` < `length - 1`:
1440    /// ```text
1441    ///     ranges[i].end_byte <= ranges[i + 1].start_byte
1442    /// ```
1443    /// If this requirement is not satisfied, method will return
1444    /// [`IncludedRangesError`] error with an offset in the passed ranges
1445    /// slice pointing to a first incorrect range.
1446    #[doc(alias = "ts_parser_set_included_ranges")]
1447    pub fn set_included_ranges(&mut self, ranges: &[Range]) -> Result<(), IncludedRangesError> {
1448        let ts_ranges = ranges.iter().copied().map(Into::into).collect::<Vec<_>>();
1449        let result = unsafe {
1450            ffi::ts_parser_set_included_ranges(
1451                self.0.as_ptr(),
1452                ts_ranges.as_ptr(),
1453                ts_ranges.len() as u32,
1454            )
1455        };
1456
1457        if result {
1458            Ok(())
1459        } else {
1460            let mut prev_end_byte = 0;
1461            for (i, range) in ranges.iter().enumerate() {
1462                if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
1463                    return Err(IncludedRangesError(i));
1464                }
1465                prev_end_byte = range.end_byte;
1466            }
1467            Err(IncludedRangesError(0))
1468        }
1469    }
1470
1471    /// Get the ranges of text that the parser will include when parsing.
1472    #[doc(alias = "ts_parser_included_ranges")]
1473    #[must_use]
1474    pub fn included_ranges(&self) -> Vec<Range> {
1475        let mut count = 0u32;
1476        unsafe {
1477            let ptr =
1478                ffi::ts_parser_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
1479            let ranges = slice::from_raw_parts(ptr, count as usize);
1480            ranges.iter().copied().map(Into::into).collect()
1481        }
1482    }
1483}
1484
1485impl Drop for Parser {
1486    fn drop(&mut self) {
1487        #[cfg(feature = "std")]
1488        #[cfg(not(target_os = "wasi"))]
1489        {
1490            self.stop_printing_dot_graphs();
1491        }
1492        self.set_logger(None);
1493        unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
1494    }
1495}
1496
1497#[cfg(windows)]
1498unsafe extern "C" {
1499    fn _open_osfhandle(osfhandle: isize, flags: core::ffi::c_int) -> core::ffi::c_int;
1500}
1501
1502impl Tree {
1503    /// Get the root node of the syntax tree.
1504    #[doc(alias = "ts_tree_root_node")]
1505    #[must_use]
1506    pub fn root_node(&self) -> Node {
1507        Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
1508    }
1509
1510    /// Get the root node of the syntax tree, but with its position shifted
1511    /// forward by the given offset.
1512    #[doc(alias = "ts_tree_root_node_with_offset")]
1513    #[must_use]
1514    pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
1515        Node::new(unsafe {
1516            ffi::ts_tree_root_node_with_offset(
1517                self.0.as_ptr(),
1518                offset_bytes as u32,
1519                offset_extent.into(),
1520            )
1521        })
1522        .unwrap()
1523    }
1524
1525    /// Get the language that was used to parse the syntax tree.
1526    ///
1527    /// When Tree-sitter is compiled to WebAssembly, this returns the original
1528    /// language if the tree is being accessed from the same WebAssembly
1529    /// instance that created it. Otherwise, this returns a copy of the language
1530    /// that can be used to inspect the tree but cannot be assigned to a parser.
1531    #[doc(alias = "ts_tree_language")]
1532    #[must_use]
1533    pub fn language(&self) -> LanguageRef {
1534        LanguageRef(
1535            unsafe { ffi::ts_tree_language(self.0.as_ptr()) },
1536            PhantomData,
1537        )
1538    }
1539
1540    /// Edit the syntax tree to keep it in sync with source code that has been
1541    /// edited.
1542    ///
1543    /// You must describe the edit both in terms of byte offsets and in terms of
1544    /// row/column coordinates.
1545    #[doc(alias = "ts_tree_edit")]
1546    pub fn edit(&mut self, edit: &InputEdit) {
1547        let edit = edit.into();
1548        unsafe { ffi::ts_tree_edit(self.0.as_ptr(), &raw const edit) };
1549    }
1550
1551    /// Create a new [`TreeCursor`] starting from the root of the tree.
1552    #[must_use]
1553    pub fn walk(&self) -> TreeCursor {
1554        self.root_node().walk()
1555    }
1556
1557    /// Compare this old edited syntax tree to a new syntax tree representing
1558    /// the same document, returning a sequence of ranges whose syntactic
1559    /// structure has changed.
1560    ///
1561    /// For this to work correctly, this syntax tree must have been edited such
1562    /// that its ranges match up to the new tree. Generally, you'll want to
1563    /// call this method right after calling one of the [`Parser::parse`]
1564    /// functions. Call it on the old tree that was passed to parse, and
1565    /// pass the new tree that was returned from `parse`.
1566    #[doc(alias = "ts_tree_get_changed_ranges")]
1567    pub fn changed_ranges(&self, other: &Self) -> impl ExactSizeIterator<Item = Range> {
1568        let mut count = 0u32;
1569        unsafe {
1570            let ptr = ffi::ts_tree_get_changed_ranges(
1571                self.0.as_ptr(),
1572                other.0.as_ptr(),
1573                core::ptr::addr_of_mut!(count),
1574            );
1575            util::CBufferIter::new(ptr, count as usize).map(Into::into)
1576        }
1577    }
1578
1579    /// Get the included ranges that were used to parse the syntax tree.
1580    #[doc(alias = "ts_tree_included_ranges")]
1581    #[must_use]
1582    pub fn included_ranges(&self) -> Vec<Range> {
1583        let mut count = 0u32;
1584        unsafe {
1585            let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
1586            let ranges = slice::from_raw_parts(ptr, count as usize);
1587            let result = ranges.iter().copied().map(Into::into).collect();
1588            ts_free(ptr.cast::<c_void>());
1589            result
1590        }
1591    }
1592
1593    /// Print a graph of the tree to the given file descriptor.
1594    /// The graph is formatted in the DOT language. You may want to pipe this
1595    /// graph directly to a `dot(1)` process in order to generate SVG
1596    /// output.
1597    #[doc(alias = "ts_tree_print_dot_graph")]
1598    #[cfg(not(target_os = "wasi"))]
1599    #[cfg(feature = "std")]
1600    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1601    pub fn print_dot_graph(
1602        &self,
1603        #[cfg(unix)] file: &impl AsRawFd,
1604        #[cfg(windows)] file: &impl AsRawHandle,
1605    ) {
1606        #[cfg(unix)]
1607        {
1608            let fd = file.as_raw_fd();
1609            unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1610        }
1611
1612        #[cfg(windows)]
1613        {
1614            let handle = file.as_raw_handle();
1615            let fd = unsafe { _open_osfhandle(handle as isize, 0) };
1616            unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1617        }
1618    }
1619}
1620
1621impl fmt::Debug for Tree {
1622    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1623        write!(f, "{{Tree {:?}}}", self.root_node())
1624    }
1625}
1626
1627impl Drop for Tree {
1628    fn drop(&mut self) {
1629        unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
1630    }
1631}
1632
1633impl Clone for Tree {
1634    fn clone(&self) -> Self {
1635        unsafe { Self(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
1636    }
1637}
1638
1639impl<'tree> Node<'tree> {
1640    fn new(node: ffi::TSNode) -> Option<Self> {
1641        (!node.id.is_null()).then_some(Node(node, PhantomData))
1642    }
1643
1644    /// Get a numeric id for this node that is unique.
1645    ///
1646    /// Within a given syntax tree, no two nodes have the same id. However:
1647    ///
1648    /// - If a new tree is created based on an older tree, and a node from the old tree is reused in
1649    ///   the process, then that node will have the same id in both trees.
1650    ///
1651    /// - A node not marked as having changes does not guarantee it was reused.
1652    ///
1653    /// - If a node is marked as having changed in the old tree, it will not be reused.
1654    #[must_use]
1655    pub fn id(&self) -> usize {
1656        self.0.id as usize
1657    }
1658
1659    /// Get this node's type as a numerical id.
1660    #[doc(alias = "ts_node_symbol")]
1661    #[must_use]
1662    pub fn kind_id(&self) -> u16 {
1663        unsafe { ffi::ts_node_symbol(self.0) }
1664    }
1665
1666    /// Get the node's type as a numerical id as it appears in the grammar
1667    /// ignoring aliases.
1668    #[doc(alias = "ts_node_grammar_symbol")]
1669    #[must_use]
1670    pub fn grammar_id(&self) -> u16 {
1671        unsafe { ffi::ts_node_grammar_symbol(self.0) }
1672    }
1673
1674    /// Get this node's type as a string.
1675    #[doc(alias = "ts_node_type")]
1676    #[must_use]
1677    pub fn kind(&self) -> &'tree str {
1678        let ptr = unsafe { ffi::ts_node_type(self.0) };
1679        assert!(!ptr.is_null());
1680        unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
1681    }
1682
1683    /// Get this node's symbol name as it appears in the grammar ignoring
1684    /// aliases as a string.
1685    #[doc(alias = "ts_node_grammar_type")]
1686    #[must_use]
1687    pub fn grammar_name(&self) -> &'tree str {
1688        let ptr = unsafe { ffi::ts_node_grammar_type(self.0) };
1689        assert!(!ptr.is_null());
1690        unsafe { CStr::from_ptr(ptr) }.to_str().unwrap()
1691    }
1692
1693    /// Get the [`Language`] that was used to parse this node's syntax tree.
1694    ///
1695    /// When Tree-sitter is compiled to WebAssembly, this returns the original
1696    /// language if the node is being accessed from the same WebAssembly
1697    /// instance that created its tree. Otherwise, this returns a copy of the
1698    /// language that can be used to inspect the tree but cannot be assigned to
1699    /// a parser.
1700    #[doc(alias = "ts_node_language")]
1701    #[must_use]
1702    pub fn language(&self) -> LanguageRef<'tree> {
1703        LanguageRef(unsafe { ffi::ts_node_language(self.0) }, PhantomData)
1704    }
1705
1706    /// Check if this node is *named*.
1707    ///
1708    /// Named nodes correspond to named rules in the grammar, whereas
1709    /// *anonymous* nodes correspond to string literals in the grammar.
1710    #[doc(alias = "ts_node_is_named")]
1711    #[must_use]
1712    pub fn is_named(&self) -> bool {
1713        unsafe { ffi::ts_node_is_named(self.0) }
1714    }
1715
1716    /// Check if this node is *extra*.
1717    ///
1718    /// Extra nodes represent things like comments, which are not required by the
1719    /// grammar, but can appear anywhere.
1720    #[doc(alias = "ts_node_is_extra")]
1721    #[must_use]
1722    pub fn is_extra(&self) -> bool {
1723        unsafe { ffi::ts_node_is_extra(self.0) }
1724    }
1725
1726    /// Check if this node has been edited.
1727    #[doc(alias = "ts_node_has_changes")]
1728    #[must_use]
1729    pub fn has_changes(&self) -> bool {
1730        unsafe { ffi::ts_node_has_changes(self.0) }
1731    }
1732
1733    /// Check if this node represents a syntax error or contains any syntax
1734    /// errors anywhere within it.
1735    #[doc(alias = "ts_node_has_error")]
1736    #[must_use]
1737    pub fn has_error(&self) -> bool {
1738        unsafe { ffi::ts_node_has_error(self.0) }
1739    }
1740
1741    /// Check if this node represents a syntax error.
1742    ///
1743    /// Syntax errors represent parts of the code that could not be incorporated
1744    /// into a valid syntax tree.
1745    #[doc(alias = "ts_node_is_error")]
1746    #[must_use]
1747    pub fn is_error(&self) -> bool {
1748        unsafe { ffi::ts_node_is_error(self.0) }
1749    }
1750
1751    /// Get the parse state immediately before this node.
1752    ///
1753    /// For a missing node, this is the state from the recovery path that was
1754    /// selected by the parser. It can be used with
1755    /// [`Language::lookahead_iterator`] to inspect the symbols that are valid in
1756    /// that state. This does not necessarily include every symbol that could be
1757    /// recovered by inserting a missing node, because the recovery process can
1758    /// consider multiple stack versions.
1759    #[doc(alias = "ts_node_parse_state")]
1760    #[must_use]
1761    pub fn parse_state(&self) -> u16 {
1762        unsafe { ffi::ts_node_parse_state(self.0) }
1763    }
1764
1765    /// Get the parse state after this node.
1766    #[doc(alias = "ts_node_next_parse_state")]
1767    #[must_use]
1768    pub fn next_parse_state(&self) -> u16 {
1769        unsafe { ffi::ts_node_next_parse_state(self.0) }
1770    }
1771
1772    /// Check if this node is *missing*.
1773    ///
1774    /// Missing nodes are inserted by the parser in order to recover from
1775    /// certain kinds of syntax errors.
1776    #[doc(alias = "ts_node_is_missing")]
1777    #[must_use]
1778    pub fn is_missing(&self) -> bool {
1779        unsafe { ffi::ts_node_is_missing(self.0) }
1780    }
1781
1782    /// Get the byte offset where this node starts.
1783    #[doc(alias = "ts_node_start_byte")]
1784    #[must_use]
1785    pub fn start_byte(&self) -> usize {
1786        unsafe { ffi::ts_node_start_byte(self.0) as usize }
1787    }
1788
1789    /// Get the byte offset where this node ends.
1790    #[doc(alias = "ts_node_end_byte")]
1791    #[must_use]
1792    pub fn end_byte(&self) -> usize {
1793        unsafe { ffi::ts_node_end_byte(self.0) as usize }
1794    }
1795
1796    /// Get the byte range of source code that this node represents.
1797    #[must_use]
1798    pub fn byte_range(&self) -> core::ops::Range<usize> {
1799        self.start_byte()..self.end_byte()
1800    }
1801
1802    /// Get the range of source code that this node represents, both in terms of
1803    /// raw bytes and of row/column coordinates.
1804    #[must_use]
1805    pub fn range(&self) -> Range {
1806        Range {
1807            start_byte: self.start_byte(),
1808            end_byte: self.end_byte(),
1809            start_point: self.start_position(),
1810            end_point: self.end_position(),
1811        }
1812    }
1813
1814    /// Get this node's start position in terms of rows and columns.
1815    #[doc(alias = "ts_node_start_point")]
1816    #[must_use]
1817    pub fn start_position(&self) -> Point {
1818        let result = unsafe { ffi::ts_node_start_point(self.0) };
1819        result.into()
1820    }
1821
1822    /// Get this node's end position in terms of rows and columns.
1823    #[doc(alias = "ts_node_end_point")]
1824    #[must_use]
1825    pub fn end_position(&self) -> Point {
1826        let result = unsafe { ffi::ts_node_end_point(self.0) };
1827        result.into()
1828    }
1829
1830    /// Get the node's child at the given index, where zero represents the first
1831    /// child.
1832    ///
1833    /// This method is fairly fast, but its cost is technically log(i), so if
1834    /// you might be iterating over a long list of children, you should use
1835    /// [`Node::children`] instead.
1836    #[doc(alias = "ts_node_child")]
1837    #[must_use]
1838    pub fn child(&self, i: u32) -> Option<Self> {
1839        Self::new(unsafe { ffi::ts_node_child(self.0, i) })
1840    }
1841
1842    /// Get this node's number of children.
1843    #[doc(alias = "ts_node_child_count")]
1844    #[must_use]
1845    pub fn child_count(&self) -> u32 {
1846        unsafe { ffi::ts_node_child_count(self.0) }
1847    }
1848
1849    /// Get this node's *named* child at the given index.
1850    ///
1851    /// See also [`Node::is_named`].
1852    /// This method is fairly fast, but its cost is technically log(i), so if
1853    /// you might be iterating over a long list of children, you should use
1854    /// [`Node::named_children`] instead.
1855    #[doc(alias = "ts_node_named_child")]
1856    #[must_use]
1857    pub fn named_child(&self, i: u32) -> Option<Self> {
1858        Self::new(unsafe { ffi::ts_node_named_child(self.0, i) })
1859    }
1860
1861    /// Get this node's number of *named* children.
1862    ///
1863    /// See also [`Node::is_named`].
1864    #[doc(alias = "ts_node_named_child_count")]
1865    #[must_use]
1866    pub fn named_child_count(&self) -> usize {
1867        unsafe { ffi::ts_node_named_child_count(self.0) as usize }
1868    }
1869
1870    /// Get the first child with the given field name.
1871    ///
1872    /// If multiple children may have the same field name, access them using
1873    /// [`children_by_field_name`](Node::children_by_field_name)
1874    #[doc(alias = "ts_node_child_by_field_name")]
1875    #[must_use]
1876    pub fn child_by_field_name(&self, field_name: impl AsRef<[u8]>) -> Option<Self> {
1877        let field_name = field_name.as_ref();
1878        Self::new(unsafe {
1879            ffi::ts_node_child_by_field_name(
1880                self.0,
1881                field_name.as_ptr().cast::<c_char>(),
1882                field_name.len() as u32,
1883            )
1884        })
1885    }
1886
1887    /// Get this node's child with the given numerical field id.
1888    ///
1889    /// See also [`child_by_field_name`](Node::child_by_field_name). You can
1890    /// convert a field name to an id using [`Language::field_id_for_name`].
1891    #[doc(alias = "ts_node_child_by_field_id")]
1892    #[must_use]
1893    pub fn child_by_field_id(&self, field_id: u16) -> Option<Self> {
1894        Self::new(unsafe { ffi::ts_node_child_by_field_id(self.0, field_id) })
1895    }
1896
1897    /// Get the field name of this node's child at the given index.
1898    #[doc(alias = "ts_node_field_name_for_child")]
1899    #[must_use]
1900    pub fn field_name_for_child(&self, child_index: u32) -> Option<&'tree str> {
1901        unsafe {
1902            let ptr = ffi::ts_node_field_name_for_child(self.0, child_index);
1903            (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1904        }
1905    }
1906
1907    /// Get the field name of this node's named child at the given index.
1908    #[must_use]
1909    pub fn field_name_for_named_child(&self, named_child_index: u32) -> Option<&'tree str> {
1910        unsafe {
1911            let ptr = ffi::ts_node_field_name_for_named_child(self.0, named_child_index);
1912            (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1913        }
1914    }
1915
1916    /// Iterate over this node's children.
1917    ///
1918    /// A [`TreeCursor`] is used to retrieve the children efficiently. Obtain
1919    /// a [`TreeCursor`] by calling [`Tree::walk`] or [`Node::walk`]. To avoid
1920    /// unnecessary allocations, you should reuse the same cursor for
1921    /// subsequent calls to this method.
1922    ///
1923    /// If you're walking the tree recursively, you may want to use the
1924    /// [`TreeCursor`] APIs directly instead.
1925    pub fn children<'cursor>(
1926        &self,
1927        cursor: &'cursor mut TreeCursor<'tree>,
1928    ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1929        cursor.reset(*self);
1930        cursor.goto_first_child();
1931        (0..self.child_count()).map(move |_| {
1932            let result = cursor.node();
1933            cursor.goto_next_sibling();
1934            result
1935        })
1936    }
1937
1938    /// Iterate over this node's named children.
1939    ///
1940    /// See also [`Node::children`].
1941    pub fn named_children<'cursor>(
1942        &self,
1943        cursor: &'cursor mut TreeCursor<'tree>,
1944    ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1945        cursor.reset(*self);
1946        cursor.goto_first_child();
1947        (0..self.named_child_count()).map(move |_| {
1948            while !cursor.node().is_named() {
1949                if !cursor.goto_next_sibling() {
1950                    break;
1951                }
1952            }
1953            let result = cursor.node();
1954            cursor.goto_next_sibling();
1955            result
1956        })
1957    }
1958
1959    /// Iterate over this node's children with a given field name.
1960    ///
1961    /// See also [`Node::children`].
1962    pub fn children_by_field_name<'cursor>(
1963        &self,
1964        field_name: &str,
1965        cursor: &'cursor mut TreeCursor<'tree>,
1966    ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1967        let field_id = self.language().field_id_for_name(field_name);
1968        let mut done = field_id.is_none();
1969        if !done {
1970            cursor.reset(*self);
1971            cursor.goto_first_child();
1972        }
1973        iter::from_fn(move || {
1974            if !done {
1975                while cursor.field_id() != field_id {
1976                    if !cursor.goto_next_sibling() {
1977                        return None;
1978                    }
1979                }
1980                let result = cursor.node();
1981                if !cursor.goto_next_sibling() {
1982                    done = true;
1983                }
1984                return Some(result);
1985            }
1986            None
1987        })
1988    }
1989
1990    /// Iterate over this node's children with a given field id.
1991    ///
1992    /// See also [`Node::children_by_field_name`].
1993    pub fn children_by_field_id<'cursor>(
1994        &self,
1995        field_id: FieldId,
1996        cursor: &'cursor mut TreeCursor<'tree>,
1997    ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1998        cursor.reset(*self);
1999        cursor.goto_first_child();
2000        let mut done = false;
2001        iter::from_fn(move || {
2002            if !done {
2003                while cursor.field_id() != Some(field_id) {
2004                    if !cursor.goto_next_sibling() {
2005                        return None;
2006                    }
2007                }
2008                let result = cursor.node();
2009                if !cursor.goto_next_sibling() {
2010                    done = true;
2011                }
2012                return Some(result);
2013            }
2014            None
2015        })
2016    }
2017
2018    /// Get this node's immediate parent.
2019    /// Prefer [`child_with_descendant`](Node::child_with_descendant)
2020    /// for iterating over this node's ancestors.
2021    #[doc(alias = "ts_node_parent")]
2022    #[must_use]
2023    pub fn parent(&self) -> Option<Self> {
2024        Self::new(unsafe { ffi::ts_node_parent(self.0) })
2025    }
2026
2027    /// Get the node that contains `descendant`.
2028    ///
2029    /// Note that this can return `descendant` itself.
2030    #[doc(alias = "ts_node_child_with_descendant")]
2031    #[must_use]
2032    pub fn child_with_descendant(&self, descendant: Self) -> Option<Self> {
2033        Self::new(unsafe { ffi::ts_node_child_with_descendant(self.0, descendant.0) })
2034    }
2035
2036    /// Get this node's next sibling.
2037    #[doc(alias = "ts_node_next_sibling")]
2038    #[must_use]
2039    pub fn next_sibling(&self) -> Option<Self> {
2040        Self::new(unsafe { ffi::ts_node_next_sibling(self.0) })
2041    }
2042
2043    /// Get this node's previous sibling.
2044    #[doc(alias = "ts_node_prev_sibling")]
2045    #[must_use]
2046    pub fn prev_sibling(&self) -> Option<Self> {
2047        Self::new(unsafe { ffi::ts_node_prev_sibling(self.0) })
2048    }
2049
2050    /// Get this node's next named sibling.
2051    #[doc(alias = "ts_node_next_named_sibling")]
2052    #[must_use]
2053    pub fn next_named_sibling(&self) -> Option<Self> {
2054        Self::new(unsafe { ffi::ts_node_next_named_sibling(self.0) })
2055    }
2056
2057    /// Get this node's previous named sibling.
2058    #[doc(alias = "ts_node_prev_named_sibling")]
2059    #[must_use]
2060    pub fn prev_named_sibling(&self) -> Option<Self> {
2061        Self::new(unsafe { ffi::ts_node_prev_named_sibling(self.0) })
2062    }
2063
2064    /// Get this node's first child that contains or starts after the given byte offset.
2065    #[doc(alias = "ts_node_first_child_for_byte")]
2066    #[must_use]
2067    pub fn first_child_for_byte(&self, byte: usize) -> Option<Self> {
2068        Self::new(unsafe { ffi::ts_node_first_child_for_byte(self.0, byte as u32) })
2069    }
2070
2071    /// Get this node's first named child that contains or starts after the given byte offset.
2072    #[doc(alias = "ts_node_first_named_child_for_point")]
2073    #[must_use]
2074    pub fn first_named_child_for_byte(&self, byte: usize) -> Option<Self> {
2075        Self::new(unsafe { ffi::ts_node_first_named_child_for_byte(self.0, byte as u32) })
2076    }
2077
2078    /// Get the node's number of descendants, including one for the node itself.
2079    #[doc(alias = "ts_node_descendant_count")]
2080    #[must_use]
2081    pub fn descendant_count(&self) -> usize {
2082        unsafe { ffi::ts_node_descendant_count(self.0) as usize }
2083    }
2084
2085    /// Get the smallest node within this node that spans the given byte range.
2086    #[doc(alias = "ts_node_descendant_for_byte_range")]
2087    #[must_use]
2088    pub fn descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
2089        Self::new(unsafe {
2090            ffi::ts_node_descendant_for_byte_range(self.0, start as u32, end as u32)
2091        })
2092    }
2093
2094    /// Get the smallest named node within this node that spans the given byte range.
2095    #[doc(alias = "ts_node_named_descendant_for_byte_range")]
2096    #[must_use]
2097    pub fn named_descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
2098        Self::new(unsafe {
2099            ffi::ts_node_named_descendant_for_byte_range(self.0, start as u32, end as u32)
2100        })
2101    }
2102
2103    /// Get the smallest node within this node that spans the given point range.
2104    #[doc(alias = "ts_node_descendant_for_point_range")]
2105    #[must_use]
2106    pub fn descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
2107        Self::new(unsafe {
2108            ffi::ts_node_descendant_for_point_range(self.0, start.into(), end.into())
2109        })
2110    }
2111
2112    /// Get the smallest named node within this node that spans the given point range.
2113    #[doc(alias = "ts_node_named_descendant_for_point_range")]
2114    #[must_use]
2115    pub fn named_descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
2116        Self::new(unsafe {
2117            ffi::ts_node_named_descendant_for_point_range(self.0, start.into(), end.into())
2118        })
2119    }
2120
2121    /// Get an S-expression representing the node.
2122    #[doc(alias = "ts_node_string")]
2123    #[must_use]
2124    pub fn to_sexp(&self) -> String {
2125        let c_string = unsafe { ffi::ts_node_string(self.0) };
2126        let result = unsafe { CStr::from_ptr(c_string) }
2127            .to_str()
2128            .unwrap()
2129            .to_string();
2130        unsafe { ts_free(c_string.cast::<c_void>()) };
2131        result
2132    }
2133
2134    pub fn utf8_text<'a>(&self, source: &'a [u8]) -> Result<&'a str, str::Utf8Error> {
2135        str::from_utf8(&source[self.start_byte()..self.end_byte()])
2136    }
2137
2138    #[must_use]
2139    pub fn utf16_text<'a>(&self, source: &'a [u16]) -> &'a [u16] {
2140        &source[self.start_byte() / 2..self.end_byte() / 2]
2141    }
2142
2143    /// Create a new [`TreeCursor`] starting from this node.
2144    ///
2145    /// Note that the given node is considered the root of the cursor,
2146    /// and the cursor cannot walk outside this node.
2147    #[doc(alias = "ts_tree_cursor_new")]
2148    #[must_use]
2149    pub fn walk(&self) -> TreeCursor<'tree> {
2150        TreeCursor(unsafe { ffi::ts_tree_cursor_new(self.0) }, PhantomData)
2151    }
2152
2153    /// Edit this node to keep it in-sync with source code that has been edited.
2154    ///
2155    /// This function is only rarely needed. When you edit a syntax tree with
2156    /// the [`Tree::edit`] method, all of the nodes that you retrieve from
2157    /// the tree afterward will already reflect the edit. You only need to
2158    /// use [`Node::edit`] when you have a specific [`Node`] instance that
2159    /// you want to keep and continue to use after an edit.
2160    #[doc(alias = "ts_node_edit")]
2161    pub fn edit(&mut self, edit: &InputEdit) {
2162        let edit = edit.into();
2163        unsafe { ffi::ts_node_edit(core::ptr::addr_of_mut!(self.0), &raw const edit) }
2164    }
2165}
2166
2167impl PartialEq for Node<'_> {
2168    fn eq(&self, other: &Self) -> bool {
2169        core::ptr::eq(self.0.id, other.0.id)
2170    }
2171}
2172
2173impl Eq for Node<'_> {}
2174
2175impl hash::Hash for Node<'_> {
2176    fn hash<H: hash::Hasher>(&self, state: &mut H) {
2177        self.0.id.hash(state);
2178        self.0.context[0].hash(state);
2179        self.0.context[1].hash(state);
2180        self.0.context[2].hash(state);
2181        self.0.context[3].hash(state);
2182    }
2183}
2184
2185impl fmt::Debug for Node<'_> {
2186    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2187        write!(
2188            f,
2189            "{{Node {} {} - {}}}",
2190            self.kind(),
2191            self.start_position(),
2192            self.end_position()
2193        )
2194    }
2195}
2196
2197impl fmt::Display for Node<'_> {
2198    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2199        if !f.alternate() {
2200            return f.write_str(&self.to_sexp());
2201        }
2202        let c_string = unsafe { ts_node_string_pretty(self.0, f.width().unwrap_or(0)) };
2203        let result = unsafe { CStr::from_ptr(c_string) }
2204            .to_str()
2205            .unwrap()
2206            .to_string();
2207        unsafe { ts_free(c_string.cast::<c_void>()) };
2208        f.write_str(&result)
2209    }
2210}
2211
2212impl<'tree> TreeCursor<'tree> {
2213    /// Get the tree cursor's current [`Node`].
2214    #[doc(alias = "ts_tree_cursor_current_node")]
2215    #[must_use]
2216    pub fn node(&self) -> Node<'tree> {
2217        Node(
2218            unsafe { ffi::ts_tree_cursor_current_node(&raw const self.0) },
2219            PhantomData,
2220        )
2221    }
2222
2223    /// Get the numerical field id of this tree cursor's current node.
2224    ///
2225    /// See also [`field_name`](TreeCursor::field_name).
2226    #[doc(alias = "ts_tree_cursor_current_field_id")]
2227    #[must_use]
2228    pub fn field_id(&self) -> Option<FieldId> {
2229        let id = unsafe { ffi::ts_tree_cursor_current_field_id(&raw const self.0) };
2230        FieldId::new(id)
2231    }
2232
2233    /// Get the field name of this tree cursor's current node.
2234    #[doc(alias = "ts_tree_cursor_current_field_name")]
2235    #[must_use]
2236    pub fn field_name(&self) -> Option<&'tree str> {
2237        unsafe {
2238            let ptr = ffi::ts_tree_cursor_current_field_name(&raw const self.0);
2239            (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
2240        }
2241    }
2242
2243    /// Get the depth of the cursor's current node relative to the original
2244    /// node that the cursor was constructed with.
2245    #[doc(alias = "ts_tree_cursor_current_depth")]
2246    #[must_use]
2247    pub fn depth(&self) -> u32 {
2248        unsafe { ffi::ts_tree_cursor_current_depth(&raw const self.0) }
2249    }
2250
2251    /// Get the index of the cursor's current node out of all of the
2252    /// descendants of the original node that the cursor was constructed with
2253    #[doc(alias = "ts_tree_cursor_current_descendant_index")]
2254    #[must_use]
2255    pub fn descendant_index(&self) -> usize {
2256        unsafe { ffi::ts_tree_cursor_current_descendant_index(&raw const self.0) as usize }
2257    }
2258
2259    /// Move this cursor to the first child of its current node.
2260    ///
2261    /// This returns `true` if the cursor successfully moved, and returns
2262    /// `false` if there were no children.
2263    #[doc(alias = "ts_tree_cursor_goto_first_child")]
2264    pub fn goto_first_child(&mut self) -> bool {
2265        unsafe { ffi::ts_tree_cursor_goto_first_child(&raw mut self.0) }
2266    }
2267
2268    /// Move this cursor to the last child of its current node.
2269    ///
2270    /// This returns `true` if the cursor successfully moved, and returns
2271    /// `false` if there were no children.
2272    ///
2273    /// Note that this function may be slower than
2274    /// [`goto_first_child`](TreeCursor::goto_first_child) because it needs to
2275    /// iterate through all the children to compute the child's position.
2276    #[doc(alias = "ts_tree_cursor_goto_last_child")]
2277    pub fn goto_last_child(&mut self) -> bool {
2278        unsafe { ffi::ts_tree_cursor_goto_last_child(&raw mut self.0) }
2279    }
2280
2281    /// Move this cursor to the parent of its current node.
2282    ///
2283    /// This returns `true` if the cursor successfully moved, and returns
2284    /// `false` if there was no parent node (the cursor was already on the
2285    /// root node).
2286    ///
2287    /// Note that the node the cursor was constructed with is considered the root
2288    /// of the cursor, and the cursor cannot walk outside this node.
2289    #[doc(alias = "ts_tree_cursor_goto_parent")]
2290    pub fn goto_parent(&mut self) -> bool {
2291        unsafe { ffi::ts_tree_cursor_goto_parent(&raw mut self.0) }
2292    }
2293
2294    /// Move this cursor to the next sibling of its current node.
2295    ///
2296    /// This returns `true` if the cursor successfully moved, and returns
2297    /// `false` if there was no next sibling node.
2298    ///
2299    /// Note that the node the cursor was constructed with is considered the root
2300    /// of the cursor, and the cursor cannot walk outside this node.
2301    #[doc(alias = "ts_tree_cursor_goto_next_sibling")]
2302    pub fn goto_next_sibling(&mut self) -> bool {
2303        unsafe { ffi::ts_tree_cursor_goto_next_sibling(&raw mut self.0) }
2304    }
2305
2306    /// Move the cursor to the node that is the nth descendant of
2307    /// the original node that the cursor was constructed with, where
2308    /// zero represents the original node itself.
2309    #[doc(alias = "ts_tree_cursor_goto_descendant")]
2310    pub fn goto_descendant(&mut self, descendant_index: usize) {
2311        unsafe { ffi::ts_tree_cursor_goto_descendant(&raw mut self.0, descendant_index as u32) }
2312    }
2313
2314    /// Move this cursor to the previous sibling of its current node.
2315    ///
2316    /// This returns `true` if the cursor successfully moved, and returns
2317    /// `false` if there was no previous sibling node.
2318    ///
2319    /// Note, that this function may be slower than
2320    /// [`goto_next_sibling`](TreeCursor::goto_next_sibling) due to how node
2321    /// positions are stored. In the worst case, this will need to iterate
2322    /// through all the children up to the previous sibling node to recalculate
2323    /// its position. Also note that the node the cursor was constructed with is
2324    /// considered the root of the cursor, and the cursor cannot walk outside this node.
2325    #[doc(alias = "ts_tree_cursor_goto_previous_sibling")]
2326    pub fn goto_previous_sibling(&mut self) -> bool {
2327        unsafe { ffi::ts_tree_cursor_goto_previous_sibling(&raw mut self.0) }
2328    }
2329
2330    /// Move this cursor to the first child of its current node that contains or
2331    /// starts after the given byte offset.
2332    ///
2333    /// This returns the index of the child node if one was found, and returns
2334    /// `None` if no such child was found.
2335    #[doc(alias = "ts_tree_cursor_goto_first_child_for_byte")]
2336    pub fn goto_first_child_for_byte(&mut self, index: usize) -> Option<usize> {
2337        let result =
2338            unsafe { ffi::ts_tree_cursor_goto_first_child_for_byte(&raw mut self.0, index as u32) };
2339        result.try_into().ok()
2340    }
2341
2342    /// Move this cursor to the first child of its current node that contains or
2343    /// starts after the given byte offset.
2344    ///
2345    /// This returns the index of the child node if one was found, and returns
2346    /// `None` if no such child was found.
2347    #[doc(alias = "ts_tree_cursor_goto_first_child_for_point")]
2348    pub fn goto_first_child_for_point(&mut self, point: Point) -> Option<usize> {
2349        let result = unsafe {
2350            ffi::ts_tree_cursor_goto_first_child_for_point(&raw mut self.0, point.into())
2351        };
2352        result.try_into().ok()
2353    }
2354
2355    /// Re-initialize this tree cursor to start at the original node that the
2356    /// cursor was constructed with.
2357    #[doc(alias = "ts_tree_cursor_reset")]
2358    pub fn reset(&mut self, node: Node<'tree>) {
2359        unsafe { ffi::ts_tree_cursor_reset(&raw mut self.0, node.0) };
2360    }
2361
2362    /// Re-initialize a tree cursor to the same position as another cursor.
2363    ///
2364    /// Unlike [`reset`](TreeCursor::reset), this will not lose parent
2365    /// information and allows reusing already created cursors.
2366    #[doc(alias = "ts_tree_cursor_reset_to")]
2367    pub fn reset_to(&mut self, cursor: &Self) {
2368        unsafe { ffi::ts_tree_cursor_reset_to(&raw mut self.0, &raw const cursor.0) };
2369    }
2370}
2371
2372impl Clone for TreeCursor<'_> {
2373    fn clone(&self) -> Self {
2374        TreeCursor(
2375            unsafe { ffi::ts_tree_cursor_copy(&raw const self.0) },
2376            PhantomData,
2377        )
2378    }
2379}
2380
2381impl Drop for TreeCursor<'_> {
2382    fn drop(&mut self) {
2383        unsafe { ffi::ts_tree_cursor_delete(&raw mut self.0) }
2384    }
2385}
2386
2387impl LookaheadIterator {
2388    /// Get the current language of the lookahead iterator.
2389    #[doc(alias = "ts_lookahead_iterator_language")]
2390    #[must_use]
2391    pub fn language(&self) -> LanguageRef<'_> {
2392        LanguageRef(
2393            unsafe { ffi::ts_lookahead_iterator_language(self.0.as_ptr()) },
2394            PhantomData,
2395        )
2396    }
2397
2398    /// Get the current symbol of the lookahead iterator.
2399    ///
2400    /// Returns `None` if the iterator is not positioned on a symbol:
2401    ///
2402    /// - Before the first [`Iterator::next`] call
2403    /// - After the iterator is exhausted
2404    /// - After a [`Self::reset`] or [`Self::reset_state`] call
2405    #[doc(alias = "ts_lookahead_iterator_current_symbol")]
2406    #[must_use]
2407    pub fn current_symbol(&self) -> Option<u16> {
2408        // C signals "not positioned" through a null symbol name.
2409        let name = unsafe { ffi::ts_lookahead_iterator_current_symbol_name(self.0.as_ptr()) };
2410        (!name.is_null())
2411            .then(|| unsafe { ffi::ts_lookahead_iterator_current_symbol(self.0.as_ptr()) })
2412    }
2413
2414    /// Get the current symbol name of the lookahead iterator.
2415    ///
2416    /// Returns `None` if the iterator is not positioned on a symbol.
2417    #[doc(alias = "ts_lookahead_iterator_current_symbol_name")]
2418    #[must_use]
2419    pub fn current_symbol_name(&self) -> Option<&str> {
2420        unsafe {
2421            let name = ffi::ts_lookahead_iterator_current_symbol_name(self.0.as_ptr());
2422            if name.is_null() {
2423                None
2424            } else {
2425                Some(CStr::from_ptr(name).to_str().unwrap())
2426            }
2427        }
2428    }
2429
2430    /// Reset the lookahead iterator.
2431    ///
2432    /// This returns `true` if the language was set successfully and `false`
2433    /// otherwise.
2434    #[doc(alias = "ts_lookahead_iterator_reset")]
2435    pub fn reset(&mut self, language: &Language, state: u16) -> bool {
2436        unsafe { ffi::ts_lookahead_iterator_reset(self.0.as_ptr(), language.0, state) }
2437    }
2438
2439    /// Reset the lookahead iterator to another state.
2440    ///
2441    /// This returns `true` if the iterator was reset to the given state and
2442    /// `false` otherwise.
2443    #[doc(alias = "ts_lookahead_iterator_reset_state")]
2444    pub fn reset_state(&mut self, state: u16) -> bool {
2445        unsafe { ffi::ts_lookahead_iterator_reset_state(self.0.as_ptr(), state) }
2446    }
2447
2448    /// Iterate symbol names.
2449    pub fn iter_names(&mut self) -> impl iter::FusedIterator<Item = &str> + '_ {
2450        LookaheadNamesIterator(self)
2451    }
2452}
2453
2454impl<'a> Iterator for LookaheadNamesIterator<'a> {
2455    type Item = &'a str;
2456
2457    #[doc(alias = "ts_lookahead_iterator_next")]
2458    fn next(&mut self) -> Option<Self::Item> {
2459        let ptr = self.0.0.as_ptr();
2460        // SAFETY: The borrow keeps the iterator (and the language refcount it holds)
2461        // alive for `'a`. The name is non-null because the iterator is positioned
2462        // whenever `next` returns `true`.
2463        unsafe {
2464            ffi::ts_lookahead_iterator_next(ptr).then(|| {
2465                let name = ffi::ts_lookahead_iterator_current_symbol_name(ptr);
2466                debug_assert!(!name.is_null());
2467                CStr::from_ptr(name).to_str().unwrap()
2468            })
2469        }
2470    }
2471}
2472
2473impl iter::FusedIterator for LookaheadNamesIterator<'_> {}
2474
2475impl Iterator for LookaheadIterator {
2476    type Item = u16;
2477
2478    #[doc(alias = "ts_lookahead_iterator_next")]
2479    fn next(&mut self) -> Option<Self::Item> {
2480        unsafe { ffi::ts_lookahead_iterator_next(self.0.as_ptr()) }
2481            .then(|| unsafe { ffi::ts_lookahead_iterator_current_symbol(self.0.as_ptr()) })
2482    }
2483}
2484
2485impl iter::FusedIterator for LookaheadIterator {}
2486
2487impl Drop for LookaheadIterator {
2488    #[doc(alias = "ts_lookahead_iterator_delete")]
2489    fn drop(&mut self) {
2490        unsafe { ffi::ts_lookahead_iterator_delete(self.0.as_ptr()) }
2491    }
2492}
2493
2494impl Query {
2495    /// Create a new query from a string containing one or more S-expression
2496    /// patterns.
2497    ///
2498    /// The query is associated with a particular language, and can only be run
2499    /// on syntax nodes parsed with that language. References to Queries can be
2500    /// shared between multiple threads.
2501    pub fn new(language: &Language, source: &str) -> Result<Self, QueryError> {
2502        let ptr = Self::new_raw(language, source)?;
2503        unsafe { Self::from_raw_parts(ptr, source) }
2504    }
2505
2506    /// Constructs a raw [`TSQuery`](ffi::TSQuery) pointer without performing extra checks specific to the rust
2507    /// bindings, such as predicate validation. A [`Query`] object can be constructed from the
2508    /// returned pointer using [`from_raw_parts`](Query::from_raw_parts). The caller is
2509    /// responsible for ensuring that the returned pointer is eventually freed by calling
2510    /// [`ts_query_delete`](ffi::ts_query_delete).
2511    pub fn new_raw(language: &Language, source: &str) -> Result<*mut ffi::TSQuery, QueryError> {
2512        let mut error_offset = 0u32;
2513        let mut error_type: ffi::TSQueryError = 0;
2514        let bytes = source.as_bytes();
2515
2516        // Compile the query.
2517        let ptr = unsafe {
2518            ffi::ts_query_new(
2519                language.0,
2520                bytes.as_ptr().cast::<c_char>(),
2521                bytes.len() as u32,
2522                core::ptr::addr_of_mut!(error_offset),
2523                core::ptr::addr_of_mut!(error_type),
2524            )
2525        };
2526
2527        if !ptr.is_null() {
2528            return Ok(ptr);
2529        }
2530
2531        // On failure, build an error based on the error code and offset.
2532        if error_type == ffi::TSQueryErrorLanguage {
2533            return Err(QueryError {
2534                row: 0,
2535                column: 0,
2536                offset: 0,
2537                message: LanguageError::Version(language.abi_version()).to_string(),
2538                kind: QueryErrorKind::Language,
2539            });
2540        }
2541
2542        let offset = error_offset as usize;
2543        let mut line_start = 0;
2544        let mut row = 0;
2545        let mut line_containing_error = None;
2546        for line in source.lines() {
2547            let line_end = line_start + line.len() + 1;
2548            if line_end > offset {
2549                line_containing_error = Some(line);
2550                break;
2551            }
2552            line_start = line_end;
2553            row += 1;
2554        }
2555        let column = offset - line_start;
2556
2557        let (message, kind) = match error_type {
2558            // Error types that report names
2559            ffi::TSQueryErrorNodeType | ffi::TSQueryErrorField | ffi::TSQueryErrorCapture => {
2560                let suffix = source.split_at(offset).1;
2561                let in_quotes = offset > 0 && source.as_bytes()[offset - 1] == b'"';
2562                let mut backslashes = 0;
2563                let end_offset = suffix
2564                    .find(|c| {
2565                        if in_quotes {
2566                            if c == '"' && backslashes % 2 == 0 {
2567                                true
2568                            } else if c == '\\' {
2569                                backslashes += 1;
2570                                false
2571                            } else {
2572                                backslashes = 0;
2573                                false
2574                            }
2575                        } else {
2576                            !char::is_alphanumeric(c) && c != '_' && c != '-'
2577                        }
2578                    })
2579                    .unwrap_or(suffix.len());
2580                (
2581                    format!("\"{}\"", suffix.split_at(end_offset).0),
2582                    match error_type {
2583                        ffi::TSQueryErrorNodeType => QueryErrorKind::NodeType,
2584                        ffi::TSQueryErrorField => QueryErrorKind::Field,
2585                        ffi::TSQueryErrorCapture => QueryErrorKind::Capture,
2586                        _ => unreachable!(),
2587                    },
2588                )
2589            }
2590
2591            // Error types that report positions
2592            _ => (
2593                line_containing_error.map_or_else(
2594                    || "Unexpected EOF".to_string(),
2595                    |line| line.to_string() + "\n" + &" ".repeat(offset - line_start) + "^",
2596                ),
2597                match error_type {
2598                    ffi::TSQueryErrorStructure => QueryErrorKind::Structure,
2599                    _ => QueryErrorKind::Syntax,
2600                },
2601            ),
2602        };
2603
2604        Err(QueryError {
2605            row,
2606            column,
2607            offset,
2608            message,
2609            kind,
2610        })
2611    }
2612
2613    #[doc(hidden)]
2614    unsafe fn from_raw_parts(ptr: *mut ffi::TSQuery, source: &str) -> Result<Self, QueryError> {
2615        let ptr = {
2616            struct TSQueryDrop(*mut ffi::TSQuery);
2617            impl Drop for TSQueryDrop {
2618                fn drop(&mut self) {
2619                    unsafe { ffi::ts_query_delete(self.0) }
2620                }
2621            }
2622            TSQueryDrop(ptr)
2623        };
2624
2625        let string_count = unsafe { ffi::ts_query_string_count(ptr.0) };
2626        let capture_count = unsafe { ffi::ts_query_capture_count(ptr.0) };
2627        let pattern_count = unsafe { ffi::ts_query_pattern_count(ptr.0) as usize };
2628
2629        let mut capture_names = Vec::with_capacity(capture_count as usize);
2630        let mut capture_quantifiers_vec = Vec::with_capacity(pattern_count);
2631        let mut text_predicates_vec = Vec::with_capacity(pattern_count);
2632        let mut property_predicates_vec = Vec::with_capacity(pattern_count);
2633        let mut property_settings_vec = Vec::with_capacity(pattern_count);
2634        let mut general_predicates_vec = Vec::with_capacity(pattern_count);
2635
2636        // Build a vector of strings to store the capture names.
2637        for i in 0..capture_count {
2638            unsafe {
2639                let mut length = 0u32;
2640                let name =
2641                    ffi::ts_query_capture_name_for_id(ptr.0, i, core::ptr::addr_of_mut!(length))
2642                        .cast::<u8>();
2643                let name = slice::from_raw_parts(name, length as usize);
2644                let name = str::from_utf8_unchecked(name);
2645                capture_names.push(name);
2646            }
2647        }
2648
2649        // Build a vector to store capture quantifiers.
2650        for i in 0..pattern_count {
2651            let mut capture_quantifiers = Vec::with_capacity(capture_count as usize);
2652            for j in 0..capture_count {
2653                unsafe {
2654                    let quantifier = ffi::ts_query_capture_quantifier_for_id(ptr.0, i as u32, j);
2655                    capture_quantifiers.push(quantifier.into());
2656                }
2657            }
2658            capture_quantifiers_vec.push(capture_quantifiers.into());
2659        }
2660
2661        // Build a vector of strings to represent literal values used in predicates.
2662        let string_values = (0..string_count)
2663            .map(|i| unsafe {
2664                let mut length = 0u32;
2665                let value =
2666                    ffi::ts_query_string_value_for_id(ptr.0, i, core::ptr::addr_of_mut!(length))
2667                        .cast::<u8>();
2668                let value = slice::from_raw_parts(value, length as usize);
2669                str::from_utf8_unchecked(value)
2670            })
2671            .collect::<Vec<_>>();
2672
2673        // Build a vector of predicates for each pattern.
2674        for i in 0..pattern_count {
2675            let predicate_steps = unsafe {
2676                let mut length = 0u32;
2677                let raw_predicates = ffi::ts_query_predicates_for_pattern(
2678                    ptr.0,
2679                    i as u32,
2680                    core::ptr::addr_of_mut!(length),
2681                );
2682                if length > 0 {
2683                    slice::from_raw_parts(raw_predicates, length as usize)
2684                } else {
2685                    Default::default()
2686                }
2687            };
2688
2689            let byte_offset = unsafe { ffi::ts_query_start_byte_for_pattern(ptr.0, i as u32) };
2690            let row = source
2691                .char_indices()
2692                .take_while(|(i, _)| *i < byte_offset as usize)
2693                .filter(|(_, c)| *c == '\n')
2694                .count();
2695
2696            use ffi::TSQueryPredicateStepType as T;
2697            const TYPE_DONE: T = ffi::TSQueryPredicateStepTypeDone;
2698            const TYPE_CAPTURE: T = ffi::TSQueryPredicateStepTypeCapture;
2699            const TYPE_STRING: T = ffi::TSQueryPredicateStepTypeString;
2700
2701            let mut text_predicates = Vec::new();
2702            let mut property_predicates = Vec::new();
2703            let mut property_settings = Vec::new();
2704            let mut general_predicates = Vec::new();
2705            for p in predicate_steps.split(|s| s.type_ == TYPE_DONE) {
2706                if p.is_empty() {
2707                    continue;
2708                }
2709
2710                if p[0].type_ != TYPE_STRING {
2711                    return Err(predicate_error(
2712                        row,
2713                        format!(
2714                            "Expected predicate to start with a function name. Got @{}.",
2715                            capture_names[p[0].value_id as usize],
2716                        ),
2717                    ));
2718                }
2719
2720                // Build a predicate for each of the known predicate function names.
2721                let operator_name = string_values[p[0].value_id as usize];
2722                match operator_name {
2723                    "eq?" | "not-eq?" | "any-eq?" | "any-not-eq?" => {
2724                        if p.len() != 3 {
2725                            return Err(predicate_error(
2726                                row,
2727                                format!(
2728                                    "Wrong number of arguments to #eq? predicate. Expected 2, got {}.",
2729                                    p.len() - 1
2730                                ),
2731                            ));
2732                        }
2733                        if p[1].type_ != TYPE_CAPTURE {
2734                            return Err(predicate_error(
2735                                row,
2736                                format!(
2737                                    "First argument to #eq? predicate must be a capture name. Got literal \"{}\".",
2738                                    string_values[p[1].value_id as usize],
2739                                ),
2740                            ));
2741                        }
2742
2743                        let is_positive = operator_name == "eq?" || operator_name == "any-eq?";
2744                        let match_all = match operator_name {
2745                            "eq?" | "not-eq?" => true,
2746                            "any-eq?" | "any-not-eq?" => false,
2747                            _ => unreachable!(),
2748                        };
2749                        text_predicates.push(if p[2].type_ == TYPE_CAPTURE {
2750                            TextPredicateCapture::EqCapture(
2751                                p[1].value_id,
2752                                p[2].value_id,
2753                                is_positive,
2754                                match_all,
2755                            )
2756                        } else {
2757                            TextPredicateCapture::EqString(
2758                                p[1].value_id,
2759                                string_values[p[2].value_id as usize].to_string().into(),
2760                                is_positive,
2761                                match_all,
2762                            )
2763                        });
2764                    }
2765
2766                    "match?" | "not-match?" | "any-match?" | "any-not-match?" => {
2767                        if p.len() != 3 {
2768                            return Err(predicate_error(
2769                                row,
2770                                format!(
2771                                    "Wrong number of arguments to #match? predicate. Expected 2, got {}.",
2772                                    p.len() - 1
2773                                ),
2774                            ));
2775                        }
2776                        if p[1].type_ != TYPE_CAPTURE {
2777                            return Err(predicate_error(
2778                                row,
2779                                format!(
2780                                    "First argument to #match? predicate must be a capture name. Got literal \"{}\".",
2781                                    string_values[p[1].value_id as usize],
2782                                ),
2783                            ));
2784                        }
2785                        if p[2].type_ == TYPE_CAPTURE {
2786                            return Err(predicate_error(
2787                                row,
2788                                format!(
2789                                    "Second argument to #match? predicate must be a literal. Got capture @{}.",
2790                                    capture_names[p[2].value_id as usize],
2791                                ),
2792                            ));
2793                        }
2794
2795                        let is_positive =
2796                            operator_name == "match?" || operator_name == "any-match?";
2797                        let match_all = match operator_name {
2798                            "match?" | "not-match?" => true,
2799                            "any-match?" | "any-not-match?" => false,
2800                            _ => unreachable!(),
2801                        };
2802                        let regex = &string_values[p[2].value_id as usize];
2803                        text_predicates.push(TextPredicateCapture::MatchString(
2804                            p[1].value_id,
2805                            regex::bytes::Regex::new(regex).map_err(|_| {
2806                                predicate_error(row, format!("Invalid regex '{regex}'"))
2807                            })?,
2808                            is_positive,
2809                            match_all,
2810                        ));
2811                    }
2812
2813                    "set!" => property_settings.push(Self::parse_property(
2814                        row,
2815                        operator_name,
2816                        &capture_names,
2817                        &string_values,
2818                        &p[1..],
2819                    )?),
2820
2821                    "is?" | "is-not?" => property_predicates.push((
2822                        Self::parse_property(
2823                            row,
2824                            operator_name,
2825                            &capture_names,
2826                            &string_values,
2827                            &p[1..],
2828                        )?,
2829                        operator_name == "is?",
2830                    )),
2831
2832                    "any-of?" | "not-any-of?" => {
2833                        if p.len() < 2 {
2834                            return Err(predicate_error(
2835                                row,
2836                                format!(
2837                                    "Wrong number of arguments to #any-of? predicate. Expected at least 1, got {}.",
2838                                    p.len() - 1
2839                                ),
2840                            ));
2841                        }
2842                        if p[1].type_ != TYPE_CAPTURE {
2843                            return Err(predicate_error(
2844                                row,
2845                                format!(
2846                                    "First argument to #any-of? predicate must be a capture name. Got literal \"{}\".",
2847                                    string_values[p[1].value_id as usize],
2848                                ),
2849                            ));
2850                        }
2851
2852                        let is_positive = operator_name == "any-of?";
2853                        let mut values = Vec::new();
2854                        for arg in &p[2..] {
2855                            if arg.type_ == TYPE_CAPTURE {
2856                                return Err(predicate_error(
2857                                    row,
2858                                    format!(
2859                                        "Arguments to #any-of? predicate must be literals. Got capture @{}.",
2860                                        capture_names[arg.value_id as usize],
2861                                    ),
2862                                ));
2863                            }
2864                            values.push(string_values[arg.value_id as usize]);
2865                        }
2866                        text_predicates.push(TextPredicateCapture::AnyString(
2867                            p[1].value_id,
2868                            values
2869                                .iter()
2870                                .map(|x| (*x).to_string().into())
2871                                .collect::<Vec<_>>()
2872                                .into(),
2873                            is_positive,
2874                        ));
2875                    }
2876
2877                    _ => general_predicates.push(QueryPredicate {
2878                        operator: operator_name.to_string().into(),
2879                        args: p[1..]
2880                            .iter()
2881                            .map(|a| {
2882                                if a.type_ == TYPE_CAPTURE {
2883                                    QueryPredicateArg::Capture(a.value_id)
2884                                } else {
2885                                    QueryPredicateArg::String(
2886                                        string_values[a.value_id as usize].to_string().into(),
2887                                    )
2888                                }
2889                            })
2890                            .collect(),
2891                    }),
2892                }
2893            }
2894
2895            text_predicates_vec.push(text_predicates.into());
2896            property_predicates_vec.push(property_predicates.into());
2897            property_settings_vec.push(property_settings.into());
2898            general_predicates_vec.push(general_predicates.into());
2899        }
2900
2901        let result = Self {
2902            ptr: unsafe { NonNull::new_unchecked(ptr.0) },
2903            capture_names: capture_names.into(),
2904            capture_quantifiers: capture_quantifiers_vec.into(),
2905            text_predicates: text_predicates_vec.into(),
2906            property_predicates: property_predicates_vec.into(),
2907            property_settings: property_settings_vec.into(),
2908            general_predicates: general_predicates_vec.into(),
2909        };
2910
2911        core::mem::forget(ptr);
2912
2913        Ok(result)
2914    }
2915
2916    /// Get the byte offset where the given pattern starts in the query's
2917    /// source.
2918    #[doc(alias = "ts_query_start_byte_for_pattern")]
2919    #[must_use]
2920    pub fn start_byte_for_pattern(&self, pattern_index: usize) -> usize {
2921        assert!(
2922            pattern_index < self.text_predicates.len(),
2923            "Pattern index is {pattern_index} but the pattern count is {}",
2924            self.text_predicates.len(),
2925        );
2926        unsafe {
2927            ffi::ts_query_start_byte_for_pattern(self.ptr.as_ptr(), pattern_index as u32) as usize
2928        }
2929    }
2930
2931    /// Get the byte offset where the given pattern ends in the query's
2932    /// source.
2933    #[doc(alias = "ts_query_end_byte_for_pattern")]
2934    #[must_use]
2935    pub fn end_byte_for_pattern(&self, pattern_index: usize) -> usize {
2936        assert!(
2937            pattern_index < self.text_predicates.len(),
2938            "Pattern index is {pattern_index} but the pattern count is {}",
2939            self.text_predicates.len(),
2940        );
2941        unsafe {
2942            ffi::ts_query_end_byte_for_pattern(self.ptr.as_ptr(), pattern_index as u32) as usize
2943        }
2944    }
2945
2946    /// Get the number of patterns in the query.
2947    #[doc(alias = "ts_query_pattern_count")]
2948    #[must_use]
2949    pub fn pattern_count(&self) -> usize {
2950        unsafe { ffi::ts_query_pattern_count(self.ptr.as_ptr()) as usize }
2951    }
2952
2953    /// Get the names of the captures used in the query.
2954    #[must_use]
2955    pub const fn capture_names(&self) -> &[&str] {
2956        &self.capture_names
2957    }
2958
2959    /// Get the quantifiers of the captures used in the query.
2960    #[must_use]
2961    pub const fn capture_quantifiers(&self, index: usize) -> &[CaptureQuantifier] {
2962        &self.capture_quantifiers[index]
2963    }
2964
2965    /// Get the index for a given capture name.
2966    #[must_use]
2967    pub fn capture_index_for_name(&self, name: &str) -> Option<u32> {
2968        self.capture_names
2969            .iter()
2970            .position(|n| *n == name)
2971            .map(|ix| ix as u32)
2972    }
2973
2974    /// Get the properties that are checked for the given pattern index.
2975    ///
2976    /// This includes predicates with the operators `is?` and `is-not?`.
2977    #[must_use]
2978    pub const fn property_predicates(&self, index: usize) -> &[(QueryProperty, bool)] {
2979        &self.property_predicates[index]
2980    }
2981
2982    /// Get the properties that are set for the given pattern index.
2983    ///
2984    /// This includes predicates with the operator `set!`.
2985    #[must_use]
2986    pub const fn property_settings(&self, index: usize) -> &[QueryProperty] {
2987        &self.property_settings[index]
2988    }
2989
2990    /// Get the other user-defined predicates associated with the given index.
2991    ///
2992    /// This includes predicate with operators other than:
2993    /// * `match?`
2994    /// * `eq?` and `not-eq?`
2995    /// * `is?` and `is-not?`
2996    /// * `set!`
2997    #[must_use]
2998    pub const fn general_predicates(&self, index: usize) -> &[QueryPredicate] {
2999        &self.general_predicates[index]
3000    }
3001
3002    /// Disable a certain capture within a query.
3003    ///
3004    /// This prevents the capture from being returned in matches, and also
3005    /// avoids any resource usage associated with recording the capture.
3006    #[doc(alias = "ts_query_disable_capture")]
3007    pub fn disable_capture(&mut self, name: &str) {
3008        unsafe {
3009            ffi::ts_query_disable_capture(
3010                self.ptr.as_ptr(),
3011                name.as_bytes().as_ptr().cast::<c_char>(),
3012                name.len() as u32,
3013            );
3014        }
3015    }
3016
3017    /// Disable a certain pattern within a query.
3018    ///
3019    /// This prevents the pattern from matching, and also avoids any resource
3020    /// usage associated with the pattern.
3021    #[doc(alias = "ts_query_disable_pattern")]
3022    pub fn disable_pattern(&mut self, index: usize) {
3023        unsafe { ffi::ts_query_disable_pattern(self.ptr.as_ptr(), index as u32) }
3024    }
3025
3026    /// Create a deep copy of this query.
3027    ///
3028    /// Queries are shareable across threads and cursors without cloning. You
3029    /// should only need this when you want an independent copy to mutate (e.g.
3030    /// via [`disable_capture`][Query::disable_capture] or
3031    /// [`disable_pattern`][Query::disable_pattern]).
3032    #[doc(alias = "ts_query_copy")]
3033    #[must_use]
3034    pub fn deep_clone(&self) -> Self {
3035        let ptr = unsafe { ffi::ts_query_copy(self.ptr.as_ptr()) };
3036        // SAFETY: from_raw_parts re-derives all Rust-side fields from the C
3037        // object. The source string is only used for predicate error row
3038        // numbers. Since this is a copy of an already-valid query, it cannot
3039        // return an error.
3040        unsafe { Self::from_raw_parts(ptr, "").unwrap_unchecked() }
3041    }
3042
3043    /// Check if a given pattern within a query has a single root node.
3044    #[doc(alias = "ts_query_is_pattern_rooted")]
3045    #[must_use]
3046    pub fn is_pattern_rooted(&self, index: usize) -> bool {
3047        unsafe { ffi::ts_query_is_pattern_rooted(self.ptr.as_ptr(), index as u32) }
3048    }
3049
3050    /// Check if a given pattern within a query has a single root node.
3051    #[doc(alias = "ts_query_is_pattern_non_local")]
3052    #[must_use]
3053    pub fn is_pattern_non_local(&self, index: usize) -> bool {
3054        unsafe { ffi::ts_query_is_pattern_non_local(self.ptr.as_ptr(), index as u32) }
3055    }
3056
3057    /// Check if a given step in a query is 'definite'.
3058    ///
3059    /// A query step is 'definite' if its parent pattern will be guaranteed to
3060    /// match successfully once it reaches the step.
3061    #[doc(alias = "ts_query_is_pattern_guaranteed_at_step")]
3062    #[must_use]
3063    pub fn is_pattern_guaranteed_at_step(&self, byte_offset: usize) -> bool {
3064        unsafe {
3065            ffi::ts_query_is_pattern_guaranteed_at_step(self.ptr.as_ptr(), byte_offset as u32)
3066        }
3067    }
3068
3069    fn parse_property(
3070        row: usize,
3071        function_name: &str,
3072        capture_names: &[&str],
3073        string_values: &[&str],
3074        args: &[ffi::TSQueryPredicateStep],
3075    ) -> Result<QueryProperty, QueryError> {
3076        if args.is_empty() || args.len() > 3 {
3077            return Err(predicate_error(
3078                row,
3079                format!(
3080                    "Wrong number of arguments to {function_name} predicate. Expected 1 to 3, got {}.",
3081                    args.len(),
3082                ),
3083            ));
3084        }
3085
3086        let mut capture_id = None;
3087        let mut key = None;
3088        let mut value = None;
3089
3090        for arg in args {
3091            if arg.type_ == ffi::TSQueryPredicateStepTypeCapture {
3092                if capture_id.is_some() {
3093                    return Err(predicate_error(
3094                        row,
3095                        format!(
3096                            "Invalid arguments to {function_name} predicate. Unexpected second capture name @{}",
3097                            capture_names[arg.value_id as usize]
3098                        ),
3099                    ));
3100                }
3101                capture_id = Some(arg.value_id as usize);
3102            } else if key.is_none() {
3103                key = Some(&string_values[arg.value_id as usize]);
3104            } else if value.is_none() {
3105                value = Some(string_values[arg.value_id as usize]);
3106            } else {
3107                return Err(predicate_error(
3108                    row,
3109                    format!(
3110                        "Invalid arguments to {function_name} predicate. Unexpected third argument @{}",
3111                        string_values[arg.value_id as usize]
3112                    ),
3113                ));
3114            }
3115        }
3116
3117        if let Some(key) = key {
3118            Ok(QueryProperty::new(key, value, capture_id))
3119        } else {
3120            Err(predicate_error(
3121                row,
3122                format!("Invalid arguments to {function_name} predicate. Missing key argument"),
3123            ))
3124        }
3125    }
3126}
3127
3128impl Default for QueryCursor {
3129    fn default() -> Self {
3130        Self::new()
3131    }
3132}
3133
3134impl QueryCursor {
3135    /// Create a new cursor for executing a given query.
3136    ///
3137    /// The cursor stores the state that is needed to iteratively search for
3138    /// matches.
3139    #[doc(alias = "ts_query_cursor_new")]
3140    #[must_use]
3141    pub fn new() -> Self {
3142        Self {
3143            ptr: unsafe { NonNull::new_unchecked(ffi::ts_query_cursor_new()) },
3144        }
3145    }
3146
3147    /// Return the maximum number of in-progress matches for this cursor.
3148    #[doc(alias = "ts_query_cursor_match_limit")]
3149    #[must_use]
3150    pub fn match_limit(&self) -> u32 {
3151        unsafe { ffi::ts_query_cursor_match_limit(self.ptr.as_ptr()) }
3152    }
3153
3154    /// Set the maximum number of in-progress matches for this cursor.  The
3155    /// limit must be > 0 and <= 65536.
3156    #[doc(alias = "ts_query_cursor_set_match_limit")]
3157    pub fn set_match_limit(&mut self, limit: u32) {
3158        unsafe {
3159            ffi::ts_query_cursor_set_match_limit(self.ptr.as_ptr(), limit);
3160        }
3161    }
3162
3163    /// Check if, on its last execution, this cursor exceeded its maximum number
3164    /// of in-progress matches.
3165    #[doc(alias = "ts_query_cursor_did_exceed_match_limit")]
3166    #[must_use]
3167    pub fn did_exceed_match_limit(&self) -> bool {
3168        unsafe { ffi::ts_query_cursor_did_exceed_match_limit(self.ptr.as_ptr()) }
3169    }
3170
3171    /// Iterate over all of the matches in the order that they were found.
3172    ///
3173    /// Each match contains the index of the pattern that matched, and a list of
3174    /// captures. Because multiple patterns can match the same set of nodes,
3175    /// one match may contain captures that appear *before* some of the
3176    /// captures from a previous match.
3177    ///
3178    /// Iterating over a `QueryMatches` object requires the `StreamingIterator`
3179    /// or `StreamingIteratorMut` trait to be in scope. This can be done via
3180    /// `use tree_sitter::StreamingIterator` or `use tree_sitter::StreamingIteratorMut`
3181    #[doc(alias = "ts_query_cursor_exec")]
3182    pub fn matches<'query, 'cursor: 'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>>(
3183        &'cursor mut self,
3184        query: &'query Query,
3185        node: Node<'tree>,
3186        text_provider: T,
3187    ) -> QueryMatches<'query, 'tree, 'static, T, I> {
3188        let ptr = self.ptr.as_ptr();
3189        unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
3190        QueryMatches {
3191            ptr,
3192            query,
3193            text_provider,
3194            buffer1: Vec::default(),
3195            buffer2: Vec::default(),
3196            current_match: None,
3197            _options: None,
3198            _phantom: PhantomData,
3199        }
3200    }
3201
3202    /// Iterate over all of the matches in the order that they were found, with options.
3203    ///
3204    /// Each match contains the index of the pattern that matched, and a list of
3205    /// captures. Because multiple patterns can match the same set of nodes,
3206    /// one match may contain captures that appear *before* some of the
3207    /// captures from a previous match.
3208    #[doc(alias = "ts_query_cursor_exec_with_options")]
3209    pub fn matches_with_options<
3210        'query,
3211        'cursor: 'query,
3212        'tree,
3213        'options,
3214        T: TextProvider<I>,
3215        I: AsRef<[u8]>,
3216    >(
3217        &'cursor mut self,
3218        query: &'query Query,
3219        node: Node<'tree>,
3220        text_provider: T,
3221        options: QueryCursorOptions<'options>,
3222    ) -> QueryMatches<'query, 'tree, 'options, T, I> {
3223        unsafe extern "C" fn progress(state: *mut ffi::TSQueryCursorState) -> bool {
3224            unsafe {
3225                let callback = (*state)
3226                    .payload
3227                    .cast::<QueryProgressCallback>()
3228                    .as_mut()
3229                    .unwrap();
3230                match callback(&QueryCursorState::from_raw(state)) {
3231                    ControlFlow::Continue(()) => false,
3232                    ControlFlow::Break(()) => true,
3233                }
3234            }
3235        }
3236
3237        let query_options = options.progress_callback.map(|cb| {
3238            QueryCursorOptionsDrop(
3239                Box::into_raw(Box::new(ffi::TSQueryCursorOptions {
3240                    payload: Box::into_raw(Box::new(cb)).cast::<c_void>(),
3241                    progress_callback: Some(progress),
3242                })),
3243                PhantomData,
3244            )
3245        });
3246
3247        let ptr = self.ptr.as_ptr();
3248        unsafe {
3249            ffi::ts_query_cursor_exec_with_options(
3250                ptr,
3251                query.ptr.as_ptr(),
3252                node.0,
3253                query_options.as_ref().map_or(ptr::null_mut(), |q| q.0),
3254            );
3255        }
3256        QueryMatches {
3257            ptr,
3258            query,
3259            text_provider,
3260            buffer1: Vec::default(),
3261            buffer2: Vec::default(),
3262            current_match: None,
3263            _options: query_options,
3264            _phantom: PhantomData,
3265        }
3266    }
3267
3268    /// Iterate over all of the individual captures in the order that they
3269    /// appear.
3270    ///
3271    /// This is useful if you don't care about which pattern matched, and just
3272    /// want a single, ordered sequence of captures.
3273    ///
3274    /// Iterating over a `QueryCaptures` object requires the `StreamingIterator`
3275    /// or `StreamingIteratorMut` trait to be in scope. This can be done via
3276    /// `use tree_sitter::StreamingIterator` or `use tree_sitter::StreamingIteratorMut`
3277    #[doc(alias = "ts_query_cursor_exec")]
3278    pub fn captures<'query, 'cursor: 'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>>(
3279        &'cursor mut self,
3280        query: &'query Query,
3281        node: Node<'tree>,
3282        text_provider: T,
3283    ) -> QueryCaptures<'query, 'tree, 'static, T, I> {
3284        let ptr = self.ptr.as_ptr();
3285        unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
3286        QueryCaptures {
3287            ptr,
3288            query,
3289            text_provider,
3290            buffer1: Vec::default(),
3291            buffer2: Vec::default(),
3292            current_match: None,
3293            _options: None,
3294            _phantom: PhantomData,
3295        }
3296    }
3297
3298    /// Iterate over all of the individual captures in the order that they
3299    /// appear, with options.
3300    ///
3301    /// This is useful if you don't care about which pattern matched, and just
3302    /// want a single, ordered sequence of captures.
3303    #[doc(alias = "ts_query_cursor_exec")]
3304    pub fn captures_with_options<
3305        'query,
3306        'cursor: 'query,
3307        'tree,
3308        'options,
3309        T: TextProvider<I>,
3310        I: AsRef<[u8]>,
3311    >(
3312        &'cursor mut self,
3313        query: &'query Query,
3314        node: Node<'tree>,
3315        text_provider: T,
3316        options: QueryCursorOptions<'options>,
3317    ) -> QueryCaptures<'query, 'tree, 'options, T, I> {
3318        unsafe extern "C" fn progress(state: *mut ffi::TSQueryCursorState) -> bool {
3319            unsafe {
3320                let callback = (*state)
3321                    .payload
3322                    .cast::<QueryProgressCallback>()
3323                    .as_mut()
3324                    .unwrap();
3325                match callback(&QueryCursorState::from_raw(state)) {
3326                    ControlFlow::Continue(()) => false,
3327                    ControlFlow::Break(()) => true,
3328                }
3329            }
3330        }
3331
3332        let query_options = options.progress_callback.map(|cb| {
3333            QueryCursorOptionsDrop(
3334                Box::into_raw(Box::new(ffi::TSQueryCursorOptions {
3335                    payload: Box::into_raw(Box::new(cb)).cast::<c_void>(),
3336                    progress_callback: Some(progress),
3337                })),
3338                PhantomData,
3339            )
3340        });
3341
3342        let ptr = self.ptr.as_ptr();
3343        unsafe {
3344            ffi::ts_query_cursor_exec_with_options(
3345                ptr,
3346                query.ptr.as_ptr(),
3347                node.0,
3348                query_options.as_ref().map_or(ptr::null_mut(), |q| q.0),
3349            );
3350        }
3351        QueryCaptures {
3352            ptr,
3353            query,
3354            text_provider,
3355            buffer1: Vec::default(),
3356            buffer2: Vec::default(),
3357            current_match: None,
3358            _options: query_options,
3359            _phantom: PhantomData,
3360        }
3361    }
3362
3363    /// Set the range in which the query will be executed, in terms of byte
3364    /// offsets.
3365    #[doc(alias = "ts_query_cursor_set_byte_range")]
3366    pub fn set_byte_range(&mut self, range: ops::Range<usize>) -> &mut Self {
3367        unsafe {
3368            ffi::ts_query_cursor_set_byte_range(
3369                self.ptr.as_ptr(),
3370                range.start as u32,
3371                range.end as u32,
3372            );
3373        }
3374        self
3375    }
3376
3377    /// Set the range in which the query will be executed, in terms of rows and
3378    /// columns.
3379    #[doc(alias = "ts_query_cursor_set_point_range")]
3380    pub fn set_point_range(&mut self, range: ops::Range<Point>) -> &mut Self {
3381        unsafe {
3382            ffi::ts_query_cursor_set_point_range(
3383                self.ptr.as_ptr(),
3384                range.start.into(),
3385                range.end.into(),
3386            );
3387        }
3388        self
3389    }
3390
3391    /// Set the byte range within which all matches must be fully contained.
3392    ///
3393    /// Set the range of bytes in which matches will be searched for. In contrast to
3394    /// `ts_query_cursor_set_byte_range`, this will restrict the query cursor to only return
3395    /// matches where _all_ nodes are _fully_ contained within the given range. Both functions
3396    /// can be used together, e.g. to search for any matches that intersect line 5000, as
3397    /// long as they are fully contained within lines 4500-5500
3398    #[doc(alias = "ts_query_cursor_set_containing_byte_range")]
3399    pub fn set_containing_byte_range(&mut self, range: ops::Range<usize>) -> &mut Self {
3400        unsafe {
3401            ffi::ts_query_cursor_set_containing_byte_range(
3402                self.ptr.as_ptr(),
3403                range.start as u32,
3404                range.end as u32,
3405            );
3406        }
3407        self
3408    }
3409
3410    /// Set the point range within which all matches must be fully contained.
3411    ///
3412    /// Set the range of bytes in which matches will be searched for. In contrast to
3413    /// `ts_query_cursor_set_point_range`, this will restrict the query cursor to only return
3414    /// matches where _all_ nodes are _fully_ contained within the given range. Both functions
3415    /// can be used together, e.g. to search for any matches that intersect line 5000, as
3416    /// long as they are fully contained within lines 4500-5500
3417    #[doc(alias = "ts_query_cursor_set_containing_point_range")]
3418    pub fn set_containing_point_range(&mut self, range: ops::Range<Point>) -> &mut Self {
3419        unsafe {
3420            ffi::ts_query_cursor_set_containing_point_range(
3421                self.ptr.as_ptr(),
3422                range.start.into(),
3423                range.end.into(),
3424            );
3425        }
3426        self
3427    }
3428
3429    /// Set the maximum start depth for a query cursor.
3430    ///
3431    /// This prevents cursors from exploring children nodes at a certain depth.
3432    /// Note if a pattern includes many children, then they will still be
3433    /// checked.
3434    ///
3435    /// The zero max start depth value can be used as a special behavior and
3436    /// it helps to destructure a subtree by staying on a node and using
3437    /// captures for interested parts. Note that the zero max start depth
3438    /// only limits a search depth for a pattern's root node but other nodes
3439    /// that are parts of the pattern may be searched at any depth depending on
3440    /// what is defined by the pattern structure.
3441    ///
3442    /// Set to `None` to remove the maximum start depth.
3443    #[doc(alias = "ts_query_cursor_set_max_start_depth")]
3444    pub fn set_max_start_depth(&mut self, max_start_depth: Option<u32>) -> &mut Self {
3445        unsafe {
3446            ffi::ts_query_cursor_set_max_start_depth(
3447                self.ptr.as_ptr(),
3448                max_start_depth.unwrap_or(u32::MAX),
3449            );
3450        }
3451        self
3452    }
3453}
3454
3455impl<'tree> QueryMatch<'_, 'tree> {
3456    #[must_use]
3457    pub const fn id(&self) -> u32 {
3458        self.id
3459    }
3460
3461    #[must_use]
3462    pub const fn captures(&self) -> &[QueryCapture<'tree>] {
3463        self.captures
3464    }
3465
3466    #[doc(alias = "ts_query_cursor_remove_match")]
3467    pub fn remove(&self) {
3468        unsafe { ffi::ts_query_cursor_remove_match(self.cursor, self.id) }
3469    }
3470
3471    pub fn nodes_for_capture_index(
3472        &self,
3473        capture_ix: u32,
3474    ) -> impl Iterator<Item = Node<'tree>> + '_ {
3475        self.captures
3476            .iter()
3477            .filter_map(move |capture| (capture.index == capture_ix).then_some(capture.node))
3478    }
3479
3480    fn new(m: &ffi::TSQueryMatch, cursor: *mut ffi::TSQueryCursor) -> Self {
3481        QueryMatch {
3482            cursor,
3483            id: m.id,
3484            pattern_index: m.pattern_index as usize,
3485            captures: if m.capture_count > 0 {
3486                unsafe {
3487                    slice::from_raw_parts(
3488                        m.captures.cast::<QueryCapture<'tree>>(),
3489                        m.capture_count as usize,
3490                    )
3491                }
3492            } else {
3493                Default::default()
3494            },
3495        }
3496    }
3497
3498    pub fn satisfies_text_predicates<I: AsRef<[u8]>>(
3499        &self,
3500        query: &Query,
3501        buffer1: &mut Vec<u8>,
3502        buffer2: &mut Vec<u8>,
3503        text_provider: &mut impl TextProvider<I>,
3504    ) -> bool {
3505        struct NodeText<'a, T> {
3506            buffer: &'a mut Vec<u8>,
3507            first_chunk: Option<T>,
3508        }
3509        impl<'a, T: AsRef<[u8]>> NodeText<'a, T> {
3510            const fn new(buffer: &'a mut Vec<u8>) -> Self {
3511                Self {
3512                    buffer,
3513                    first_chunk: None,
3514                }
3515            }
3516
3517            fn get_text(&mut self, chunks: &mut impl Iterator<Item = T>) -> &[u8] {
3518                self.first_chunk = chunks.next();
3519                if let Some(next_chunk) = chunks.next() {
3520                    self.buffer.clear();
3521                    self.buffer
3522                        .extend_from_slice(self.first_chunk.as_ref().unwrap().as_ref());
3523                    self.buffer.extend_from_slice(next_chunk.as_ref());
3524                    for chunk in chunks {
3525                        self.buffer.extend_from_slice(chunk.as_ref());
3526                    }
3527                    self.buffer.as_slice()
3528                } else if let Some(ref first_chunk) = self.first_chunk {
3529                    first_chunk.as_ref()
3530                } else {
3531                    &[]
3532                }
3533            }
3534        }
3535
3536        let mut node_text1 = NodeText::new(buffer1);
3537        let mut node_text2 = NodeText::new(buffer2);
3538
3539        query.text_predicates[self.pattern_index]
3540            .iter()
3541            .all(|predicate| match predicate {
3542                TextPredicateCapture::EqCapture(i, j, is_positive, match_all_nodes) => {
3543                    let mut nodes_1 = self.nodes_for_capture_index(*i).peekable();
3544                    let mut nodes_2 = self.nodes_for_capture_index(*j).peekable();
3545                    while nodes_1.peek().is_some() && nodes_2.peek().is_some() {
3546                        let node1 = nodes_1.next().unwrap();
3547                        let node2 = nodes_2.next().unwrap();
3548                        let mut text1 = text_provider.text(node1);
3549                        let mut text2 = text_provider.text(node2);
3550                        let text1 = node_text1.get_text(&mut text1);
3551                        let text2 = node_text2.get_text(&mut text2);
3552                        let is_positive_match = text1 == text2;
3553                        if is_positive_match != *is_positive && *match_all_nodes {
3554                            return false;
3555                        }
3556                        if is_positive_match == *is_positive && !*match_all_nodes {
3557                            return true;
3558                        }
3559                    }
3560                    nodes_1.next().is_none() && nodes_2.next().is_none()
3561                }
3562                TextPredicateCapture::EqString(i, s, is_positive, match_all_nodes) => {
3563                    let nodes = self.nodes_for_capture_index(*i);
3564                    for node in nodes {
3565                        let mut text = text_provider.text(node);
3566                        let text = node_text1.get_text(&mut text);
3567                        let is_positive_match = text == s.as_bytes();
3568                        if is_positive_match != *is_positive && *match_all_nodes {
3569                            return false;
3570                        }
3571                        if is_positive_match == *is_positive && !*match_all_nodes {
3572                            return true;
3573                        }
3574                    }
3575                    true
3576                }
3577                TextPredicateCapture::MatchString(i, r, is_positive, match_all_nodes) => {
3578                    let nodes = self.nodes_for_capture_index(*i);
3579                    for node in nodes {
3580                        let mut text = text_provider.text(node);
3581                        let text = node_text1.get_text(&mut text);
3582                        let is_positive_match = r.is_match(text);
3583                        if is_positive_match != *is_positive && *match_all_nodes {
3584                            return false;
3585                        }
3586                        if is_positive_match == *is_positive && !*match_all_nodes {
3587                            return true;
3588                        }
3589                    }
3590                    true
3591                }
3592                TextPredicateCapture::AnyString(i, v, is_positive) => {
3593                    let nodes = self.nodes_for_capture_index(*i);
3594                    for node in nodes {
3595                        let mut text = text_provider.text(node);
3596                        let text = node_text1.get_text(&mut text);
3597                        if (v.iter().any(|s| text == s.as_bytes())) != *is_positive {
3598                            return false;
3599                        }
3600                    }
3601                    true
3602                }
3603            })
3604    }
3605}
3606
3607impl QueryProperty {
3608    #[must_use]
3609    pub fn new(key: &str, value: Option<&str>, capture_id: Option<usize>) -> Self {
3610        Self {
3611            capture_id,
3612            key: key.to_string().into(),
3613            value: value.map(|s| s.to_string().into()),
3614        }
3615    }
3616}
3617
3618/// Provide a `StreamingIterator` instead of the traditional `Iterator`, as the
3619/// underlying object in the C library gets updated on each iteration. Copies would
3620/// have their internal state overwritten, leading to Undefined Behavior
3621impl<'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>> StreamingIterator
3622    for QueryMatches<'query, 'tree, '_, T, I>
3623{
3624    type Item = QueryMatch<'query, 'tree>;
3625
3626    fn advance(&mut self) {
3627        self.current_match = unsafe {
3628            loop {
3629                let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
3630                if ffi::ts_query_cursor_next_match(self.ptr, m.as_mut_ptr()) {
3631                    let result = QueryMatch::new(&m.assume_init(), self.ptr);
3632                    if result.satisfies_text_predicates(
3633                        self.query,
3634                        &mut self.buffer1,
3635                        &mut self.buffer2,
3636                        &mut self.text_provider,
3637                    ) {
3638                        break Some(result);
3639                    }
3640                } else {
3641                    break None;
3642                }
3643            }
3644        };
3645    }
3646
3647    fn get(&self) -> Option<&Self::Item> {
3648        self.current_match.as_ref()
3649    }
3650}
3651
3652impl<T: TextProvider<I>, I: AsRef<[u8]>> StreamingIteratorMut for QueryMatches<'_, '_, '_, T, I> {
3653    fn get_mut(&mut self) -> Option<&mut Self::Item> {
3654        self.current_match.as_mut()
3655    }
3656}
3657
3658impl<'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>> StreamingIterator
3659    for QueryCaptures<'query, 'tree, '_, T, I>
3660{
3661    type Item = (QueryMatch<'query, 'tree>, usize);
3662
3663    fn advance(&mut self) {
3664        self.current_match = unsafe {
3665            loop {
3666                let mut capture_index = 0u32;
3667                let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
3668                if ffi::ts_query_cursor_next_capture(
3669                    self.ptr,
3670                    m.as_mut_ptr(),
3671                    core::ptr::addr_of_mut!(capture_index),
3672                ) {
3673                    let result = QueryMatch::new(&m.assume_init(), self.ptr);
3674                    if result.satisfies_text_predicates(
3675                        self.query,
3676                        &mut self.buffer1,
3677                        &mut self.buffer2,
3678                        &mut self.text_provider,
3679                    ) {
3680                        break Some((result, capture_index as usize));
3681                    }
3682                    result.remove();
3683                } else {
3684                    break None;
3685                }
3686            }
3687        }
3688    }
3689
3690    fn get(&self) -> Option<&Self::Item> {
3691        self.current_match.as_ref()
3692    }
3693}
3694
3695impl<T: TextProvider<I>, I: AsRef<[u8]>> StreamingIteratorMut for QueryCaptures<'_, '_, '_, T, I> {
3696    fn get_mut(&mut self) -> Option<&mut Self::Item> {
3697        self.current_match.as_mut()
3698    }
3699}
3700
3701impl<T: TextProvider<I>, I: AsRef<[u8]>> QueryMatches<'_, '_, '_, T, I> {
3702    #[doc(alias = "ts_query_cursor_set_byte_range")]
3703    pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
3704        unsafe {
3705            ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
3706        }
3707    }
3708
3709    #[doc(alias = "ts_query_cursor_set_point_range")]
3710    pub fn set_point_range(&mut self, range: ops::Range<Point>) {
3711        unsafe {
3712            ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
3713        }
3714    }
3715}
3716
3717impl<T: TextProvider<I>, I: AsRef<[u8]>> QueryCaptures<'_, '_, '_, T, I> {
3718    #[doc(alias = "ts_query_cursor_set_byte_range")]
3719    pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
3720        unsafe {
3721            ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
3722        }
3723    }
3724
3725    #[doc(alias = "ts_query_cursor_set_point_range")]
3726    pub fn set_point_range(&mut self, range: ops::Range<Point>) {
3727        unsafe {
3728            ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
3729        }
3730    }
3731}
3732
3733impl fmt::Debug for QueryMatch<'_, '_> {
3734    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3735        write!(
3736            f,
3737            "QueryMatch {{ id: {}, pattern_index: {}, captures: {:?} }}",
3738            self.id, self.pattern_index, self.captures
3739        )
3740    }
3741}
3742
3743impl<F, R, I> TextProvider<I> for F
3744where
3745    F: FnMut(Node) -> R,
3746    R: Iterator<Item = I>,
3747    I: AsRef<[u8]>,
3748{
3749    type I = R;
3750
3751    fn text(&mut self, node: Node) -> Self::I {
3752        (self)(node)
3753    }
3754}
3755
3756impl<'a> TextProvider<&'a [u8]> for &'a [u8] {
3757    type I = iter::Once<&'a [u8]>;
3758
3759    fn text(&mut self, node: Node) -> Self::I {
3760        iter::once(&self[node.byte_range()])
3761    }
3762}
3763
3764impl PartialEq for Query {
3765    fn eq(&self, other: &Self) -> bool {
3766        self.ptr == other.ptr
3767    }
3768}
3769
3770impl Drop for Query {
3771    fn drop(&mut self) {
3772        unsafe { ffi::ts_query_delete(self.ptr.as_ptr()) }
3773    }
3774}
3775
3776impl Drop for QueryCursor {
3777    fn drop(&mut self) {
3778        unsafe { ffi::ts_query_cursor_delete(self.ptr.as_ptr()) }
3779    }
3780}
3781
3782impl Point {
3783    #[must_use]
3784    pub const fn new(row: usize, column: usize) -> Self {
3785        Self { row, column }
3786    }
3787}
3788
3789impl fmt::Display for Point {
3790    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3791        write!(f, "({}, {})", self.row, self.column)
3792    }
3793}
3794
3795impl From<Point> for ffi::TSPoint {
3796    fn from(val: Point) -> Self {
3797        Self {
3798            row: val.row as u32,
3799            column: val.column as u32,
3800        }
3801    }
3802}
3803
3804impl From<ffi::TSPoint> for Point {
3805    fn from(point: ffi::TSPoint) -> Self {
3806        Self {
3807            row: point.row as usize,
3808            column: point.column as usize,
3809        }
3810    }
3811}
3812
3813impl From<Range> for ffi::TSRange {
3814    fn from(val: Range) -> Self {
3815        Self {
3816            start_byte: val.start_byte as u32,
3817            end_byte: val.end_byte as u32,
3818            start_point: val.start_point.into(),
3819            end_point: val.end_point.into(),
3820        }
3821    }
3822}
3823
3824impl From<ffi::TSRange> for Range {
3825    fn from(range: ffi::TSRange) -> Self {
3826        Self {
3827            start_byte: range.start_byte as usize,
3828            end_byte: range.end_byte as usize,
3829            start_point: range.start_point.into(),
3830            end_point: range.end_point.into(),
3831        }
3832    }
3833}
3834
3835impl From<&InputEdit> for ffi::TSInputEdit {
3836    fn from(val: &InputEdit) -> Self {
3837        Self {
3838            start_byte: val.start_byte as u32,
3839            old_end_byte: val.old_end_byte as u32,
3840            new_end_byte: val.new_end_byte as u32,
3841            start_point: val.start_position.into(),
3842            old_end_point: val.old_end_position.into(),
3843            new_end_point: val.new_end_position.into(),
3844        }
3845    }
3846}
3847
3848impl<'a> LossyUtf8<'a> {
3849    #[must_use]
3850    pub const fn new(bytes: &'a [u8]) -> Self {
3851        LossyUtf8 {
3852            bytes,
3853            in_replacement: false,
3854        }
3855    }
3856}
3857
3858impl<'a> Iterator for LossyUtf8<'a> {
3859    type Item = &'a str;
3860
3861    fn next(&mut self) -> Option<&'a str> {
3862        if self.bytes.is_empty() {
3863            return None;
3864        }
3865        if self.in_replacement {
3866            self.in_replacement = false;
3867            return Some("\u{fffd}");
3868        }
3869        match core::str::from_utf8(self.bytes) {
3870            Ok(valid) => {
3871                self.bytes = &[];
3872                Some(valid)
3873            }
3874            Err(error) => {
3875                if let Some(error_len) = error.error_len() {
3876                    let error_start = error.valid_up_to();
3877                    if error_start > 0 {
3878                        let result =
3879                            unsafe { core::str::from_utf8_unchecked(&self.bytes[..error_start]) };
3880                        self.bytes = &self.bytes[(error_start + error_len)..];
3881                        self.in_replacement = true;
3882                        Some(result)
3883                    } else {
3884                        self.bytes = &self.bytes[error_len..];
3885                        Some("\u{fffd}")
3886                    }
3887                } else {
3888                    None
3889                }
3890            }
3891        }
3892    }
3893}
3894
3895#[must_use]
3896const fn predicate_error(row: usize, message: String) -> QueryError {
3897    QueryError {
3898        kind: QueryErrorKind::Predicate,
3899        row,
3900        column: 0,
3901        offset: 0,
3902        message,
3903    }
3904}
3905
3906impl fmt::Display for IncludedRangesError {
3907    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3908        write!(f, "Incorrect range by index: {}", self.0)
3909    }
3910}
3911
3912impl fmt::Display for LanguageError {
3913    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3914        match self {
3915            Self::Version(version) => {
3916                write!(
3917                    f,
3918                    "Incompatible language version {version:#x}. Expected {LANGUAGE_VERSION:#x}",
3919                )
3920            }
3921            Self::NotParseable => {
3922                write!(f, "Language cannot be used for parsing.")
3923            }
3924            #[cfg(feature = "wasm")]
3925            Self::Wasm => {
3926                write!(f, "Failed to load the Wasm store.")
3927            }
3928        }
3929    }
3930}
3931
3932impl fmt::Display for QueryError {
3933    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3934        let msg = match self.kind {
3935            QueryErrorKind::Field => "Invalid field name ",
3936            QueryErrorKind::NodeType => "Invalid node type ",
3937            QueryErrorKind::Capture => "Invalid capture name ",
3938            QueryErrorKind::Predicate => "Invalid predicate: ",
3939            QueryErrorKind::Structure => "Impossible pattern:\n",
3940            QueryErrorKind::Syntax => "Invalid syntax:\n",
3941            QueryErrorKind::Language => "",
3942        };
3943        if msg.is_empty() {
3944            write!(f, "{}", self.message)
3945        } else {
3946            write!(
3947                f,
3948                "Query error at {}:{}. {}{}",
3949                self.row + 1,
3950                self.column + 1,
3951                msg,
3952                self.message
3953            )
3954        }
3955    }
3956}
3957
3958#[doc(hidden)]
3959#[must_use]
3960pub fn format_sexp(sexp: &str, initial_indent_level: usize) -> String {
3961    let sexp = sexp.trim();
3962    let mut indent_level = initial_indent_level;
3963    let mut formatted = String::with_capacity(sexp.len());
3964    let mut has_field = false;
3965
3966    let mut c_iter = sexp.chars().peekable();
3967    let mut scratch = String::with_capacity(sexp.len());
3968    let mut quote = '\0';
3969    let mut saw_paren = false;
3970    let mut did_last = false;
3971    let mut first_token = true;
3972    let mut quote_suffixes = quote_suffix_minimum_depths(sexp);
3973    let mut byte_offset = 0;
3974
3975    let mut fetch_next_str = |next: &mut String, payload_quote: char, open_nodes: usize| {
3976        let root_token = first_token;
3977        first_token = false;
3978        let open_nodes = if root_token { 1 } else { open_nodes };
3979        next.clear();
3980        let mut separated = false;
3981        while let Some(c) = c_iter.next() {
3982            byte_offset += c.len_utf8();
3983            if quote != '\0' {
3984                // `to_sexp` does not escape quotes in anonymous MISSING names or
3985                // quoted UNEXPECTED characters, so their node boundary disambiguates
3986                // the delimiter. Named MISSING payloads are emitted without delimiters.
3987                if c == quote
3988                    && quote_closing_depth(c_iter.clone()).is_some_and(|depth| depth <= open_nodes)
3989                {
3990                    quote = '\0';
3991                }
3992            } else if next.is_empty() && c == payload_quote {
3993                let suffixes = &mut quote_suffixes[usize::from(c == '"')];
3994                while suffixes
3995                    .last()
3996                    .is_some_and(|&(offset, _)| offset < byte_offset)
3997                {
3998                    suffixes.pop();
3999                }
4000                if suffixes
4001                    .last()
4002                    .is_some_and(|&(_, depth)| depth <= open_nodes)
4003                {
4004                    quote = c;
4005                }
4006            } else if root_token
4007                && next == "("
4008                && c == '"'
4009                && sexp.len() > 3
4010                && sexp.ends_with("\")")
4011            {
4012                quote = c;
4013            } else if c == ' ' {
4014                separated = true;
4015                break;
4016            } else if c == ')' {
4017                saw_paren = true;
4018                break;
4019            }
4020            next.push(c);
4021        }
4022
4023        if c_iter.peek().is_none() && next.is_empty() {
4024            if saw_paren {
4025                saw_paren = false;
4026                return Some(false);
4027            }
4028            if !did_last {
4029                did_last = true;
4030                return Some(false);
4031            }
4032            return None;
4033        }
4034        let has_payload = separated
4035            && (next == "(MISSING" || next == "(UNEXPECTED")
4036            && c_iter.peek().is_some_and(|&c| c != '(' && c != ')')
4037            && !sexp_field_follows(c_iter.clone());
4038        Some(has_payload)
4039    };
4040
4041    while let Some(has_payload) = fetch_next_str(
4042        &mut scratch,
4043        '\0',
4044        indent_level.saturating_sub(initial_indent_level),
4045    ) {
4046        if scratch.is_empty() && indent_level > initial_indent_level {
4047            indent_level -= 1;
4048            write!(formatted, ")").unwrap();
4049        } else if scratch.starts_with('(') {
4050            if has_field {
4051                has_field = false;
4052            } else {
4053                if indent_level > 0 {
4054                    writeln!(formatted).unwrap();
4055                    for _ in 0..indent_level {
4056                        write!(formatted, "  ").unwrap();
4057                    }
4058                }
4059                indent_level += 1;
4060            }
4061
4062            write!(formatted, "{scratch}").unwrap();
4063
4064            if has_payload {
4065                let payload_quote = if scratch == "(UNEXPECTED" { '\'' } else { '"' };
4066                fetch_next_str(
4067                    &mut scratch,
4068                    payload_quote,
4069                    indent_level.saturating_sub(initial_indent_level),
4070                )
4071                .unwrap();
4072                if scratch.is_empty() {
4073                    while indent_level > initial_indent_level {
4074                        indent_level -= 1;
4075                        write!(formatted, ")").unwrap();
4076                    }
4077                } else {
4078                    write!(formatted, " {scratch}").unwrap();
4079                }
4080            }
4081        } else if scratch.ends_with(':') {
4082            writeln!(formatted).unwrap();
4083            for _ in 0..indent_level {
4084                write!(formatted, "  ").unwrap();
4085            }
4086            write!(formatted, "{scratch} ").unwrap();
4087            has_field = true;
4088            indent_level += 1;
4089        }
4090    }
4091
4092    formatted
4093}
4094
4095fn sexp_field_follows(mut chars: impl Iterator<Item = char>) -> bool {
4096    let mut last = None;
4097    for c in chars.by_ref() {
4098        match c {
4099            '(' | ')' | '\'' | '"' => return false,
4100            ' ' => break,
4101            _ => last = Some(c),
4102        }
4103    }
4104    last == Some(':') && chars.next() == Some('(')
4105}
4106
4107fn quote_suffix_minimum_depths(sexp: &str) -> [Vec<(usize, usize)>; 2] {
4108    let mut suffixes: [Vec<(usize, usize)>; 2] = [Vec::new(), Vec::new()];
4109    for (offset, c) in sexp.char_indices().rev() {
4110        if c != '\'' && c != '"' {
4111            continue;
4112        }
4113        if let Some(depth) = quote_closing_depth(sexp[offset + 1..].chars()) {
4114            let quotes = &mut suffixes[usize::from(c == '"')];
4115            // A later, shallower candidate answers the same existence query for longer.
4116            if quotes.last().is_none_or(|&(_, minimum)| depth < minimum) {
4117                quotes.push((offset, depth));
4118            }
4119        }
4120    }
4121    suffixes
4122}
4123
4124fn quote_closing_depth(mut chars: impl Iterator<Item = char>) -> Option<usize> {
4125    match chars.next() {
4126        None => Some(0),
4127        Some(')') => {
4128            let mut depth = 1;
4129            for c in chars {
4130                match c {
4131                    ')' => depth += 1,
4132                    c if c.is_whitespace() => return Some(depth),
4133                    _ => return None,
4134                }
4135            }
4136            Some(depth)
4137        }
4138        _ => None,
4139    }
4140}
4141
4142pub fn wasm_stdlib_symbols() -> impl Iterator<Item = &'static str> {
4143    const WASM_STDLIB_SYMBOLS: &str = include_str!(concat!(env!("OUT_DIR"), "/stdlib-symbols.txt"));
4144
4145    WASM_STDLIB_SYMBOLS
4146        .lines()
4147        .map(|s| s.trim_matches(|c| c == '"' || c == ','))
4148}
4149
4150unsafe extern "C" {
4151    fn ts_node_string_pretty(node: ffi::TSNode, initial_indent_level: usize) -> *mut c_char;
4152    static mut ts_current_free: unsafe extern "C" fn(ptr: *mut c_void);
4153}
4154
4155/// Frees a pointer that was returned by a tree-sitter C API using whichever `free`
4156/// function is currently installed via [`set_allocator`] or [`ffi::ts_set_allocator`].
4157#[inline]
4158unsafe fn ts_free(ptr: *mut c_void) {
4159    let f = unsafe { core::ptr::addr_of!(ts_current_free).read() };
4160    unsafe { f(ptr) };
4161}
4162
4163/// A complete set of memory allocation functions for the core C library.
4164#[derive(Copy, Clone)]
4165pub struct Allocator {
4166    pub malloc: unsafe extern "C" fn(size: usize) -> *mut c_void,
4167    pub calloc: unsafe extern "C" fn(nmemb: usize, size: usize) -> *mut c_void,
4168    pub realloc: unsafe extern "C" fn(ptr: *mut c_void, size: usize) -> *mut c_void,
4169    pub free: unsafe extern "C" fn(ptr: *mut c_void),
4170}
4171
4172/// Replaces the memory allocation functions used by the core C library.
4173///
4174/// Pass `Some` to install an allocator, or `None` to restore libc defaults.
4175///
4176/// # Safety
4177///
4178/// All of the following must hold:
4179///
4180/// - The four functions must belong to a single allocator family.
4181///
4182/// - The functions must not return null for non-zero allocs.
4183///
4184/// - Returned pointers must satisfy the alignment that libc `malloc` provides.
4185///
4186/// - Call this before any other tree-sitter API call, and do not call it again
4187///   while live tree-sitter objects exist.
4188///
4189/// - This function is not thread-safe.
4190#[doc(alias = "ts_set_allocator")]
4191pub unsafe fn set_allocator(allocator: Option<Allocator>) {
4192    let (m, c, r, f) = match allocator {
4193        Some(a) => (
4194            Some(a.malloc),
4195            Some(a.calloc),
4196            Some(a.realloc),
4197            Some(a.free),
4198        ),
4199        None => (None, None, None, None),
4200    };
4201    unsafe { ffi::ts_set_allocator(m, c, r, f) };
4202}
4203
4204#[cfg(feature = "std")]
4205#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
4206impl error::Error for IncludedRangesError {}
4207#[cfg(feature = "std")]
4208#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
4209impl error::Error for LanguageError {}
4210#[cfg(feature = "std")]
4211#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
4212impl error::Error for QueryError {}
4213
4214#[cfg(not(target_family = "wasm"))]
4215unsafe impl Send for Language {}
4216#[cfg(not(target_family = "wasm"))]
4217unsafe impl Sync for Language {}
4218
4219unsafe impl Send for Node<'_> {}
4220unsafe impl Sync for Node<'_> {}
4221
4222#[cfg(not(target_family = "wasm"))]
4223unsafe impl Send for LookaheadIterator {}
4224#[cfg(not(target_family = "wasm"))]
4225unsafe impl Sync for LookaheadIterator {}
4226
4227#[cfg(not(target_family = "wasm"))]
4228unsafe impl Send for LookaheadNamesIterator<'_> {}
4229#[cfg(not(target_family = "wasm"))]
4230unsafe impl Sync for LookaheadNamesIterator<'_> {}
4231
4232#[cfg(not(target_family = "wasm"))]
4233unsafe impl Send for Parser {}
4234#[cfg(not(target_family = "wasm"))]
4235unsafe impl Sync for Parser {}
4236
4237unsafe impl Send for Query {}
4238unsafe impl Sync for Query {}
4239
4240unsafe impl Send for QueryCursor {}
4241unsafe impl Sync for QueryCursor {}
4242
4243unsafe impl Send for Tree {}
4244unsafe impl Sync for Tree {}
4245
4246unsafe impl Send for TreeCursor<'_> {}
4247unsafe impl Sync for TreeCursor<'_> {}