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#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
47pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
48
49#[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#[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#[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#[doc(alias = "TSTree")]
91pub struct Tree(NonNull<ffi::TSTree>);
92
93#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
97pub struct Point {
98 pub row: usize,
99 pub column: usize,
100}
101
102#[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#[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 #[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 #[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#[doc(alias = "TSNode")]
167#[derive(Clone, Copy)]
168#[repr(transparent)]
169pub struct Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>);
170
171#[doc(alias = "TSParser")]
174pub struct Parser(NonNull<ffi::TSParser>);
175
176#[doc(alias = "TSLookaheadIterator")]
179pub struct LookaheadIterator(NonNull<ffi::TSLookaheadIterator>);
180struct LookaheadNamesIterator<'a>(&'a mut LookaheadIterator);
181
182pub 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
198pub 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 #[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 #[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#[derive(Debug, PartialEq, Eq)]
296pub enum LogType {
297 Parse,
298 Lex,
299}
300
301type FieldId = NonZeroU16;
302
303type Logger<'a> = Box<dyn FnMut(LogType, &str) + 'a>;
305
306type ParseProgressCallback<'a> = &'a mut dyn FnMut(&ParseState) -> ControlFlow<()>;
308
309type QueryProgressCallback<'a> = &'a mut dyn FnMut(&QueryCursorState) -> ControlFlow<()>;
311
312pub trait Decode {
313 fn decode(bytes: &[u8]) -> (i32, u32);
316}
317
318#[doc(alias = "TSTreeCursor")]
320pub struct TreeCursor<'tree>(ffi::TSTreeCursor, PhantomData<&'tree ()>);
321
322#[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#[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#[doc(alias = "TSQueryCursor")]
364pub struct QueryCursor {
365 ptr: NonNull<ffi::TSQueryCursor>,
366}
367
368#[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#[derive(Debug, PartialEq, Eq)]
384pub struct QueryPredicate {
385 pub operator: Box<str>,
386 pub args: Box<[QueryPredicateArg]>,
387}
388
389pub 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
397pub 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
409pub 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#[derive(Clone, Copy, Debug)]
435#[repr(C)]
436pub struct QueryCapture<'tree> {
437 pub node: Node<'tree>,
438 pub index: u32,
439}
440
441#[derive(Debug, PartialEq, Eq)]
445pub enum LanguageError {
446 Version(usize),
447 #[cfg(feature = "wasm")]
448 Wasm,
449}
450
451#[derive(Debug, PartialEq, Eq)]
453pub struct IncludedRangesError(pub usize);
454
455#[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)]
477enum 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
489pub 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[doc(alias = "ts_parser_reset")]
1354 pub fn reset(&mut self) {
1355 unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
1356 }
1357
1358 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
1477 pub fn walk(&self) -> TreeCursor {
1478 self.root_node().walk()
1479 }
1480
1481 #[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 #[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 #[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 #[must_use]
1580 pub fn id(&self) -> usize {
1581 self.0.id as usize
1582 }
1583
1584 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
1710 pub fn byte_range(&self) -> core::ops::Range<usize> {
1711 self.start_byte()..self.end_byte()
1712 }
1713
1714 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 _ => {
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 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 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 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 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 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 #[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 #[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 #[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 #[must_use]
2840 pub const fn capture_names(&self) -> &[&str] {
2841 &self.capture_names
2842 }
2843
2844 #[must_use]
2846 pub const fn capture_quantifiers(&self, index: usize) -> &[CaptureQuantifier] {
2847 &self.capture_quantifiers[index]
2848 }
2849
2850 #[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 #[must_use]
2863 pub const fn property_predicates(&self, index: usize) -> &[(QueryProperty, bool)] {
2864 &self.property_predicates[index]
2865 }
2866
2867 #[must_use]
2871 pub const fn property_settings(&self, index: usize) -> &[QueryProperty] {
2872 &self.property_settings[index]
2873 }
2874
2875 #[must_use]
2883 pub const fn general_predicates(&self, index: usize) -> &[QueryPredicate] {
2884 &self.general_predicates[index]
2885 }
2886
2887 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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
3473impl<'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 if c_iter.peek().is_none() && next.is_empty() {
3849 if saw_paren {
3850 saw_paren = false;
3852 return Some(());
3853 }
3854 if !did_last {
3855 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 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 write!(formatted, "{scratch}").unwrap();
3884
3885 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 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#[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<'_> {}