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::{c_char, c_void, CStr},
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 &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), &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<'cursor>(ffi::TSTreeCursor, PhantomData<&'cursor ()>);
321
322#[doc(alias = "TSQuery")]
324#[derive(Debug)]
325#[allow(clippy::type_complexity)]
326pub struct Query {
327 ptr: NonNull<ffi::TSQuery>,
328 capture_names: Box<[&'static str]>,
329 capture_quantifiers: Box<[Box<[CaptureQuantifier]>]>,
330 text_predicates: Box<[Box<[TextPredicateCapture]>]>,
331 property_settings: Box<[Box<[QueryProperty]>]>,
332 property_predicates: Box<[Box<[(QueryProperty, bool)]>]>,
333 general_predicates: Box<[Box<[QueryPredicate]>]>,
334}
335
336#[derive(Debug, PartialEq, Eq, Clone, Copy)]
338pub enum CaptureQuantifier {
339 Zero,
340 ZeroOrOne,
341 ZeroOrMore,
342 One,
343 OneOrMore,
344}
345
346impl From<ffi::TSQuantifier> for CaptureQuantifier {
347 fn from(value: ffi::TSQuantifier) -> Self {
348 match value {
349 ffi::TSQuantifierZero => Self::Zero,
350 ffi::TSQuantifierZeroOrOne => Self::ZeroOrOne,
351 ffi::TSQuantifierZeroOrMore => Self::ZeroOrMore,
352 ffi::TSQuantifierOne => Self::One,
353 ffi::TSQuantifierOneOrMore => Self::OneOrMore,
354 _ => unreachable!(),
355 }
356 }
357}
358
359#[doc(alias = "TSQueryCursor")]
361pub struct QueryCursor {
362 ptr: NonNull<ffi::TSQueryCursor>,
363}
364
365#[derive(Debug, PartialEq, Eq)]
367pub struct QueryProperty {
368 pub key: Box<str>,
369 pub value: Option<Box<str>>,
370 pub capture_id: Option<usize>,
371}
372
373#[derive(Debug, PartialEq, Eq)]
374pub enum QueryPredicateArg {
375 Capture(u32),
376 String(Box<str>),
377}
378
379#[derive(Debug, PartialEq, Eq)]
381pub struct QueryPredicate {
382 pub operator: Box<str>,
383 pub args: Box<[QueryPredicateArg]>,
384}
385
386pub struct QueryMatch<'cursor, 'tree> {
388 pub pattern_index: usize,
389 pub captures: &'cursor [QueryCapture<'tree>],
390 id: u32,
391 cursor: *mut ffi::TSQueryCursor,
392}
393
394pub struct QueryMatches<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> {
396 ptr: *mut ffi::TSQueryCursor,
397 query: &'query Query,
398 text_provider: T,
399 buffer1: Vec<u8>,
400 buffer2: Vec<u8>,
401 current_match: Option<QueryMatch<'query, 'tree>>,
402 _options: Option<QueryCursorOptionsDrop>,
403 _phantom: PhantomData<(&'tree (), I)>,
404}
405
406pub struct QueryCaptures<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> {
411 ptr: *mut ffi::TSQueryCursor,
412 query: &'query Query,
413 text_provider: T,
414 buffer1: Vec<u8>,
415 buffer2: Vec<u8>,
416 current_match: Option<(QueryMatch<'query, 'tree>, usize)>,
417 _options: Option<QueryCursorOptionsDrop>,
418 _phantom: PhantomData<(&'tree (), I)>,
419}
420
421pub trait TextProvider<I>
422where
423 I: AsRef<[u8]>,
424{
425 type I: Iterator<Item = I>;
426 fn text(&mut self, node: Node) -> Self::I;
427}
428
429#[derive(Clone, Copy, Debug)]
432#[repr(C)]
433pub struct QueryCapture<'tree> {
434 pub node: Node<'tree>,
435 pub index: u32,
436}
437
438#[derive(Debug, PartialEq, Eq)]
442pub enum LanguageError {
443 Version(usize),
444 #[cfg(feature = "wasm")]
445 Wasm,
446}
447
448#[derive(Debug, PartialEq, Eq)]
450pub struct IncludedRangesError(pub usize);
451
452#[derive(Debug, PartialEq, Eq)]
454pub struct QueryError {
455 pub row: usize,
456 pub column: usize,
457 pub offset: usize,
458 pub message: String,
459 pub kind: QueryErrorKind,
460}
461
462#[derive(Debug, PartialEq, Eq)]
463pub enum QueryErrorKind {
464 Syntax,
465 NodeType,
466 Field,
467 Capture,
468 Predicate,
469 Structure,
470 Language,
471}
472
473#[derive(Debug)]
474enum TextPredicateCapture {
480 EqString(u32, Box<str>, bool, bool),
481 EqCapture(u32, u32, bool, bool),
482 MatchString(u32, regex::bytes::Regex, bool, bool),
483 AnyString(u32, Box<[Box<str>]>, bool),
484}
485
486pub struct LossyUtf8<'a> {
489 bytes: &'a [u8],
490 in_replacement: bool,
491}
492
493impl Language {
494 #[must_use]
495 pub fn new(builder: LanguageFn) -> Self {
496 Self(unsafe { builder.into_raw()().cast() })
497 }
498
499 #[doc(alias = "ts_language_name")]
501 #[must_use]
502 pub fn name(&self) -> Option<&'static str> {
503 let ptr = unsafe { ffi::ts_language_name(self.0) };
504 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
505 }
506
507 #[doc(alias = "ts_language_abi_version")]
510 #[must_use]
511 pub fn abi_version(&self) -> usize {
512 unsafe { ffi::ts_language_abi_version(self.0) as usize }
513 }
514
515 #[doc(alias = "ts_language_metadata")]
521 #[must_use]
522 pub fn metadata(&self) -> Option<LanguageMetadata> {
523 unsafe {
524 let ptr = ffi::ts_language_metadata(self.0);
525 (!ptr.is_null()).then(|| (*ptr).into())
526 }
527 }
528
529 #[doc(alias = "ts_language_symbol_count")]
531 #[must_use]
532 pub fn node_kind_count(&self) -> usize {
533 unsafe { ffi::ts_language_symbol_count(self.0) as usize }
534 }
535
536 #[doc(alias = "ts_language_state_count")]
538 #[must_use]
539 pub fn parse_state_count(&self) -> usize {
540 unsafe { ffi::ts_language_state_count(self.0) as usize }
541 }
542
543 #[doc(alias = "ts_language_supertypes")]
545 #[must_use]
546 pub fn supertypes(&self) -> &[u16] {
547 let mut length = 0u32;
548 unsafe {
549 let ptr = ffi::ts_language_supertypes(self.0, core::ptr::addr_of_mut!(length));
550 if length == 0 {
551 &[]
552 } else {
553 slice::from_raw_parts(ptr.cast_mut(), length as usize)
554 }
555 }
556 }
557
558 #[doc(alias = "ts_language_supertype_map")]
560 #[must_use]
561 pub fn subtypes_for_supertype(&self, supertype: u16) -> &[u16] {
562 unsafe {
563 let mut length = 0u32;
564 let ptr = ffi::ts_language_subtypes(self.0, supertype, core::ptr::addr_of_mut!(length));
565 if length == 0 {
566 &[]
567 } else {
568 slice::from_raw_parts(ptr.cast_mut(), length as usize)
569 }
570 }
571 }
572
573 #[doc(alias = "ts_language_symbol_name")]
575 #[must_use]
576 pub fn node_kind_for_id(&self, id: u16) -> Option<&'static str> {
577 let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
578 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
579 }
580
581 #[doc(alias = "ts_language_symbol_for_name")]
583 #[must_use]
584 pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
585 unsafe {
586 ffi::ts_language_symbol_for_name(
587 self.0,
588 kind.as_bytes().as_ptr().cast::<c_char>(),
589 kind.len() as u32,
590 named,
591 )
592 }
593 }
594
595 #[must_use]
598 pub fn node_kind_is_named(&self, id: u16) -> bool {
599 unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeRegular }
600 }
601
602 #[must_use]
605 pub fn node_kind_is_visible(&self, id: u16) -> bool {
606 unsafe { ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolTypeAnonymous }
607 }
608
609 #[must_use]
611 pub fn node_kind_is_supertype(&self, id: u16) -> bool {
612 unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeSupertype }
613 }
614
615 #[doc(alias = "ts_language_field_count")]
617 #[must_use]
618 pub fn field_count(&self) -> usize {
619 unsafe { ffi::ts_language_field_count(self.0) as usize }
620 }
621
622 #[doc(alias = "ts_language_field_name_for_id")]
624 #[must_use]
625 pub fn field_name_for_id(&self, field_id: u16) -> Option<&'static str> {
626 let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
627 (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
628 }
629
630 #[doc(alias = "ts_language_field_id_for_name")]
632 #[must_use]
633 pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId> {
634 let field_name = field_name.as_ref();
635 let id = unsafe {
636 ffi::ts_language_field_id_for_name(
637 self.0,
638 field_name.as_ptr().cast::<c_char>(),
639 field_name.len() as u32,
640 )
641 };
642 FieldId::new(id)
643 }
644
645 #[doc(alias = "ts_language_next_state")]
654 #[must_use]
655 pub fn next_state(&self, state: u16, id: u16) -> u16 {
656 unsafe { ffi::ts_language_next_state(self.0, state, id) }
657 }
658
659 #[doc(alias = "ts_lookahead_iterator_new")]
673 #[must_use]
674 pub fn lookahead_iterator(&self, state: u16) -> Option<LookaheadIterator> {
675 let ptr = unsafe { ffi::ts_lookahead_iterator_new(self.0, state) };
676 (!ptr.is_null()).then(|| unsafe { LookaheadIterator::from_raw(ptr) })
677 }
678}
679
680impl From<LanguageFn> for Language {
681 fn from(value: LanguageFn) -> Self {
682 Self::new(value)
683 }
684}
685
686impl Clone for Language {
687 fn clone(&self) -> Self {
688 unsafe { Self(ffi::ts_language_copy(self.0)) }
689 }
690}
691
692impl Drop for Language {
693 fn drop(&mut self) {
694 unsafe { ffi::ts_language_delete(self.0) }
695 }
696}
697
698impl Deref for LanguageRef<'_> {
699 type Target = Language;
700
701 fn deref(&self) -> &Self::Target {
702 unsafe { &*(core::ptr::addr_of!(self.0).cast::<Language>()) }
703 }
704}
705
706impl Default for Parser {
707 fn default() -> Self {
708 Self::new()
709 }
710}
711
712impl Parser {
713 #[doc(alias = "ts_parser_new")]
715 #[must_use]
716 pub fn new() -> Self {
717 unsafe {
718 let parser = ffi::ts_parser_new();
719 Self(NonNull::new_unchecked(parser))
720 }
721 }
722
723 #[doc(alias = "ts_parser_set_language")]
732 pub fn set_language(&mut self, language: &Language) -> Result<(), LanguageError> {
733 let version = language.abi_version();
734 if (MIN_COMPATIBLE_LANGUAGE_VERSION..=LANGUAGE_VERSION).contains(&version) {
735 #[allow(unused_variables)]
736 let success = unsafe { ffi::ts_parser_set_language(self.0.as_ptr(), language.0) };
737 #[cfg(feature = "wasm")]
738 if !success {
739 return Err(LanguageError::Wasm);
740 }
741 Ok(())
742 } else {
743 Err(LanguageError::Version(version))
744 }
745 }
746
747 #[doc(alias = "ts_parser_language")]
749 #[must_use]
750 pub fn language(&self) -> Option<LanguageRef<'_>> {
751 let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
752 (!ptr.is_null()).then_some(LanguageRef(ptr, PhantomData))
753 }
754
755 #[doc(alias = "ts_parser_logger")]
757 #[must_use]
758 pub fn logger(&self) -> Option<&Logger> {
759 let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
760 unsafe { logger.payload.cast::<Logger>().as_ref() }
761 }
762
763 #[doc(alias = "ts_parser_set_logger")]
765 pub fn set_logger(&mut self, logger: Option<Logger>) {
766 let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
767 if !prev_logger.payload.is_null() {
768 drop(unsafe { Box::from_raw(prev_logger.payload.cast::<Logger>()) });
769 }
770
771 let c_logger = if let Some(logger) = logger {
772 let container = Box::new(logger);
773
774 unsafe extern "C" fn log(
775 payload: *mut c_void,
776 c_log_type: ffi::TSLogType,
777 c_message: *const c_char,
778 ) {
779 let callback = payload.cast::<Logger>().as_mut().unwrap();
780 if let Ok(message) = CStr::from_ptr(c_message).to_str() {
781 let log_type = if c_log_type == ffi::TSLogTypeParse {
782 LogType::Parse
783 } else {
784 LogType::Lex
785 };
786 callback(log_type, message);
787 }
788 }
789
790 let raw_container = Box::into_raw(container);
791
792 ffi::TSLogger {
793 payload: raw_container.cast::<c_void>(),
794 log: Some(log),
795 }
796 } else {
797 ffi::TSLogger {
798 payload: ptr::null_mut(),
799 log: None,
800 }
801 };
802
803 unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
804 }
805
806 #[doc(alias = "ts_parser_print_dot_graphs")]
811 #[cfg(not(target_os = "wasi"))]
812 #[cfg(feature = "std")]
813 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
814 pub fn print_dot_graphs(
815 &mut self,
816 #[cfg(unix)] file: &impl AsRawFd,
817 #[cfg(windows)] file: &impl AsRawHandle,
818 ) {
819 #[cfg(unix)]
820 {
821 let fd = file.as_raw_fd();
822 unsafe {
823 ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(fd));
824 }
825 }
826
827 #[cfg(windows)]
828 {
829 let handle = file.as_raw_handle();
830 unsafe {
831 ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(handle));
832 }
833 }
834 }
835
836 #[doc(alias = "ts_parser_print_dot_graphs")]
838 #[cfg(not(target_os = "wasi"))]
839 #[cfg(feature = "std")]
840 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
841 pub fn stop_printing_dot_graphs(&mut self) {
842 unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
843 }
844
845 #[doc(alias = "ts_parser_parse")]
856 pub fn parse(&mut self, text: impl AsRef<[u8]>, old_tree: Option<&Tree>) -> Option<Tree> {
857 let bytes = text.as_ref();
858 let len = bytes.len();
859 self.parse_with_options(
860 &mut |i, _| (i < len).then(|| &bytes[i..]).unwrap_or_default(),
861 old_tree,
862 None,
863 )
864 }
865
866 pub fn parse_with_options<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
878 &mut self,
879 callback: &mut F,
880 old_tree: Option<&Tree>,
881 options: Option<ParseOptions>,
882 ) -> Option<Tree> {
883 type Payload<'a, F, T> = (&'a mut F, Option<T>);
884
885 unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
887 let callback = (*state)
888 .payload
889 .cast::<ParseProgressCallback>()
890 .as_mut()
891 .unwrap();
892 match callback(&ParseState::from_raw(state)) {
893 ControlFlow::Continue(()) => false,
894 ControlFlow::Break(()) => true,
895 }
896 }
897
898 unsafe extern "C" fn read<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
900 payload: *mut c_void,
901 byte_offset: u32,
902 position: ffi::TSPoint,
903 bytes_read: *mut u32,
904 ) -> *const c_char {
905 let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
906 *text = Some(callback(byte_offset as usize, position.into()));
907 let slice = text.as_ref().unwrap().as_ref();
908 *bytes_read = slice.len() as u32;
909 slice.as_ptr().cast::<c_char>()
910 }
911
912 let empty_options = ffi::TSParseOptions {
913 payload: ptr::null_mut(),
914 progress_callback: None,
915 };
916
917 let mut callback_ptr;
918 let parse_options = if let Some(options) = options {
919 if let Some(cb) = options.progress_callback {
920 callback_ptr = cb;
921 ffi::TSParseOptions {
922 payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
923 progress_callback: Some(progress),
924 }
925 } else {
926 empty_options
927 }
928 } else {
929 empty_options
930 };
931
932 let mut payload: Payload<F, T> = (callback, None);
938
939 let c_input = ffi::TSInput {
940 payload: ptr::addr_of_mut!(payload).cast::<c_void>(),
941 read: Some(read::<T, F>),
942 encoding: ffi::TSInputEncodingUTF8,
943 decode: None,
944 };
945
946 let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
947 unsafe {
948 let c_new_tree = ffi::ts_parser_parse_with_options(
949 self.0.as_ptr(),
950 c_old_tree,
951 c_input,
952 parse_options,
953 );
954
955 NonNull::new(c_new_tree).map(Tree)
956 }
957 }
958
959 pub fn parse_utf16_le(
967 &mut self,
968 input: impl AsRef<[u16]>,
969 old_tree: Option<&Tree>,
970 ) -> Option<Tree> {
971 let code_points = input.as_ref();
972 let len = code_points.len();
973 self.parse_utf16_le_with_options(
974 &mut |i, _| (i < len).then(|| &code_points[i..]).unwrap_or_default(),
975 old_tree,
976 None,
977 )
978 }
979
980 pub fn parse_utf16_le_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
992 &mut self,
993 callback: &mut F,
994 old_tree: Option<&Tree>,
995 options: Option<ParseOptions>,
996 ) -> Option<Tree> {
997 type Payload<'a, F, T> = (&'a mut F, Option<T>);
998
999 unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
1000 let callback = (*state)
1001 .payload
1002 .cast::<ParseProgressCallback>()
1003 .as_mut()
1004 .unwrap();
1005 match callback(&ParseState::from_raw(state)) {
1006 ControlFlow::Continue(()) => false,
1007 ControlFlow::Break(()) => true,
1008 }
1009 }
1010
1011 unsafe extern "C" fn read<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1013 payload: *mut c_void,
1014 byte_offset: u32,
1015 position: ffi::TSPoint,
1016 bytes_read: *mut u32,
1017 ) -> *const c_char {
1018 let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
1019 *text = Some(callback(
1020 (byte_offset / 2) as usize,
1021 Point {
1022 row: position.row as usize,
1023 column: position.column as usize / 2,
1024 },
1025 ));
1026 let slice = text.as_ref().unwrap().as_ref();
1027 *bytes_read = slice.len() as u32 * 2;
1028 slice.as_ptr().cast::<c_char>()
1029 }
1030
1031 let empty_options = ffi::TSParseOptions {
1032 payload: ptr::null_mut(),
1033 progress_callback: None,
1034 };
1035
1036 let mut callback_ptr;
1037 let parse_options = if let Some(options) = options {
1038 if let Some(cb) = options.progress_callback {
1039 callback_ptr = cb;
1040 ffi::TSParseOptions {
1041 payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1042 progress_callback: Some(progress),
1043 }
1044 } else {
1045 empty_options
1046 }
1047 } else {
1048 empty_options
1049 };
1050
1051 let mut payload: Payload<F, T> = (callback, None);
1057
1058 let c_input = ffi::TSInput {
1059 payload: core::ptr::addr_of_mut!(payload).cast::<c_void>(),
1060 read: Some(read::<T, F>),
1061 encoding: ffi::TSInputEncodingUTF16LE,
1062 decode: None,
1063 };
1064
1065 let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1066 unsafe {
1067 let c_new_tree = ffi::ts_parser_parse_with_options(
1068 self.0.as_ptr(),
1069 c_old_tree,
1070 c_input,
1071 parse_options,
1072 );
1073
1074 NonNull::new(c_new_tree).map(Tree)
1075 }
1076 }
1077
1078 pub fn parse_utf16_be(
1086 &mut self,
1087 input: impl AsRef<[u16]>,
1088 old_tree: Option<&Tree>,
1089 ) -> Option<Tree> {
1090 let code_points = input.as_ref();
1091 let len = code_points.len();
1092 self.parse_utf16_be_with_options(
1093 &mut |i, _| if i < len { &code_points[i..] } else { &[] },
1094 old_tree,
1095 None,
1096 )
1097 }
1098
1099 pub fn parse_utf16_be_with_options<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1111 &mut self,
1112 callback: &mut F,
1113 old_tree: Option<&Tree>,
1114 options: Option<ParseOptions>,
1115 ) -> Option<Tree> {
1116 type Payload<'a, F, T> = (&'a mut F, Option<T>);
1117
1118 unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
1120 let callback = (*state)
1121 .payload
1122 .cast::<ParseProgressCallback>()
1123 .as_mut()
1124 .unwrap();
1125 match callback(&ParseState::from_raw(state)) {
1126 ControlFlow::Continue(()) => false,
1127 ControlFlow::Break(()) => true,
1128 }
1129 }
1130
1131 unsafe extern "C" fn read<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
1133 payload: *mut c_void,
1134 byte_offset: u32,
1135 position: ffi::TSPoint,
1136 bytes_read: *mut u32,
1137 ) -> *const c_char {
1138 let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
1139 *text = Some(callback(
1140 (byte_offset / 2) as usize,
1141 Point {
1142 row: position.row as usize,
1143 column: position.column as usize / 2,
1144 },
1145 ));
1146 let slice = text.as_ref().unwrap().as_ref();
1147 *bytes_read = slice.len() as u32 * 2;
1148 slice.as_ptr().cast::<c_char>()
1149 }
1150
1151 let empty_options = ffi::TSParseOptions {
1152 payload: ptr::null_mut(),
1153 progress_callback: None,
1154 };
1155
1156 let mut callback_ptr;
1157 let parse_options = if let Some(options) = options {
1158 if let Some(cb) = options.progress_callback {
1159 callback_ptr = cb;
1160 ffi::TSParseOptions {
1161 payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1162 progress_callback: Some(progress),
1163 }
1164 } else {
1165 empty_options
1166 }
1167 } else {
1168 empty_options
1169 };
1170
1171 let mut payload: Payload<F, T> = (callback, None);
1177
1178 let c_input = ffi::TSInput {
1179 payload: core::ptr::addr_of_mut!(payload).cast::<c_void>(),
1180 read: Some(read::<T, F>),
1181 encoding: ffi::TSInputEncodingUTF16BE,
1182 decode: None,
1183 };
1184
1185 let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1186 unsafe {
1187 let c_new_tree = ffi::ts_parser_parse_with_options(
1188 self.0.as_ptr(),
1189 c_old_tree,
1190 c_input,
1191 parse_options,
1192 );
1193
1194 NonNull::new(c_new_tree).map(Tree)
1195 }
1196 }
1197
1198 pub fn parse_custom_encoding<D: Decode, T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
1215 &mut self,
1216 callback: &mut F,
1217 old_tree: Option<&Tree>,
1218 options: Option<ParseOptions>,
1219 ) -> Option<Tree> {
1220 type Payload<'a, F, T> = (&'a mut F, Option<T>);
1221
1222 unsafe extern "C" fn progress(state: *mut ffi::TSParseState) -> bool {
1223 let callback = (*state)
1224 .payload
1225 .cast::<ParseProgressCallback>()
1226 .as_mut()
1227 .unwrap();
1228 match callback(&ParseState::from_raw(state)) {
1229 ControlFlow::Continue(()) => false,
1230 ControlFlow::Break(()) => true,
1231 }
1232 }
1233
1234 unsafe extern "C" fn decode_fn<D: Decode>(
1236 data: *const u8,
1237 len: u32,
1238 code_point: *mut i32,
1239 ) -> u32 {
1240 let (c, len) = D::decode(core::slice::from_raw_parts(data, len as usize));
1241 if let Some(code_point) = code_point.as_mut() {
1242 *code_point = c;
1243 }
1244 len
1245 }
1246
1247 unsafe extern "C" fn read<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
1249 payload: *mut c_void,
1250 byte_offset: u32,
1251 position: ffi::TSPoint,
1252 bytes_read: *mut u32,
1253 ) -> *const c_char {
1254 let (callback, text) = payload.cast::<Payload<F, T>>().as_mut().unwrap();
1255 *text = Some(callback(byte_offset as usize, position.into()));
1256 let slice = text.as_ref().unwrap().as_ref();
1257 *bytes_read = slice.len() as u32;
1258 slice.as_ptr().cast::<c_char>()
1259 }
1260
1261 let empty_options = ffi::TSParseOptions {
1262 payload: ptr::null_mut(),
1263 progress_callback: None,
1264 };
1265
1266 let mut callback_ptr;
1267 let parse_options = if let Some(options) = options {
1268 if let Some(cb) = options.progress_callback {
1269 callback_ptr = cb;
1270 ffi::TSParseOptions {
1271 payload: core::ptr::addr_of_mut!(callback_ptr).cast::<c_void>(),
1272 progress_callback: Some(progress),
1273 }
1274 } else {
1275 empty_options
1276 }
1277 } else {
1278 empty_options
1279 };
1280
1281 let mut payload: Payload<F, T> = (callback, None);
1287
1288 let c_input = ffi::TSInput {
1289 payload: core::ptr::addr_of_mut!(payload).cast::<c_void>(),
1290 read: Some(read::<T, F>),
1291 encoding: ffi::TSInputEncodingCustom,
1292 decode: Some(decode_fn::<D>),
1294 };
1295
1296 let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
1297 unsafe {
1298 let c_new_tree = ffi::ts_parser_parse_with_options(
1299 self.0.as_ptr(),
1300 c_old_tree,
1301 c_input,
1302 parse_options,
1303 );
1304
1305 NonNull::new(c_new_tree).map(Tree)
1306 }
1307 }
1308
1309 #[doc(alias = "ts_parser_reset")]
1316 pub fn reset(&mut self) {
1317 unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
1318 }
1319
1320 #[doc(alias = "ts_parser_set_included_ranges")]
1338 pub fn set_included_ranges(&mut self, ranges: &[Range]) -> Result<(), IncludedRangesError> {
1339 let ts_ranges = ranges.iter().copied().map(Into::into).collect::<Vec<_>>();
1340 let result = unsafe {
1341 ffi::ts_parser_set_included_ranges(
1342 self.0.as_ptr(),
1343 ts_ranges.as_ptr(),
1344 ts_ranges.len() as u32,
1345 )
1346 };
1347
1348 if result {
1349 Ok(())
1350 } else {
1351 let mut prev_end_byte = 0;
1352 for (i, range) in ranges.iter().enumerate() {
1353 if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
1354 return Err(IncludedRangesError(i));
1355 }
1356 prev_end_byte = range.end_byte;
1357 }
1358 Err(IncludedRangesError(0))
1359 }
1360 }
1361
1362 #[doc(alias = "ts_parser_included_ranges")]
1364 #[must_use]
1365 pub fn included_ranges(&self) -> Vec<Range> {
1366 let mut count = 0u32;
1367 unsafe {
1368 let ptr =
1369 ffi::ts_parser_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
1370 let ranges = slice::from_raw_parts(ptr, count as usize);
1371 let result = ranges.iter().copied().map(Into::into).collect();
1372 result
1373 }
1374 }
1375}
1376
1377impl Drop for Parser {
1378 fn drop(&mut self) {
1379 #[cfg(feature = "std")]
1380 #[cfg(not(target_os = "wasi"))]
1381 {
1382 self.stop_printing_dot_graphs();
1383 }
1384 self.set_logger(None);
1385 unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
1386 }
1387}
1388
1389#[cfg(windows)]
1390extern "C" {
1391 fn _open_osfhandle(osfhandle: isize, flags: core::ffi::c_int) -> core::ffi::c_int;
1392}
1393
1394impl Tree {
1395 #[doc(alias = "ts_tree_root_node")]
1397 #[must_use]
1398 pub fn root_node(&self) -> Node {
1399 Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
1400 }
1401
1402 #[doc(alias = "ts_tree_root_node_with_offset")]
1405 #[must_use]
1406 pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
1407 Node::new(unsafe {
1408 ffi::ts_tree_root_node_with_offset(
1409 self.0.as_ptr(),
1410 offset_bytes as u32,
1411 offset_extent.into(),
1412 )
1413 })
1414 .unwrap()
1415 }
1416
1417 #[doc(alias = "ts_tree_language")]
1419 #[must_use]
1420 pub fn language(&self) -> LanguageRef {
1421 LanguageRef(
1422 unsafe { ffi::ts_tree_language(self.0.as_ptr()) },
1423 PhantomData,
1424 )
1425 }
1426
1427 #[doc(alias = "ts_tree_edit")]
1433 pub fn edit(&mut self, edit: &InputEdit) {
1434 let edit = edit.into();
1435 unsafe { ffi::ts_tree_edit(self.0.as_ptr(), &edit) };
1436 }
1437
1438 #[must_use]
1440 pub fn walk(&self) -> TreeCursor {
1441 self.root_node().walk()
1442 }
1443
1444 #[doc(alias = "ts_tree_get_changed_ranges")]
1454 pub fn changed_ranges(&self, other: &Self) -> impl ExactSizeIterator<Item = Range> {
1455 let mut count = 0u32;
1456 unsafe {
1457 let ptr = ffi::ts_tree_get_changed_ranges(
1458 self.0.as_ptr(),
1459 other.0.as_ptr(),
1460 core::ptr::addr_of_mut!(count),
1461 );
1462 util::CBufferIter::new(ptr, count as usize).map(Into::into)
1463 }
1464 }
1465
1466 #[doc(alias = "ts_tree_included_ranges")]
1468 #[must_use]
1469 pub fn included_ranges(&self) -> Vec<Range> {
1470 let mut count = 0u32;
1471 unsafe {
1472 let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), core::ptr::addr_of_mut!(count));
1473 let ranges = slice::from_raw_parts(ptr, count as usize);
1474 let result = ranges.iter().copied().map(Into::into).collect();
1475 (FREE_FN)(ptr.cast::<c_void>());
1476 result
1477 }
1478 }
1479
1480 #[doc(alias = "ts_tree_print_dot_graph")]
1485 #[cfg(not(target_os = "wasi"))]
1486 #[cfg(feature = "std")]
1487 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1488 pub fn print_dot_graph(
1489 &self,
1490 #[cfg(unix)] file: &impl AsRawFd,
1491 #[cfg(windows)] file: &impl AsRawHandle,
1492 ) {
1493 #[cfg(unix)]
1494 {
1495 let fd = file.as_raw_fd();
1496 unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1497 }
1498
1499 #[cfg(windows)]
1500 {
1501 let handle = file.as_raw_handle();
1502 let fd = unsafe { _open_osfhandle(handle as isize, 0) };
1503 unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
1504 }
1505 }
1506}
1507
1508impl fmt::Debug for Tree {
1509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1510 write!(f, "{{Tree {:?}}}", self.root_node())
1511 }
1512}
1513
1514impl Drop for Tree {
1515 fn drop(&mut self) {
1516 unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
1517 }
1518}
1519
1520impl Clone for Tree {
1521 fn clone(&self) -> Self {
1522 unsafe { Self(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
1523 }
1524}
1525
1526impl<'tree> Node<'tree> {
1527 fn new(node: ffi::TSNode) -> Option<Self> {
1528 (!node.id.is_null()).then_some(Node(node, PhantomData))
1529 }
1530
1531 #[must_use]
1542 pub fn id(&self) -> usize {
1543 self.0.id as usize
1544 }
1545
1546 #[doc(alias = "ts_node_symbol")]
1548 #[must_use]
1549 pub fn kind_id(&self) -> u16 {
1550 unsafe { ffi::ts_node_symbol(self.0) }
1551 }
1552
1553 #[doc(alias = "ts_node_grammar_symbol")]
1556 #[must_use]
1557 pub fn grammar_id(&self) -> u16 {
1558 unsafe { ffi::ts_node_grammar_symbol(self.0) }
1559 }
1560
1561 #[doc(alias = "ts_node_type")]
1563 #[must_use]
1564 pub fn kind(&self) -> &'static str {
1565 unsafe { CStr::from_ptr(ffi::ts_node_type(self.0)) }
1566 .to_str()
1567 .unwrap()
1568 }
1569
1570 #[doc(alias = "ts_node_grammar_type")]
1573 #[must_use]
1574 pub fn grammar_name(&self) -> &'static str {
1575 unsafe { CStr::from_ptr(ffi::ts_node_grammar_type(self.0)) }
1576 .to_str()
1577 .unwrap()
1578 }
1579
1580 #[doc(alias = "ts_node_language")]
1582 #[must_use]
1583 pub fn language(&self) -> LanguageRef {
1584 LanguageRef(unsafe { ffi::ts_node_language(self.0) }, PhantomData)
1585 }
1586
1587 #[doc(alias = "ts_node_is_named")]
1592 #[must_use]
1593 pub fn is_named(&self) -> bool {
1594 unsafe { ffi::ts_node_is_named(self.0) }
1595 }
1596
1597 #[doc(alias = "ts_node_is_extra")]
1602 #[must_use]
1603 pub fn is_extra(&self) -> bool {
1604 unsafe { ffi::ts_node_is_extra(self.0) }
1605 }
1606
1607 #[doc(alias = "ts_node_has_changes")]
1609 #[must_use]
1610 pub fn has_changes(&self) -> bool {
1611 unsafe { ffi::ts_node_has_changes(self.0) }
1612 }
1613
1614 #[doc(alias = "ts_node_has_error")]
1617 #[must_use]
1618 pub fn has_error(&self) -> bool {
1619 unsafe { ffi::ts_node_has_error(self.0) }
1620 }
1621
1622 #[doc(alias = "ts_node_is_error")]
1627 #[must_use]
1628 pub fn is_error(&self) -> bool {
1629 unsafe { ffi::ts_node_is_error(self.0) }
1630 }
1631
1632 #[doc(alias = "ts_node_parse_state")]
1634 #[must_use]
1635 pub fn parse_state(&self) -> u16 {
1636 unsafe { ffi::ts_node_parse_state(self.0) }
1637 }
1638
1639 #[doc(alias = "ts_node_next_parse_state")]
1641 #[must_use]
1642 pub fn next_parse_state(&self) -> u16 {
1643 unsafe { ffi::ts_node_next_parse_state(self.0) }
1644 }
1645
1646 #[doc(alias = "ts_node_is_missing")]
1651 #[must_use]
1652 pub fn is_missing(&self) -> bool {
1653 unsafe { ffi::ts_node_is_missing(self.0) }
1654 }
1655
1656 #[doc(alias = "ts_node_start_byte")]
1658 #[must_use]
1659 pub fn start_byte(&self) -> usize {
1660 unsafe { ffi::ts_node_start_byte(self.0) as usize }
1661 }
1662
1663 #[doc(alias = "ts_node_end_byte")]
1665 #[must_use]
1666 pub fn end_byte(&self) -> usize {
1667 unsafe { ffi::ts_node_end_byte(self.0) as usize }
1668 }
1669
1670 #[must_use]
1672 pub fn byte_range(&self) -> core::ops::Range<usize> {
1673 self.start_byte()..self.end_byte()
1674 }
1675
1676 #[must_use]
1679 pub fn range(&self) -> Range {
1680 Range {
1681 start_byte: self.start_byte(),
1682 end_byte: self.end_byte(),
1683 start_point: self.start_position(),
1684 end_point: self.end_position(),
1685 }
1686 }
1687
1688 #[doc(alias = "ts_node_start_point")]
1690 #[must_use]
1691 pub fn start_position(&self) -> Point {
1692 let result = unsafe { ffi::ts_node_start_point(self.0) };
1693 result.into()
1694 }
1695
1696 #[doc(alias = "ts_node_end_point")]
1698 #[must_use]
1699 pub fn end_position(&self) -> Point {
1700 let result = unsafe { ffi::ts_node_end_point(self.0) };
1701 result.into()
1702 }
1703
1704 #[doc(alias = "ts_node_child")]
1711 #[must_use]
1712 pub fn child(&self, i: u32) -> Option<Self> {
1713 Self::new(unsafe { ffi::ts_node_child(self.0, i) })
1714 }
1715
1716 #[doc(alias = "ts_node_child_count")]
1718 #[must_use]
1719 pub fn child_count(&self) -> usize {
1720 unsafe { ffi::ts_node_child_count(self.0) as usize }
1721 }
1722
1723 #[doc(alias = "ts_node_named_child")]
1730 #[must_use]
1731 pub fn named_child(&self, i: u32) -> Option<Self> {
1732 Self::new(unsafe { ffi::ts_node_named_child(self.0, i) })
1733 }
1734
1735 #[doc(alias = "ts_node_named_child_count")]
1739 #[must_use]
1740 pub fn named_child_count(&self) -> usize {
1741 unsafe { ffi::ts_node_named_child_count(self.0) as usize }
1742 }
1743
1744 #[doc(alias = "ts_node_child_by_field_name")]
1749 #[must_use]
1750 pub fn child_by_field_name(&self, field_name: impl AsRef<[u8]>) -> Option<Self> {
1751 let field_name = field_name.as_ref();
1752 Self::new(unsafe {
1753 ffi::ts_node_child_by_field_name(
1754 self.0,
1755 field_name.as_ptr().cast::<c_char>(),
1756 field_name.len() as u32,
1757 )
1758 })
1759 }
1760
1761 #[doc(alias = "ts_node_child_by_field_id")]
1766 #[must_use]
1767 pub fn child_by_field_id(&self, field_id: u16) -> Option<Self> {
1768 Self::new(unsafe { ffi::ts_node_child_by_field_id(self.0, field_id) })
1769 }
1770
1771 #[doc(alias = "ts_node_field_name_for_child")]
1773 #[must_use]
1774 pub fn field_name_for_child(&self, child_index: u32) -> Option<&'static str> {
1775 unsafe {
1776 let ptr = ffi::ts_node_field_name_for_child(self.0, child_index);
1777 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1778 }
1779 }
1780
1781 #[must_use]
1783 pub fn field_name_for_named_child(&self, named_child_index: u32) -> Option<&'static str> {
1784 unsafe {
1785 let ptr = ffi::ts_node_field_name_for_named_child(self.0, named_child_index);
1786 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
1787 }
1788 }
1789
1790 pub fn children<'cursor>(
1800 &self,
1801 cursor: &'cursor mut TreeCursor<'tree>,
1802 ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1803 cursor.reset(*self);
1804 cursor.goto_first_child();
1805 (0..self.child_count()).map(move |_| {
1806 let result = cursor.node();
1807 cursor.goto_next_sibling();
1808 result
1809 })
1810 }
1811
1812 pub fn named_children<'cursor>(
1816 &self,
1817 cursor: &'cursor mut TreeCursor<'tree>,
1818 ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
1819 cursor.reset(*self);
1820 cursor.goto_first_child();
1821 (0..self.named_child_count()).map(move |_| {
1822 while !cursor.node().is_named() {
1823 if !cursor.goto_next_sibling() {
1824 break;
1825 }
1826 }
1827 let result = cursor.node();
1828 cursor.goto_next_sibling();
1829 result
1830 })
1831 }
1832
1833 pub fn children_by_field_name<'cursor>(
1837 &self,
1838 field_name: &str,
1839 cursor: &'cursor mut TreeCursor<'tree>,
1840 ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1841 let field_id = self.language().field_id_for_name(field_name);
1842 let mut done = field_id.is_none();
1843 if !done {
1844 cursor.reset(*self);
1845 cursor.goto_first_child();
1846 }
1847 iter::from_fn(move || {
1848 if !done {
1849 while cursor.field_id() != field_id {
1850 if !cursor.goto_next_sibling() {
1851 return None;
1852 }
1853 }
1854 let result = cursor.node();
1855 if !cursor.goto_next_sibling() {
1856 done = true;
1857 }
1858 return Some(result);
1859 }
1860 None
1861 })
1862 }
1863
1864 pub fn children_by_field_id<'cursor>(
1868 &self,
1869 field_id: FieldId,
1870 cursor: &'cursor mut TreeCursor<'tree>,
1871 ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
1872 cursor.reset(*self);
1873 cursor.goto_first_child();
1874 let mut done = false;
1875 iter::from_fn(move || {
1876 if !done {
1877 while cursor.field_id() != Some(field_id) {
1878 if !cursor.goto_next_sibling() {
1879 return None;
1880 }
1881 }
1882 let result = cursor.node();
1883 if !cursor.goto_next_sibling() {
1884 done = true;
1885 }
1886 return Some(result);
1887 }
1888 None
1889 })
1890 }
1891
1892 #[doc(alias = "ts_node_parent")]
1896 #[must_use]
1897 pub fn parent(&self) -> Option<Self> {
1898 Self::new(unsafe { ffi::ts_node_parent(self.0) })
1899 }
1900
1901 #[doc(alias = "ts_node_child_with_descendant")]
1905 #[must_use]
1906 pub fn child_with_descendant(&self, descendant: Self) -> Option<Self> {
1907 Self::new(unsafe { ffi::ts_node_child_with_descendant(self.0, descendant.0) })
1908 }
1909
1910 #[doc(alias = "ts_node_next_sibling")]
1912 #[must_use]
1913 pub fn next_sibling(&self) -> Option<Self> {
1914 Self::new(unsafe { ffi::ts_node_next_sibling(self.0) })
1915 }
1916
1917 #[doc(alias = "ts_node_prev_sibling")]
1919 #[must_use]
1920 pub fn prev_sibling(&self) -> Option<Self> {
1921 Self::new(unsafe { ffi::ts_node_prev_sibling(self.0) })
1922 }
1923
1924 #[doc(alias = "ts_node_next_named_sibling")]
1926 #[must_use]
1927 pub fn next_named_sibling(&self) -> Option<Self> {
1928 Self::new(unsafe { ffi::ts_node_next_named_sibling(self.0) })
1929 }
1930
1931 #[doc(alias = "ts_node_prev_named_sibling")]
1933 #[must_use]
1934 pub fn prev_named_sibling(&self) -> Option<Self> {
1935 Self::new(unsafe { ffi::ts_node_prev_named_sibling(self.0) })
1936 }
1937
1938 #[doc(alias = "ts_node_first_child_for_byte")]
1940 #[must_use]
1941 pub fn first_child_for_byte(&self, byte: usize) -> Option<Self> {
1942 Self::new(unsafe { ffi::ts_node_first_child_for_byte(self.0, byte as u32) })
1943 }
1944
1945 #[doc(alias = "ts_node_first_named_child_for_point")]
1947 #[must_use]
1948 pub fn first_named_child_for_byte(&self, byte: usize) -> Option<Self> {
1949 Self::new(unsafe { ffi::ts_node_first_named_child_for_byte(self.0, byte as u32) })
1950 }
1951
1952 #[doc(alias = "ts_node_descendant_count")]
1954 #[must_use]
1955 pub fn descendant_count(&self) -> usize {
1956 unsafe { ffi::ts_node_descendant_count(self.0) as usize }
1957 }
1958
1959 #[doc(alias = "ts_node_descendant_for_byte_range")]
1961 #[must_use]
1962 pub fn descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
1963 Self::new(unsafe {
1964 ffi::ts_node_descendant_for_byte_range(self.0, start as u32, end as u32)
1965 })
1966 }
1967
1968 #[doc(alias = "ts_node_named_descendant_for_byte_range")]
1970 #[must_use]
1971 pub fn named_descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
1972 Self::new(unsafe {
1973 ffi::ts_node_named_descendant_for_byte_range(self.0, start as u32, end as u32)
1974 })
1975 }
1976
1977 #[doc(alias = "ts_node_descendant_for_point_range")]
1979 #[must_use]
1980 pub fn descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
1981 Self::new(unsafe {
1982 ffi::ts_node_descendant_for_point_range(self.0, start.into(), end.into())
1983 })
1984 }
1985
1986 #[doc(alias = "ts_node_named_descendant_for_point_range")]
1988 #[must_use]
1989 pub fn named_descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
1990 Self::new(unsafe {
1991 ffi::ts_node_named_descendant_for_point_range(self.0, start.into(), end.into())
1992 })
1993 }
1994
1995 #[doc(alias = "ts_node_string")]
1997 #[must_use]
1998 pub fn to_sexp(&self) -> String {
1999 let c_string = unsafe { ffi::ts_node_string(self.0) };
2000 let result = unsafe { CStr::from_ptr(c_string) }
2001 .to_str()
2002 .unwrap()
2003 .to_string();
2004 unsafe { (FREE_FN)(c_string.cast::<c_void>()) };
2005 result
2006 }
2007
2008 pub fn utf8_text<'a>(&self, source: &'a [u8]) -> Result<&'a str, str::Utf8Error> {
2009 str::from_utf8(&source[self.start_byte()..self.end_byte()])
2010 }
2011
2012 #[must_use]
2013 pub fn utf16_text<'a>(&self, source: &'a [u16]) -> &'a [u16] {
2014 &source[self.start_byte() / 2..self.end_byte() / 2]
2015 }
2016
2017 #[doc(alias = "ts_tree_cursor_new")]
2022 #[must_use]
2023 pub fn walk(&self) -> TreeCursor<'tree> {
2024 TreeCursor(unsafe { ffi::ts_tree_cursor_new(self.0) }, PhantomData)
2025 }
2026
2027 #[doc(alias = "ts_node_edit")]
2035 pub fn edit(&mut self, edit: &InputEdit) {
2036 let edit = edit.into();
2037 unsafe { ffi::ts_node_edit(core::ptr::addr_of_mut!(self.0), &edit) }
2038 }
2039}
2040
2041impl PartialEq for Node<'_> {
2042 fn eq(&self, other: &Self) -> bool {
2043 core::ptr::eq(self.0.id, other.0.id)
2044 }
2045}
2046
2047impl Eq for Node<'_> {}
2048
2049impl hash::Hash for Node<'_> {
2050 fn hash<H: hash::Hasher>(&self, state: &mut H) {
2051 self.0.id.hash(state);
2052 self.0.context[0].hash(state);
2053 self.0.context[1].hash(state);
2054 self.0.context[2].hash(state);
2055 self.0.context[3].hash(state);
2056 }
2057}
2058
2059impl fmt::Debug for Node<'_> {
2060 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2061 write!(
2062 f,
2063 "{{Node {} {} - {}}}",
2064 self.kind(),
2065 self.start_position(),
2066 self.end_position()
2067 )
2068 }
2069}
2070
2071impl fmt::Display for Node<'_> {
2072 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2073 let sexp = self.to_sexp();
2074 if sexp.is_empty() {
2075 write!(f, "")
2076 } else if !f.alternate() {
2077 write!(f, "{sexp}")
2078 } else {
2079 write!(f, "{}", format_sexp(&sexp, f.width().unwrap_or(0)))
2080 }
2081 }
2082}
2083
2084impl<'cursor> TreeCursor<'cursor> {
2085 #[doc(alias = "ts_tree_cursor_current_node")]
2087 #[must_use]
2088 pub fn node(&self) -> Node<'cursor> {
2089 Node(
2090 unsafe { ffi::ts_tree_cursor_current_node(&self.0) },
2091 PhantomData,
2092 )
2093 }
2094
2095 #[doc(alias = "ts_tree_cursor_current_field_id")]
2099 #[must_use]
2100 pub fn field_id(&self) -> Option<FieldId> {
2101 let id = unsafe { ffi::ts_tree_cursor_current_field_id(&self.0) };
2102 FieldId::new(id)
2103 }
2104
2105 #[doc(alias = "ts_tree_cursor_current_field_name")]
2107 #[must_use]
2108 pub fn field_name(&self) -> Option<&'static str> {
2109 unsafe {
2110 let ptr = ffi::ts_tree_cursor_current_field_name(&self.0);
2111 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
2112 }
2113 }
2114
2115 #[doc(alias = "ts_tree_cursor_current_depth")]
2118 #[must_use]
2119 pub fn depth(&self) -> u32 {
2120 unsafe { ffi::ts_tree_cursor_current_depth(&self.0) }
2121 }
2122
2123 #[doc(alias = "ts_tree_cursor_current_descendant_index")]
2126 #[must_use]
2127 pub fn descendant_index(&self) -> usize {
2128 unsafe { ffi::ts_tree_cursor_current_descendant_index(&self.0) as usize }
2129 }
2130
2131 #[doc(alias = "ts_tree_cursor_goto_first_child")]
2136 pub fn goto_first_child(&mut self) -> bool {
2137 unsafe { ffi::ts_tree_cursor_goto_first_child(&mut self.0) }
2138 }
2139
2140 #[doc(alias = "ts_tree_cursor_goto_last_child")]
2149 pub fn goto_last_child(&mut self) -> bool {
2150 unsafe { ffi::ts_tree_cursor_goto_last_child(&mut self.0) }
2151 }
2152
2153 #[doc(alias = "ts_tree_cursor_goto_parent")]
2162 pub fn goto_parent(&mut self) -> bool {
2163 unsafe { ffi::ts_tree_cursor_goto_parent(&mut self.0) }
2164 }
2165
2166 #[doc(alias = "ts_tree_cursor_goto_next_sibling")]
2174 pub fn goto_next_sibling(&mut self) -> bool {
2175 unsafe { ffi::ts_tree_cursor_goto_next_sibling(&mut self.0) }
2176 }
2177
2178 #[doc(alias = "ts_tree_cursor_goto_descendant")]
2182 pub fn goto_descendant(&mut self, descendant_index: usize) {
2183 unsafe { ffi::ts_tree_cursor_goto_descendant(&mut self.0, descendant_index as u32) }
2184 }
2185
2186 #[doc(alias = "ts_tree_cursor_goto_previous_sibling")]
2198 pub fn goto_previous_sibling(&mut self) -> bool {
2199 unsafe { ffi::ts_tree_cursor_goto_previous_sibling(&mut self.0) }
2200 }
2201
2202 #[doc(alias = "ts_tree_cursor_goto_first_child_for_byte")]
2208 pub fn goto_first_child_for_byte(&mut self, index: usize) -> Option<usize> {
2209 let result =
2210 unsafe { ffi::ts_tree_cursor_goto_first_child_for_byte(&mut self.0, index as u32) };
2211 result.try_into().ok()
2212 }
2213
2214 #[doc(alias = "ts_tree_cursor_goto_first_child_for_point")]
2220 pub fn goto_first_child_for_point(&mut self, point: Point) -> Option<usize> {
2221 let result =
2222 unsafe { ffi::ts_tree_cursor_goto_first_child_for_point(&mut self.0, point.into()) };
2223 result.try_into().ok()
2224 }
2225
2226 #[doc(alias = "ts_tree_cursor_reset")]
2229 pub fn reset(&mut self, node: Node<'cursor>) {
2230 unsafe { ffi::ts_tree_cursor_reset(&mut self.0, node.0) };
2231 }
2232
2233 #[doc(alias = "ts_tree_cursor_reset_to")]
2238 pub fn reset_to(&mut self, cursor: &Self) {
2239 unsafe { ffi::ts_tree_cursor_reset_to(&mut self.0, &cursor.0) };
2240 }
2241}
2242
2243impl Clone for TreeCursor<'_> {
2244 fn clone(&self) -> Self {
2245 TreeCursor(unsafe { ffi::ts_tree_cursor_copy(&self.0) }, PhantomData)
2246 }
2247}
2248
2249impl Drop for TreeCursor<'_> {
2250 fn drop(&mut self) {
2251 unsafe { ffi::ts_tree_cursor_delete(&mut self.0) }
2252 }
2253}
2254
2255impl LookaheadIterator {
2256 #[doc(alias = "ts_lookahead_iterator_language")]
2258 #[must_use]
2259 pub fn language(&self) -> LanguageRef<'_> {
2260 LanguageRef(
2261 unsafe { ffi::ts_lookahead_iterator_language(self.0.as_ptr()) },
2262 PhantomData,
2263 )
2264 }
2265
2266 #[doc(alias = "ts_lookahead_iterator_current_symbol")]
2268 #[must_use]
2269 pub fn current_symbol(&self) -> u16 {
2270 unsafe { ffi::ts_lookahead_iterator_current_symbol(self.0.as_ptr()) }
2271 }
2272
2273 #[doc(alias = "ts_lookahead_iterator_current_symbol_name")]
2275 #[must_use]
2276 pub fn current_symbol_name(&self) -> &'static str {
2277 unsafe {
2278 CStr::from_ptr(ffi::ts_lookahead_iterator_current_symbol_name(
2279 self.0.as_ptr(),
2280 ))
2281 .to_str()
2282 .unwrap()
2283 }
2284 }
2285
2286 #[doc(alias = "ts_lookahead_iterator_reset")]
2291 pub fn reset(&mut self, language: &Language, state: u16) -> bool {
2292 unsafe { ffi::ts_lookahead_iterator_reset(self.0.as_ptr(), language.0, state) }
2293 }
2294
2295 #[doc(alias = "ts_lookahead_iterator_reset_state")]
2300 pub fn reset_state(&mut self, state: u16) -> bool {
2301 unsafe { ffi::ts_lookahead_iterator_reset_state(self.0.as_ptr(), state) }
2302 }
2303
2304 pub fn iter_names(&mut self) -> impl Iterator<Item = &'static str> + '_ {
2306 LookaheadNamesIterator(self)
2307 }
2308}
2309
2310impl Iterator for LookaheadNamesIterator<'_> {
2311 type Item = &'static str;
2312
2313 #[doc(alias = "ts_lookahead_iterator_next")]
2314 fn next(&mut self) -> Option<Self::Item> {
2315 unsafe { ffi::ts_lookahead_iterator_next(self.0 .0.as_ptr()) }
2316 .then(|| self.0.current_symbol_name())
2317 }
2318}
2319
2320impl Iterator for LookaheadIterator {
2321 type Item = u16;
2322
2323 #[doc(alias = "ts_lookahead_iterator_next")]
2324 fn next(&mut self) -> Option<Self::Item> {
2325 unsafe { ffi::ts_lookahead_iterator_next(self.0.as_ptr()) }.then(|| self.current_symbol())
2327 }
2328}
2329
2330impl Drop for LookaheadIterator {
2331 #[doc(alias = "ts_lookahead_iterator_delete")]
2332 fn drop(&mut self) {
2333 unsafe { ffi::ts_lookahead_iterator_delete(self.0.as_ptr()) }
2334 }
2335}
2336
2337impl Query {
2338 pub fn new(language: &Language, source: &str) -> Result<Self, QueryError> {
2345 let ptr = Self::new_raw(language, source)?;
2346 unsafe { Self::from_raw_parts(ptr, source) }
2347 }
2348
2349 pub fn new_raw(language: &Language, source: &str) -> Result<*mut ffi::TSQuery, QueryError> {
2355 let mut error_offset = 0u32;
2356 let mut error_type: ffi::TSQueryError = 0;
2357 let bytes = source.as_bytes();
2358
2359 let ptr = unsafe {
2361 ffi::ts_query_new(
2362 language.0,
2363 bytes.as_ptr().cast::<c_char>(),
2364 bytes.len() as u32,
2365 core::ptr::addr_of_mut!(error_offset),
2366 core::ptr::addr_of_mut!(error_type),
2367 )
2368 };
2369
2370 if !ptr.is_null() {
2371 return Ok(ptr);
2372 }
2373
2374 if error_type == ffi::TSQueryErrorLanguage {
2376 return Err(QueryError {
2377 row: 0,
2378 column: 0,
2379 offset: 0,
2380 message: LanguageError::Version(language.abi_version()).to_string(),
2381 kind: QueryErrorKind::Language,
2382 });
2383 }
2384
2385 let offset = error_offset as usize;
2386 let mut line_start = 0;
2387 let mut row = 0;
2388 let mut line_containing_error = None;
2389 for line in source.lines() {
2390 let line_end = line_start + line.len() + 1;
2391 if line_end > offset {
2392 line_containing_error = Some(line);
2393 break;
2394 }
2395 line_start = line_end;
2396 row += 1;
2397 }
2398 let column = offset - line_start;
2399
2400 let (message, kind) = match error_type {
2401 ffi::TSQueryErrorNodeType | ffi::TSQueryErrorField | ffi::TSQueryErrorCapture => {
2403 let suffix = source.split_at(offset).1;
2404 let in_quotes = offset > 0 && source.as_bytes()[offset - 1] == b'"';
2405 let mut backslashes = 0;
2406 let end_offset = suffix
2407 .find(|c| {
2408 if in_quotes {
2409 if c == '"' && backslashes % 2 == 0 {
2410 true
2411 } else if c == '\\' {
2412 backslashes += 1;
2413 false
2414 } else {
2415 backslashes = 0;
2416 false
2417 }
2418 } else {
2419 !char::is_alphanumeric(c) && c != '_' && c != '-'
2420 }
2421 })
2422 .unwrap_or(suffix.len());
2423 (
2424 format!("\"{}\"", suffix.split_at(end_offset).0),
2425 match error_type {
2426 ffi::TSQueryErrorNodeType => QueryErrorKind::NodeType,
2427 ffi::TSQueryErrorField => QueryErrorKind::Field,
2428 ffi::TSQueryErrorCapture => QueryErrorKind::Capture,
2429 _ => unreachable!(),
2430 },
2431 )
2432 }
2433
2434 _ => (
2436 line_containing_error.map_or_else(
2437 || "Unexpected EOF".to_string(),
2438 |line| line.to_string() + "\n" + &" ".repeat(offset - line_start) + "^",
2439 ),
2440 match error_type {
2441 ffi::TSQueryErrorStructure => QueryErrorKind::Structure,
2442 _ => QueryErrorKind::Syntax,
2443 },
2444 ),
2445 };
2446
2447 Err(QueryError {
2448 row,
2449 column,
2450 offset,
2451 message,
2452 kind,
2453 })
2454 }
2455
2456 #[doc(hidden)]
2457 unsafe fn from_raw_parts(ptr: *mut ffi::TSQuery, source: &str) -> Result<Self, QueryError> {
2458 let ptr = {
2459 struct TSQueryDrop(*mut ffi::TSQuery);
2460 impl Drop for TSQueryDrop {
2461 fn drop(&mut self) {
2462 unsafe { ffi::ts_query_delete(self.0) }
2463 }
2464 }
2465 TSQueryDrop(ptr)
2466 };
2467
2468 let string_count = unsafe { ffi::ts_query_string_count(ptr.0) };
2469 let capture_count = unsafe { ffi::ts_query_capture_count(ptr.0) };
2470 let pattern_count = unsafe { ffi::ts_query_pattern_count(ptr.0) as usize };
2471
2472 let mut capture_names = Vec::with_capacity(capture_count as usize);
2473 let mut capture_quantifiers_vec = Vec::with_capacity(pattern_count);
2474 let mut text_predicates_vec = Vec::with_capacity(pattern_count);
2475 let mut property_predicates_vec = Vec::with_capacity(pattern_count);
2476 let mut property_settings_vec = Vec::with_capacity(pattern_count);
2477 let mut general_predicates_vec = Vec::with_capacity(pattern_count);
2478
2479 for i in 0..capture_count {
2481 unsafe {
2482 let mut length = 0u32;
2483 let name =
2484 ffi::ts_query_capture_name_for_id(ptr.0, i, core::ptr::addr_of_mut!(length))
2485 .cast::<u8>();
2486 let name = slice::from_raw_parts(name, length as usize);
2487 let name = str::from_utf8_unchecked(name);
2488 capture_names.push(name);
2489 }
2490 }
2491
2492 for i in 0..pattern_count {
2494 let mut capture_quantifiers = Vec::with_capacity(capture_count as usize);
2495 for j in 0..capture_count {
2496 unsafe {
2497 let quantifier = ffi::ts_query_capture_quantifier_for_id(ptr.0, i as u32, j);
2498 capture_quantifiers.push(quantifier.into());
2499 }
2500 }
2501 capture_quantifiers_vec.push(capture_quantifiers.into());
2502 }
2503
2504 let string_values = (0..string_count)
2506 .map(|i| unsafe {
2507 let mut length = 0u32;
2508 let value =
2509 ffi::ts_query_string_value_for_id(ptr.0, i, core::ptr::addr_of_mut!(length))
2510 .cast::<u8>();
2511 let value = slice::from_raw_parts(value, length as usize);
2512 let value = str::from_utf8_unchecked(value);
2513 value
2514 })
2515 .collect::<Vec<_>>();
2516
2517 for i in 0..pattern_count {
2519 let predicate_steps = unsafe {
2520 let mut length = 0u32;
2521 let raw_predicates = ffi::ts_query_predicates_for_pattern(
2522 ptr.0,
2523 i as u32,
2524 core::ptr::addr_of_mut!(length),
2525 );
2526 (length > 0)
2527 .then(|| slice::from_raw_parts(raw_predicates, length as usize))
2528 .unwrap_or_default()
2529 };
2530
2531 let byte_offset = unsafe { ffi::ts_query_start_byte_for_pattern(ptr.0, i as u32) };
2532 let row = source
2533 .char_indices()
2534 .take_while(|(i, _)| *i < byte_offset as usize)
2535 .filter(|(_, c)| *c == '\n')
2536 .count();
2537
2538 use ffi::TSQueryPredicateStepType as T;
2539 const TYPE_DONE: T = ffi::TSQueryPredicateStepTypeDone;
2540 const TYPE_CAPTURE: T = ffi::TSQueryPredicateStepTypeCapture;
2541 const TYPE_STRING: T = ffi::TSQueryPredicateStepTypeString;
2542
2543 let mut text_predicates = Vec::new();
2544 let mut property_predicates = Vec::new();
2545 let mut property_settings = Vec::new();
2546 let mut general_predicates = Vec::new();
2547 for p in predicate_steps.split(|s| s.type_ == TYPE_DONE) {
2548 if p.is_empty() {
2549 continue;
2550 }
2551
2552 if p[0].type_ != TYPE_STRING {
2553 return Err(predicate_error(
2554 row,
2555 format!(
2556 "Expected predicate to start with a function name. Got @{}.",
2557 capture_names[p[0].value_id as usize],
2558 ),
2559 ));
2560 }
2561
2562 let operator_name = string_values[p[0].value_id as usize];
2564 match operator_name {
2565 "eq?" | "not-eq?" | "any-eq?" | "any-not-eq?" => {
2566 if p.len() != 3 {
2567 return Err(predicate_error(
2568 row,
2569 format!(
2570 "Wrong number of arguments to #eq? predicate. Expected 2, got {}.",
2571 p.len() - 1
2572 ),
2573 ));
2574 }
2575 if p[1].type_ != TYPE_CAPTURE {
2576 return Err(predicate_error(row, format!(
2577 "First argument to #eq? predicate must be a capture name. Got literal \"{}\".",
2578 string_values[p[1].value_id as usize],
2579 )));
2580 }
2581
2582 let is_positive = operator_name == "eq?" || operator_name == "any-eq?";
2583 let match_all = match operator_name {
2584 "eq?" | "not-eq?" => true,
2585 "any-eq?" | "any-not-eq?" => false,
2586 _ => unreachable!(),
2587 };
2588 text_predicates.push(if p[2].type_ == TYPE_CAPTURE {
2589 TextPredicateCapture::EqCapture(
2590 p[1].value_id,
2591 p[2].value_id,
2592 is_positive,
2593 match_all,
2594 )
2595 } else {
2596 TextPredicateCapture::EqString(
2597 p[1].value_id,
2598 string_values[p[2].value_id as usize].to_string().into(),
2599 is_positive,
2600 match_all,
2601 )
2602 });
2603 }
2604
2605 "match?" | "not-match?" | "any-match?" | "any-not-match?" => {
2606 if p.len() != 3 {
2607 return Err(predicate_error(row, format!(
2608 "Wrong number of arguments to #match? predicate. Expected 2, got {}.",
2609 p.len() - 1
2610 )));
2611 }
2612 if p[1].type_ != TYPE_CAPTURE {
2613 return Err(predicate_error(row, format!(
2614 "First argument to #match? predicate must be a capture name. Got literal \"{}\".",
2615 string_values[p[1].value_id as usize],
2616 )));
2617 }
2618 if p[2].type_ == TYPE_CAPTURE {
2619 return Err(predicate_error(row, format!(
2620 "Second argument to #match? predicate must be a literal. Got capture @{}.",
2621 capture_names[p[2].value_id as usize],
2622 )));
2623 }
2624
2625 let is_positive =
2626 operator_name == "match?" || operator_name == "any-match?";
2627 let match_all = match operator_name {
2628 "match?" | "not-match?" => true,
2629 "any-match?" | "any-not-match?" => false,
2630 _ => unreachable!(),
2631 };
2632 let regex = &string_values[p[2].value_id as usize];
2633 text_predicates.push(TextPredicateCapture::MatchString(
2634 p[1].value_id,
2635 regex::bytes::Regex::new(regex).map_err(|_| {
2636 predicate_error(row, format!("Invalid regex '{regex}'"))
2637 })?,
2638 is_positive,
2639 match_all,
2640 ));
2641 }
2642
2643 "set!" => property_settings.push(Self::parse_property(
2644 row,
2645 operator_name,
2646 &capture_names,
2647 &string_values,
2648 &p[1..],
2649 )?),
2650
2651 "is?" | "is-not?" => property_predicates.push((
2652 Self::parse_property(
2653 row,
2654 operator_name,
2655 &capture_names,
2656 &string_values,
2657 &p[1..],
2658 )?,
2659 operator_name == "is?",
2660 )),
2661
2662 "any-of?" | "not-any-of?" => {
2663 if p.len() < 2 {
2664 return Err(predicate_error(row, format!(
2665 "Wrong number of arguments to #any-of? predicate. Expected at least 1, got {}.",
2666 p.len() - 1
2667 )));
2668 }
2669 if p[1].type_ != TYPE_CAPTURE {
2670 return Err(predicate_error(row, format!(
2671 "First argument to #any-of? predicate must be a capture name. Got literal \"{}\".",
2672 string_values[p[1].value_id as usize],
2673 )));
2674 }
2675
2676 let is_positive = operator_name == "any-of?";
2677 let mut values = Vec::new();
2678 for arg in &p[2..] {
2679 if arg.type_ == TYPE_CAPTURE {
2680 return Err(predicate_error(row, format!(
2681 "Arguments to #any-of? predicate must be literals. Got capture @{}.",
2682 capture_names[arg.value_id as usize],
2683 )));
2684 }
2685 values.push(string_values[arg.value_id as usize]);
2686 }
2687 text_predicates.push(TextPredicateCapture::AnyString(
2688 p[1].value_id,
2689 values
2690 .iter()
2691 .map(|x| (*x).to_string().into())
2692 .collect::<Vec<_>>()
2693 .into(),
2694 is_positive,
2695 ));
2696 }
2697
2698 _ => general_predicates.push(QueryPredicate {
2699 operator: operator_name.to_string().into(),
2700 args: p[1..]
2701 .iter()
2702 .map(|a| {
2703 if a.type_ == TYPE_CAPTURE {
2704 QueryPredicateArg::Capture(a.value_id)
2705 } else {
2706 QueryPredicateArg::String(
2707 string_values[a.value_id as usize].to_string().into(),
2708 )
2709 }
2710 })
2711 .collect(),
2712 }),
2713 }
2714 }
2715
2716 text_predicates_vec.push(text_predicates.into());
2717 property_predicates_vec.push(property_predicates.into());
2718 property_settings_vec.push(property_settings.into());
2719 general_predicates_vec.push(general_predicates.into());
2720 }
2721
2722 let result = Self {
2723 ptr: unsafe { NonNull::new_unchecked(ptr.0) },
2724 capture_names: capture_names.into(),
2725 capture_quantifiers: capture_quantifiers_vec.into(),
2726 text_predicates: text_predicates_vec.into(),
2727 property_predicates: property_predicates_vec.into(),
2728 property_settings: property_settings_vec.into(),
2729 general_predicates: general_predicates_vec.into(),
2730 };
2731
2732 core::mem::forget(ptr);
2733
2734 Ok(result)
2735 }
2736
2737 #[doc(alias = "ts_query_start_byte_for_pattern")]
2740 #[must_use]
2741 pub fn start_byte_for_pattern(&self, pattern_index: usize) -> usize {
2742 assert!(
2743 pattern_index < self.text_predicates.len(),
2744 "Pattern index is {pattern_index} but the pattern count is {}",
2745 self.text_predicates.len(),
2746 );
2747 unsafe {
2748 ffi::ts_query_start_byte_for_pattern(self.ptr.as_ptr(), pattern_index as u32) as usize
2749 }
2750 }
2751
2752 #[doc(alias = "ts_query_end_byte_for_pattern")]
2755 #[must_use]
2756 pub fn end_byte_for_pattern(&self, pattern_index: usize) -> usize {
2757 assert!(
2758 pattern_index < self.text_predicates.len(),
2759 "Pattern index is {pattern_index} but the pattern count is {}",
2760 self.text_predicates.len(),
2761 );
2762 unsafe {
2763 ffi::ts_query_end_byte_for_pattern(self.ptr.as_ptr(), pattern_index as u32) as usize
2764 }
2765 }
2766
2767 #[doc(alias = "ts_query_pattern_count")]
2769 #[must_use]
2770 pub fn pattern_count(&self) -> usize {
2771 unsafe { ffi::ts_query_pattern_count(self.ptr.as_ptr()) as usize }
2772 }
2773
2774 #[must_use]
2776 pub const fn capture_names(&self) -> &[&str] {
2777 &self.capture_names
2778 }
2779
2780 #[must_use]
2782 pub const fn capture_quantifiers(&self, index: usize) -> &[CaptureQuantifier] {
2783 &self.capture_quantifiers[index]
2784 }
2785
2786 #[must_use]
2788 pub fn capture_index_for_name(&self, name: &str) -> Option<u32> {
2789 self.capture_names
2790 .iter()
2791 .position(|n| *n == name)
2792 .map(|ix| ix as u32)
2793 }
2794
2795 #[must_use]
2799 pub const fn property_predicates(&self, index: usize) -> &[(QueryProperty, bool)] {
2800 &self.property_predicates[index]
2801 }
2802
2803 #[must_use]
2807 pub const fn property_settings(&self, index: usize) -> &[QueryProperty] {
2808 &self.property_settings[index]
2809 }
2810
2811 #[must_use]
2819 pub const fn general_predicates(&self, index: usize) -> &[QueryPredicate] {
2820 &self.general_predicates[index]
2821 }
2822
2823 #[doc(alias = "ts_query_disable_capture")]
2828 pub fn disable_capture(&mut self, name: &str) {
2829 unsafe {
2830 ffi::ts_query_disable_capture(
2831 self.ptr.as_ptr(),
2832 name.as_bytes().as_ptr().cast::<c_char>(),
2833 name.len() as u32,
2834 );
2835 }
2836 }
2837
2838 #[doc(alias = "ts_query_disable_pattern")]
2843 pub fn disable_pattern(&mut self, index: usize) {
2844 unsafe { ffi::ts_query_disable_pattern(self.ptr.as_ptr(), index as u32) }
2845 }
2846
2847 #[doc(alias = "ts_query_is_pattern_rooted")]
2849 #[must_use]
2850 pub fn is_pattern_rooted(&self, index: usize) -> bool {
2851 unsafe { ffi::ts_query_is_pattern_rooted(self.ptr.as_ptr(), index as u32) }
2852 }
2853
2854 #[doc(alias = "ts_query_is_pattern_non_local")]
2856 #[must_use]
2857 pub fn is_pattern_non_local(&self, index: usize) -> bool {
2858 unsafe { ffi::ts_query_is_pattern_non_local(self.ptr.as_ptr(), index as u32) }
2859 }
2860
2861 #[doc(alias = "ts_query_is_pattern_guaranteed_at_step")]
2866 #[must_use]
2867 pub fn is_pattern_guaranteed_at_step(&self, byte_offset: usize) -> bool {
2868 unsafe {
2869 ffi::ts_query_is_pattern_guaranteed_at_step(self.ptr.as_ptr(), byte_offset as u32)
2870 }
2871 }
2872
2873 fn parse_property(
2874 row: usize,
2875 function_name: &str,
2876 capture_names: &[&str],
2877 string_values: &[&str],
2878 args: &[ffi::TSQueryPredicateStep],
2879 ) -> Result<QueryProperty, QueryError> {
2880 if args.is_empty() || args.len() > 3 {
2881 return Err(predicate_error(
2882 row,
2883 format!(
2884 "Wrong number of arguments to {function_name} predicate. Expected 1 to 3, got {}.",
2885 args.len(),
2886 ),
2887 ));
2888 }
2889
2890 let mut capture_id = None;
2891 let mut key = None;
2892 let mut value = None;
2893
2894 for arg in args {
2895 if arg.type_ == ffi::TSQueryPredicateStepTypeCapture {
2896 if capture_id.is_some() {
2897 return Err(predicate_error(
2898 row,
2899 format!(
2900 "Invalid arguments to {function_name} predicate. Unexpected second capture name @{}",
2901 capture_names[arg.value_id as usize]
2902 ),
2903 ));
2904 }
2905 capture_id = Some(arg.value_id as usize);
2906 } else if key.is_none() {
2907 key = Some(&string_values[arg.value_id as usize]);
2908 } else if value.is_none() {
2909 value = Some(string_values[arg.value_id as usize]);
2910 } else {
2911 return Err(predicate_error(
2912 row,
2913 format!(
2914 "Invalid arguments to {function_name} predicate. Unexpected third argument @{}",
2915 string_values[arg.value_id as usize]
2916 ),
2917 ));
2918 }
2919 }
2920
2921 if let Some(key) = key {
2922 Ok(QueryProperty::new(key, value, capture_id))
2923 } else {
2924 Err(predicate_error(
2925 row,
2926 format!("Invalid arguments to {function_name} predicate. Missing key argument"),
2927 ))
2928 }
2929 }
2930}
2931
2932impl Default for QueryCursor {
2933 fn default() -> Self {
2934 Self::new()
2935 }
2936}
2937
2938impl QueryCursor {
2939 #[doc(alias = "ts_query_cursor_new")]
2944 #[must_use]
2945 pub fn new() -> Self {
2946 Self {
2947 ptr: unsafe { NonNull::new_unchecked(ffi::ts_query_cursor_new()) },
2948 }
2949 }
2950
2951 #[doc(alias = "ts_query_cursor_match_limit")]
2953 #[must_use]
2954 pub fn match_limit(&self) -> u32 {
2955 unsafe { ffi::ts_query_cursor_match_limit(self.ptr.as_ptr()) }
2956 }
2957
2958 #[doc(alias = "ts_query_cursor_set_match_limit")]
2961 pub fn set_match_limit(&mut self, limit: u32) {
2962 unsafe {
2963 ffi::ts_query_cursor_set_match_limit(self.ptr.as_ptr(), limit);
2964 }
2965 }
2966
2967 #[doc(alias = "ts_query_cursor_did_exceed_match_limit")]
2970 #[must_use]
2971 pub fn did_exceed_match_limit(&self) -> bool {
2972 unsafe { ffi::ts_query_cursor_did_exceed_match_limit(self.ptr.as_ptr()) }
2973 }
2974
2975 #[doc(alias = "ts_query_cursor_exec")]
2986 pub fn matches<'query, 'cursor: 'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>>(
2987 &'cursor mut self,
2988 query: &'query Query,
2989 node: Node<'tree>,
2990 text_provider: T,
2991 ) -> QueryMatches<'query, 'tree, T, I> {
2992 let ptr = self.ptr.as_ptr();
2993 unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
2994 QueryMatches {
2995 ptr,
2996 query,
2997 text_provider,
2998 buffer1: Vec::default(),
2999 buffer2: Vec::default(),
3000 current_match: None,
3001 _options: None,
3002 _phantom: PhantomData,
3003 }
3004 }
3005
3006 #[doc(alias = "ts_query_cursor_exec_with_options")]
3013 pub fn matches_with_options<
3014 'query,
3015 'cursor: 'query,
3016 'tree,
3017 T: TextProvider<I>,
3018 I: AsRef<[u8]>,
3019 >(
3020 &'cursor mut self,
3021 query: &'query Query,
3022 node: Node<'tree>,
3023 text_provider: T,
3024 options: QueryCursorOptions,
3025 ) -> QueryMatches<'query, 'tree, T, I> {
3026 unsafe extern "C" fn progress(state: *mut ffi::TSQueryCursorState) -> bool {
3027 let callback = (*state)
3028 .payload
3029 .cast::<QueryProgressCallback>()
3030 .as_mut()
3031 .unwrap();
3032 match callback(&QueryCursorState::from_raw(state)) {
3033 ControlFlow::Continue(()) => false,
3034 ControlFlow::Break(()) => true,
3035 }
3036 }
3037
3038 let query_options = options.progress_callback.map(|cb| {
3039 QueryCursorOptionsDrop(Box::into_raw(Box::new(ffi::TSQueryCursorOptions {
3040 payload: Box::into_raw(Box::new(cb)).cast::<c_void>(),
3041 progress_callback: Some(progress),
3042 })))
3043 });
3044
3045 let ptr = self.ptr.as_ptr();
3046 unsafe {
3047 ffi::ts_query_cursor_exec_with_options(
3048 ptr,
3049 query.ptr.as_ptr(),
3050 node.0,
3051 query_options.as_ref().map_or(ptr::null_mut(), |q| q.0),
3052 );
3053 }
3054 QueryMatches {
3055 ptr,
3056 query,
3057 text_provider,
3058 buffer1: Vec::default(),
3059 buffer2: Vec::default(),
3060 current_match: None,
3061 _options: query_options,
3062 _phantom: PhantomData,
3063 }
3064 }
3065
3066 #[doc(alias = "ts_query_cursor_exec")]
3076 pub fn captures<'query, 'cursor: 'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>>(
3077 &'cursor mut self,
3078 query: &'query Query,
3079 node: Node<'tree>,
3080 text_provider: T,
3081 ) -> QueryCaptures<'query, 'tree, T, I> {
3082 let ptr = self.ptr.as_ptr();
3083 unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
3084 QueryCaptures {
3085 ptr,
3086 query,
3087 text_provider,
3088 buffer1: Vec::default(),
3089 buffer2: Vec::default(),
3090 current_match: None,
3091 _options: None,
3092 _phantom: PhantomData,
3093 }
3094 }
3095
3096 #[doc(alias = "ts_query_cursor_exec")]
3102 pub fn captures_with_options<
3103 'query,
3104 'cursor: 'query,
3105 'tree,
3106 T: TextProvider<I>,
3107 I: AsRef<[u8]>,
3108 >(
3109 &'cursor mut self,
3110 query: &'query Query,
3111 node: Node<'tree>,
3112 text_provider: T,
3113 options: QueryCursorOptions,
3114 ) -> QueryCaptures<'query, 'tree, T, I> {
3115 unsafe extern "C" fn progress(state: *mut ffi::TSQueryCursorState) -> bool {
3116 let callback = (*state)
3117 .payload
3118 .cast::<QueryProgressCallback>()
3119 .as_mut()
3120 .unwrap();
3121 match callback(&QueryCursorState::from_raw(state)) {
3122 ControlFlow::Continue(()) => false,
3123 ControlFlow::Break(()) => true,
3124 }
3125 }
3126
3127 let query_options = options.progress_callback.map(|cb| {
3128 QueryCursorOptionsDrop(Box::into_raw(Box::new(ffi::TSQueryCursorOptions {
3129 payload: Box::into_raw(Box::new(cb)).cast::<c_void>(),
3130 progress_callback: Some(progress),
3131 })))
3132 });
3133
3134 let ptr = self.ptr.as_ptr();
3135 unsafe {
3136 ffi::ts_query_cursor_exec_with_options(
3137 ptr,
3138 query.ptr.as_ptr(),
3139 node.0,
3140 query_options.as_ref().map_or(ptr::null_mut(), |q| q.0),
3141 );
3142 }
3143 QueryCaptures {
3144 ptr,
3145 query,
3146 text_provider,
3147 buffer1: Vec::default(),
3148 buffer2: Vec::default(),
3149 current_match: None,
3150 _options: query_options,
3151 _phantom: PhantomData,
3152 }
3153 }
3154
3155 #[doc(alias = "ts_query_cursor_set_byte_range")]
3158 pub fn set_byte_range(&mut self, range: ops::Range<usize>) -> &mut Self {
3159 unsafe {
3160 ffi::ts_query_cursor_set_byte_range(
3161 self.ptr.as_ptr(),
3162 range.start as u32,
3163 range.end as u32,
3164 );
3165 }
3166 self
3167 }
3168
3169 #[doc(alias = "ts_query_cursor_set_point_range")]
3172 pub fn set_point_range(&mut self, range: ops::Range<Point>) -> &mut Self {
3173 unsafe {
3174 ffi::ts_query_cursor_set_point_range(
3175 self.ptr.as_ptr(),
3176 range.start.into(),
3177 range.end.into(),
3178 );
3179 }
3180 self
3181 }
3182
3183 #[doc(alias = "ts_query_cursor_set_containing_byte_range")]
3191 pub fn set_containing_byte_range(&mut self, range: ops::Range<usize>) -> &mut Self {
3192 unsafe {
3193 ffi::ts_query_cursor_set_containing_byte_range(
3194 self.ptr.as_ptr(),
3195 range.start as u32,
3196 range.end as u32,
3197 );
3198 }
3199 self
3200 }
3201
3202 #[doc(alias = "ts_query_cursor_set_containing_point_range")]
3210 pub fn set_containing_point_range(&mut self, range: ops::Range<Point>) -> &mut Self {
3211 unsafe {
3212 ffi::ts_query_cursor_set_containing_point_range(
3213 self.ptr.as_ptr(),
3214 range.start.into(),
3215 range.end.into(),
3216 );
3217 }
3218 self
3219 }
3220
3221 #[doc(alias = "ts_query_cursor_set_max_start_depth")]
3236 pub fn set_max_start_depth(&mut self, max_start_depth: Option<u32>) -> &mut Self {
3237 unsafe {
3238 ffi::ts_query_cursor_set_max_start_depth(
3239 self.ptr.as_ptr(),
3240 max_start_depth.unwrap_or(u32::MAX),
3241 );
3242 }
3243 self
3244 }
3245}
3246
3247impl<'tree> QueryMatch<'_, 'tree> {
3248 #[must_use]
3249 pub const fn id(&self) -> u32 {
3250 self.id
3251 }
3252
3253 #[doc(alias = "ts_query_cursor_remove_match")]
3254 pub fn remove(&self) {
3255 unsafe { ffi::ts_query_cursor_remove_match(self.cursor, self.id) }
3256 }
3257
3258 pub fn nodes_for_capture_index(
3259 &self,
3260 capture_ix: u32,
3261 ) -> impl Iterator<Item = Node<'tree>> + '_ {
3262 self.captures
3263 .iter()
3264 .filter_map(move |capture| (capture.index == capture_ix).then_some(capture.node))
3265 }
3266
3267 fn new(m: &ffi::TSQueryMatch, cursor: *mut ffi::TSQueryCursor) -> Self {
3268 QueryMatch {
3269 cursor,
3270 id: m.id,
3271 pattern_index: m.pattern_index as usize,
3272 captures: (m.capture_count > 0)
3273 .then(|| unsafe {
3274 slice::from_raw_parts(
3275 m.captures.cast::<QueryCapture<'tree>>(),
3276 m.capture_count as usize,
3277 )
3278 })
3279 .unwrap_or_default(),
3280 }
3281 }
3282
3283 pub fn satisfies_text_predicates<I: AsRef<[u8]>>(
3284 &self,
3285 query: &Query,
3286 buffer1: &mut Vec<u8>,
3287 buffer2: &mut Vec<u8>,
3288 text_provider: &mut impl TextProvider<I>,
3289 ) -> bool {
3290 struct NodeText<'a, T> {
3291 buffer: &'a mut Vec<u8>,
3292 first_chunk: Option<T>,
3293 }
3294 impl<'a, T: AsRef<[u8]>> NodeText<'a, T> {
3295 fn new(buffer: &'a mut Vec<u8>) -> Self {
3296 Self {
3297 buffer,
3298 first_chunk: None,
3299 }
3300 }
3301
3302 fn get_text(&mut self, chunks: &mut impl Iterator<Item = T>) -> &[u8] {
3303 self.first_chunk = chunks.next();
3304 if let Some(next_chunk) = chunks.next() {
3305 self.buffer.clear();
3306 self.buffer
3307 .extend_from_slice(self.first_chunk.as_ref().unwrap().as_ref());
3308 self.buffer.extend_from_slice(next_chunk.as_ref());
3309 for chunk in chunks {
3310 self.buffer.extend_from_slice(chunk.as_ref());
3311 }
3312 self.buffer.as_slice()
3313 } else if let Some(ref first_chunk) = self.first_chunk {
3314 first_chunk.as_ref()
3315 } else {
3316 &[]
3317 }
3318 }
3319 }
3320
3321 let mut node_text1 = NodeText::new(buffer1);
3322 let mut node_text2 = NodeText::new(buffer2);
3323
3324 query.text_predicates[self.pattern_index]
3325 .iter()
3326 .all(|predicate| match predicate {
3327 TextPredicateCapture::EqCapture(i, j, is_positive, match_all_nodes) => {
3328 let mut nodes_1 = self.nodes_for_capture_index(*i).peekable();
3329 let mut nodes_2 = self.nodes_for_capture_index(*j).peekable();
3330 while nodes_1.peek().is_some() && nodes_2.peek().is_some() {
3331 let node1 = nodes_1.next().unwrap();
3332 let node2 = nodes_2.next().unwrap();
3333 let mut text1 = text_provider.text(node1);
3334 let mut text2 = text_provider.text(node2);
3335 let text1 = node_text1.get_text(&mut text1);
3336 let text2 = node_text2.get_text(&mut text2);
3337 let is_positive_match = text1 == text2;
3338 if is_positive_match != *is_positive && *match_all_nodes {
3339 return false;
3340 }
3341 if is_positive_match == *is_positive && !*match_all_nodes {
3342 return true;
3343 }
3344 }
3345 nodes_1.next().is_none() && nodes_2.next().is_none()
3346 }
3347 TextPredicateCapture::EqString(i, s, is_positive, match_all_nodes) => {
3348 let nodes = self.nodes_for_capture_index(*i);
3349 for node in nodes {
3350 let mut text = text_provider.text(node);
3351 let text = node_text1.get_text(&mut text);
3352 let is_positive_match = text == s.as_bytes();
3353 if is_positive_match != *is_positive && *match_all_nodes {
3354 return false;
3355 }
3356 if is_positive_match == *is_positive && !*match_all_nodes {
3357 return true;
3358 }
3359 }
3360 true
3361 }
3362 TextPredicateCapture::MatchString(i, r, is_positive, match_all_nodes) => {
3363 let nodes = self.nodes_for_capture_index(*i);
3364 for node in nodes {
3365 let mut text = text_provider.text(node);
3366 let text = node_text1.get_text(&mut text);
3367 let is_positive_match = r.is_match(text);
3368 if is_positive_match != *is_positive && *match_all_nodes {
3369 return false;
3370 }
3371 if is_positive_match == *is_positive && !*match_all_nodes {
3372 return true;
3373 }
3374 }
3375 true
3376 }
3377 TextPredicateCapture::AnyString(i, v, is_positive) => {
3378 let nodes = self.nodes_for_capture_index(*i);
3379 for node in nodes {
3380 let mut text = text_provider.text(node);
3381 let text = node_text1.get_text(&mut text);
3382 if (v.iter().any(|s| text == s.as_bytes())) != *is_positive {
3383 return false;
3384 }
3385 }
3386 true
3387 }
3388 })
3389 }
3390}
3391
3392impl QueryProperty {
3393 #[must_use]
3394 pub fn new(key: &str, value: Option<&str>, capture_id: Option<usize>) -> Self {
3395 Self {
3396 capture_id,
3397 key: key.to_string().into(),
3398 value: value.map(|s| s.to_string().into()),
3399 }
3400 }
3401}
3402
3403impl<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> StreamingIterator
3407 for QueryMatches<'query, 'tree, T, I>
3408{
3409 type Item = QueryMatch<'query, 'tree>;
3410
3411 fn advance(&mut self) {
3412 self.current_match = unsafe {
3413 loop {
3414 let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
3415 if ffi::ts_query_cursor_next_match(self.ptr, m.as_mut_ptr()) {
3416 let result = QueryMatch::new(&m.assume_init(), self.ptr);
3417 if result.satisfies_text_predicates(
3418 self.query,
3419 &mut self.buffer1,
3420 &mut self.buffer2,
3421 &mut self.text_provider,
3422 ) {
3423 break Some(result);
3424 }
3425 } else {
3426 break None;
3427 }
3428 }
3429 };
3430 }
3431
3432 fn get(&self) -> Option<&Self::Item> {
3433 self.current_match.as_ref()
3434 }
3435}
3436
3437impl<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> StreamingIteratorMut
3438 for QueryMatches<'query, 'tree, T, I>
3439{
3440 fn get_mut(&mut self) -> Option<&mut Self::Item> {
3441 self.current_match.as_mut()
3442 }
3443}
3444
3445impl<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> StreamingIterator
3446 for QueryCaptures<'query, 'tree, T, I>
3447{
3448 type Item = (QueryMatch<'query, 'tree>, usize);
3449
3450 fn advance(&mut self) {
3451 self.current_match = unsafe {
3452 loop {
3453 let mut capture_index = 0u32;
3454 let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
3455 if ffi::ts_query_cursor_next_capture(
3456 self.ptr,
3457 m.as_mut_ptr(),
3458 core::ptr::addr_of_mut!(capture_index),
3459 ) {
3460 let result = QueryMatch::new(&m.assume_init(), self.ptr);
3461 if result.satisfies_text_predicates(
3462 self.query,
3463 &mut self.buffer1,
3464 &mut self.buffer2,
3465 &mut self.text_provider,
3466 ) {
3467 break Some((result, capture_index as usize));
3468 }
3469 result.remove();
3470 } else {
3471 break None;
3472 }
3473 }
3474 }
3475 }
3476
3477 fn get(&self) -> Option<&Self::Item> {
3478 self.current_match.as_ref()
3479 }
3480}
3481
3482impl<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> StreamingIteratorMut
3483 for QueryCaptures<'query, 'tree, T, I>
3484{
3485 fn get_mut(&mut self) -> Option<&mut Self::Item> {
3486 self.current_match.as_mut()
3487 }
3488}
3489
3490impl<T: TextProvider<I>, I: AsRef<[u8]>> QueryMatches<'_, '_, T, I> {
3491 #[doc(alias = "ts_query_cursor_set_byte_range")]
3492 pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
3493 unsafe {
3494 ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
3495 }
3496 }
3497
3498 #[doc(alias = "ts_query_cursor_set_point_range")]
3499 pub fn set_point_range(&mut self, range: ops::Range<Point>) {
3500 unsafe {
3501 ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
3502 }
3503 }
3504}
3505
3506impl<T: TextProvider<I>, I: AsRef<[u8]>> QueryCaptures<'_, '_, T, I> {
3507 #[doc(alias = "ts_query_cursor_set_byte_range")]
3508 pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
3509 unsafe {
3510 ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
3511 }
3512 }
3513
3514 #[doc(alias = "ts_query_cursor_set_point_range")]
3515 pub fn set_point_range(&mut self, range: ops::Range<Point>) {
3516 unsafe {
3517 ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
3518 }
3519 }
3520}
3521
3522impl fmt::Debug for QueryMatch<'_, '_> {
3523 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3524 write!(
3525 f,
3526 "QueryMatch {{ id: {}, pattern_index: {}, captures: {:?} }}",
3527 self.id, self.pattern_index, self.captures
3528 )
3529 }
3530}
3531
3532impl<F, R, I> TextProvider<I> for F
3533where
3534 F: FnMut(Node) -> R,
3535 R: Iterator<Item = I>,
3536 I: AsRef<[u8]>,
3537{
3538 type I = R;
3539
3540 fn text(&mut self, node: Node) -> Self::I {
3541 (self)(node)
3542 }
3543}
3544
3545impl<'a> TextProvider<&'a [u8]> for &'a [u8] {
3546 type I = iter::Once<&'a [u8]>;
3547
3548 fn text(&mut self, node: Node) -> Self::I {
3549 iter::once(&self[node.byte_range()])
3550 }
3551}
3552
3553impl PartialEq for Query {
3554 fn eq(&self, other: &Self) -> bool {
3555 self.ptr == other.ptr
3556 }
3557}
3558
3559impl Drop for Query {
3560 fn drop(&mut self) {
3561 unsafe { ffi::ts_query_delete(self.ptr.as_ptr()) }
3562 }
3563}
3564
3565impl Drop for QueryCursor {
3566 fn drop(&mut self) {
3567 unsafe { ffi::ts_query_cursor_delete(self.ptr.as_ptr()) }
3568 }
3569}
3570
3571impl Point {
3572 #[must_use]
3573 pub const fn new(row: usize, column: usize) -> Self {
3574 Self { row, column }
3575 }
3576}
3577
3578impl fmt::Display for Point {
3579 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3580 write!(f, "({}, {})", self.row, self.column)
3581 }
3582}
3583
3584impl From<Point> for ffi::TSPoint {
3585 fn from(val: Point) -> Self {
3586 Self {
3587 row: val.row as u32,
3588 column: val.column as u32,
3589 }
3590 }
3591}
3592
3593impl From<ffi::TSPoint> for Point {
3594 fn from(point: ffi::TSPoint) -> Self {
3595 Self {
3596 row: point.row as usize,
3597 column: point.column as usize,
3598 }
3599 }
3600}
3601
3602impl From<Range> for ffi::TSRange {
3603 fn from(val: Range) -> Self {
3604 Self {
3605 start_byte: val.start_byte as u32,
3606 end_byte: val.end_byte as u32,
3607 start_point: val.start_point.into(),
3608 end_point: val.end_point.into(),
3609 }
3610 }
3611}
3612
3613impl From<ffi::TSRange> for Range {
3614 fn from(range: ffi::TSRange) -> Self {
3615 Self {
3616 start_byte: range.start_byte as usize,
3617 end_byte: range.end_byte as usize,
3618 start_point: range.start_point.into(),
3619 end_point: range.end_point.into(),
3620 }
3621 }
3622}
3623
3624impl From<&'_ InputEdit> for ffi::TSInputEdit {
3625 fn from(val: &'_ InputEdit) -> Self {
3626 Self {
3627 start_byte: val.start_byte as u32,
3628 old_end_byte: val.old_end_byte as u32,
3629 new_end_byte: val.new_end_byte as u32,
3630 start_point: val.start_position.into(),
3631 old_end_point: val.old_end_position.into(),
3632 new_end_point: val.new_end_position.into(),
3633 }
3634 }
3635}
3636
3637impl<'a> LossyUtf8<'a> {
3638 #[must_use]
3639 pub const fn new(bytes: &'a [u8]) -> Self {
3640 LossyUtf8 {
3641 bytes,
3642 in_replacement: false,
3643 }
3644 }
3645}
3646
3647impl<'a> Iterator for LossyUtf8<'a> {
3648 type Item = &'a str;
3649
3650 fn next(&mut self) -> Option<&'a str> {
3651 if self.bytes.is_empty() {
3652 return None;
3653 }
3654 if self.in_replacement {
3655 self.in_replacement = false;
3656 return Some("\u{fffd}");
3657 }
3658 match core::str::from_utf8(self.bytes) {
3659 Ok(valid) => {
3660 self.bytes = &[];
3661 Some(valid)
3662 }
3663 Err(error) => {
3664 if let Some(error_len) = error.error_len() {
3665 let error_start = error.valid_up_to();
3666 if error_start > 0 {
3667 let result =
3668 unsafe { core::str::from_utf8_unchecked(&self.bytes[..error_start]) };
3669 self.bytes = &self.bytes[(error_start + error_len)..];
3670 self.in_replacement = true;
3671 Some(result)
3672 } else {
3673 self.bytes = &self.bytes[error_len..];
3674 Some("\u{fffd}")
3675 }
3676 } else {
3677 None
3678 }
3679 }
3680 }
3681 }
3682}
3683
3684#[must_use]
3685const fn predicate_error(row: usize, message: String) -> QueryError {
3686 QueryError {
3687 kind: QueryErrorKind::Predicate,
3688 row,
3689 column: 0,
3690 offset: 0,
3691 message,
3692 }
3693}
3694
3695impl fmt::Display for IncludedRangesError {
3696 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3697 write!(f, "Incorrect range by index: {}", self.0)
3698 }
3699}
3700
3701impl fmt::Display for LanguageError {
3702 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3703 match self {
3704 Self::Version(version) => {
3705 write!(
3706 f,
3707 "Incompatible language version {version}. Expected minimum {MIN_COMPATIBLE_LANGUAGE_VERSION}, maximum {LANGUAGE_VERSION}",
3708 )
3709 }
3710 #[cfg(feature = "wasm")]
3711 Self::Wasm => {
3712 write!(f, "Failed to load the Wasm store.")
3713 }
3714 }
3715 }
3716}
3717
3718impl fmt::Display for QueryError {
3719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3720 let msg = match self.kind {
3721 QueryErrorKind::Field => "Invalid field name ",
3722 QueryErrorKind::NodeType => "Invalid node type ",
3723 QueryErrorKind::Capture => "Invalid capture name ",
3724 QueryErrorKind::Predicate => "Invalid predicate: ",
3725 QueryErrorKind::Structure => "Impossible pattern:\n",
3726 QueryErrorKind::Syntax => "Invalid syntax:\n",
3727 QueryErrorKind::Language => "",
3728 };
3729 if msg.is_empty() {
3730 write!(f, "{}", self.message)
3731 } else {
3732 write!(
3733 f,
3734 "Query error at {}:{}. {}{}",
3735 self.row + 1,
3736 self.column + 1,
3737 msg,
3738 self.message
3739 )
3740 }
3741 }
3742}
3743
3744#[doc(hidden)]
3745#[must_use]
3746pub fn format_sexp(sexp: &str, initial_indent_level: usize) -> String {
3747 let mut indent_level = initial_indent_level;
3748 let mut formatted = String::with_capacity(sexp.len());
3749 let mut has_field = false;
3750
3751 let mut c_iter = sexp.chars().peekable();
3752 let mut scratch = String::with_capacity(sexp.len());
3753 let mut quote = '\0';
3754 let mut saw_paren = false;
3755 let mut did_last = false;
3756
3757 let mut fetch_next_str = |next: &mut String| {
3758 next.clear();
3759 while let Some(c) = c_iter.next() {
3760 if c == '\'' || c == '"' {
3761 quote = c;
3762 } else if c == ' ' || (c == ')' && quote != '\0') {
3763 if let Some(next_c) = c_iter.peek() {
3764 if *next_c == quote {
3765 next.push(c);
3766 next.push(*next_c);
3767 c_iter.next();
3768 quote = '\0';
3769 continue;
3770 }
3771 }
3772 break;
3773 }
3774 if c == ')' {
3775 saw_paren = true;
3776 break;
3777 }
3778 next.push(c);
3779 }
3780
3781 if c_iter.peek().is_none() && next.is_empty() {
3783 if saw_paren {
3784 saw_paren = false;
3786 return Some(());
3787 }
3788 if !did_last {
3789 did_last = true;
3791 return Some(());
3792 }
3793 return None;
3794 }
3795 Some(())
3796 };
3797
3798 while fetch_next_str(&mut scratch).is_some() {
3799 if scratch.is_empty() && indent_level > 0 {
3800 indent_level -= 1;
3802 write!(formatted, ")").unwrap();
3803 } else if scratch.starts_with('(') {
3804 if has_field {
3805 has_field = false;
3806 } else {
3807 if indent_level > 0 {
3808 writeln!(formatted).unwrap();
3809 for _ in 0..indent_level {
3810 write!(formatted, " ").unwrap();
3811 }
3812 }
3813 indent_level += 1;
3814 }
3815
3816 write!(formatted, "{scratch}").unwrap();
3818
3819 if scratch.starts_with("(MISSING") || scratch.starts_with("(UNEXPECTED") {
3821 fetch_next_str(&mut scratch).unwrap();
3822 if scratch.is_empty() {
3823 while indent_level > 0 {
3824 indent_level -= 1;
3825 write!(formatted, ")").unwrap();
3826 }
3827 } else {
3828 write!(formatted, " {scratch}").unwrap();
3829 }
3830 }
3831 } else if scratch.ends_with(':') {
3832 writeln!(formatted).unwrap();
3834 for _ in 0..indent_level {
3835 write!(formatted, " ").unwrap();
3836 }
3837 write!(formatted, "{scratch} ").unwrap();
3838 has_field = true;
3839 indent_level += 1;
3840 }
3841 }
3842
3843 formatted
3844}
3845
3846pub fn wasm_stdlib_symbols() -> impl Iterator<Item = &'static str> {
3847 const WASM_STDLIB_SYMBOLS: &str = include_str!(concat!(env!("OUT_DIR"), "/stdlib-symbols.txt"));
3848
3849 WASM_STDLIB_SYMBOLS
3850 .lines()
3851 .map(|s| s.trim_matches(|c| c == '"' || c == ','))
3852}
3853
3854extern "C" {
3855 fn free(ptr: *mut c_void);
3856}
3857
3858static mut FREE_FN: unsafe extern "C" fn(ptr: *mut c_void) = free;
3859
3860#[doc(alias = "ts_set_allocator")]
3866pub unsafe fn set_allocator(
3867 new_malloc: Option<unsafe extern "C" fn(size: usize) -> *mut c_void>,
3868 new_calloc: Option<unsafe extern "C" fn(nmemb: usize, size: usize) -> *mut c_void>,
3869 new_realloc: Option<unsafe extern "C" fn(ptr: *mut c_void, size: usize) -> *mut c_void>,
3870 new_free: Option<unsafe extern "C" fn(ptr: *mut c_void)>,
3871) {
3872 FREE_FN = new_free.unwrap_or(free);
3873 ffi::ts_set_allocator(new_malloc, new_calloc, new_realloc, new_free);
3874}
3875
3876#[cfg(feature = "std")]
3877#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
3878impl error::Error for IncludedRangesError {}
3879#[cfg(feature = "std")]
3880#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
3881impl error::Error for LanguageError {}
3882#[cfg(feature = "std")]
3883#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
3884impl error::Error for QueryError {}
3885
3886unsafe impl Send for Language {}
3887unsafe impl Sync for Language {}
3888
3889unsafe impl Send for Node<'_> {}
3890unsafe impl Sync for Node<'_> {}
3891
3892unsafe impl Send for LookaheadIterator {}
3893unsafe impl Sync for LookaheadIterator {}
3894
3895unsafe impl Send for LookaheadNamesIterator<'_> {}
3896unsafe impl Sync for LookaheadNamesIterator<'_> {}
3897
3898unsafe impl Send for Parser {}
3899unsafe impl Sync for Parser {}
3900
3901unsafe impl Send for Query {}
3902unsafe impl Sync for Query {}
3903
3904unsafe impl Send for QueryCursor {}
3905unsafe impl Sync for QueryCursor {}
3906
3907unsafe impl Send for Tree {}
3908unsafe impl Sync for Tree {}
3909
3910unsafe impl Send for TreeCursor<'_> {}
3911unsafe impl Sync for TreeCursor<'_> {}