Skip to main content

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