Guest User

Untitled

a guest
Feb 2nd, 2024
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 85.54 KB | None | 0 0
  1. mod ffi;
  2. mod util;
  3.  
  4. #[cfg(unix)]
  5. use std::os::unix::io::AsRawFd;
  6.  
  7. use std::{
  8.     char, error,
  9.     ffi::CStr,
  10.     fmt, hash, iter,
  11.     marker::PhantomData,
  12.     mem::MaybeUninit,
  13.     ops,
  14.     os::raw::{c_char, c_void},
  15.     ptr::{self, NonNull},
  16.     slice, str,
  17.     sync::atomic::AtomicUsize,
  18.     u16,
  19. };
  20.  
  21. /// The latest ABI version that is supported by the current version of the
  22. /// library.
  23. ///
  24. /// When Languages are generated by the Tree-sitter CLI, they are
  25. /// assigned an ABI version number that corresponds to the current CLI version.
  26. /// The Tree-sitter library is generally backwards-compatible with languages
  27. /// generated using older CLI versions, but is not forwards-compatible.
  28. #[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
  29. pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION;
  30.  
  31. /// The earliest ABI version that is supported by the current version of the
  32. /// library.
  33. #[doc(alias = "TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION")]
  34. pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize = ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION;
  35.  
  36. pub const PARSER_HEADER: &'static str = include_str!("../include/tree_sitter/parser.h");
  37.  
  38. /// An opaque object that defines how to parse a particular language. The code for each
  39. /// `Language` is generated by the Tree-sitter CLI.
  40. #[doc(alias = "TSLanguage")]
  41. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
  42. #[repr(transparent)]
  43. pub struct Language(*const ffi::TSLanguage);
  44.  
  45. /// A tree that represents the syntactic structure of a source code file.
  46. #[doc(alias = "TSTree")]
  47. pub struct Tree(NonNull<ffi::TSTree>);
  48.  
  49. /// A position in a multi-line text document, in terms of rows and columns.
  50. ///
  51. /// Rows and columns are zero-based.
  52. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
  53. pub struct Point {
  54.    pub row: usize,
  55.    pub column: usize,
  56. }
  57.  
  58. /// A range of positions in a multi-line text document, both in terms of bytes and of
  59. /// rows and columns.
  60. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
  61. pub struct Range {
  62.    pub start_byte: usize,
  63.    pub end_byte: usize,
  64.    pub start_point: Point,
  65.    pub end_point: Point,
  66. }
  67.  
  68. /// A summary of a change to a text document.
  69. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  70. pub struct InputEdit {
  71.    pub start_byte: usize,
  72.    pub old_end_byte: usize,
  73.    pub new_end_byte: usize,
  74.    pub start_position: Point,
  75.    pub old_end_position: Point,
  76.    pub new_end_position: Point,
  77. }
  78.  
  79. /// A single node within a syntax `Tree`.
  80. #[doc(alias = "TSNode")]
  81. #[derive(Clone, Copy)]
  82. #[repr(transparent)]
  83. pub struct Node<'a>(ffi::TSNode, PhantomData<&'a ()>);
  84.  
  85. /// A stateful object that this is used to produce a `Tree` based on some source code.
  86. #[doc(alias = "TSParser")]
  87. pub struct Parser(NonNull<ffi::TSParser>);
  88.  
  89. /// A type of log message.
  90. #[derive(Debug, PartialEq, Eq)]
  91. pub enum LogType {
  92.    Parse,
  93.    Lex,
  94. }
  95.  
  96. /// A callback that receives log messages during parser.
  97. type Logger<'a> = Box<dyn FnMut(LogType, &str) + 'a>;
  98.  
  99. /// A stateful object for walking a syntax `Tree` efficiently.
  100. #[doc(alias = "TSTreeCursor")]
  101. pub struct TreeCursor<'a>(ffi::TSTreeCursor, PhantomData<&'a ()>);
  102.  
  103. /// A set of patterns that match nodes in a syntax tree.
  104. #[doc(alias = "TSQuery")]
  105. #[derive(Debug)]
  106. pub struct Query {
  107.    ptr: NonNull<ffi::TSQuery>,
  108.    capture_names: Vec<String>,
  109.    capture_quantifiers: Vec<Vec<CaptureQuantifier>>,
  110.    text_predicates: Vec<Box<[TextPredicate]>>,
  111.    property_settings: Vec<Box<[QueryProperty]>>,
  112.    property_predicates: Vec<Box<[(QueryProperty, bool)]>>,
  113.    general_predicates: Vec<Box<[QueryPredicate]>>,
  114. }
  115.  
  116. /// A quantifier for captures
  117. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  118. pub enum CaptureQuantifier {
  119.    Zero,
  120.    ZeroOrOne,
  121.    ZeroOrMore,
  122.    One,
  123.    OneOrMore,
  124. }
  125.  
  126. impl From<ffi::TSQuantifier> for CaptureQuantifier {
  127.    fn from(value: ffi::TSQuantifier) -> Self {
  128.        match value {
  129.            ffi::TSQuantifier_TSQuantifierZero => CaptureQuantifier::Zero,
  130.            ffi::TSQuantifier_TSQuantifierZeroOrOne => CaptureQuantifier::ZeroOrOne,
  131.            ffi::TSQuantifier_TSQuantifierZeroOrMore => CaptureQuantifier::ZeroOrMore,
  132.            ffi::TSQuantifier_TSQuantifierOne => CaptureQuantifier::One,
  133.            ffi::TSQuantifier_TSQuantifierOneOrMore => CaptureQuantifier::OneOrMore,
  134.            _ => panic!("Unrecognized quantifier: {}", value),
  135.        }
  136.    }
  137. }
  138.  
  139. /// A stateful object for executing a `Query` on a syntax `Tree`.
  140. #[doc(alias = "TSQueryCursor")]
  141. pub struct QueryCursor {
  142.    ptr: NonNull<ffi::TSQueryCursor>,
  143. }
  144.  
  145. /// A key-value pair associated with a particular pattern in a `Query`.
  146. #[derive(Debug, PartialEq, Eq)]
  147. pub struct QueryProperty {
  148.    pub key: Box<str>,
  149.    pub value: Option<Box<str>>,
  150.    pub capture_id: Option<usize>,
  151. }
  152.  
  153. #[derive(Debug, PartialEq, Eq)]
  154. pub enum QueryPredicateArg {
  155.    Capture(u32),
  156.    String(Box<str>),
  157. }
  158.  
  159. /// A key-value pair associated with a particular pattern in a `Query`.
  160. #[derive(Debug, PartialEq, Eq)]
  161. pub struct QueryPredicate {
  162.    pub operator: Box<str>,
  163.    pub args: Vec<QueryPredicateArg>,
  164. }
  165.  
  166. /// A match of a `Query` to a particular set of `Node`s.
  167. pub struct QueryMatch<'cursor, 'tree> {
  168.    pub pattern_index: usize,
  169.    pub captures: &'cursor [QueryCapture<'tree>],
  170.    id: u32,
  171.    cursor: *mut ffi::TSQueryCursor,
  172. }
  173.  
  174. /// A sequence of `QueryMatch`es associated with a given `QueryCursor`.
  175. pub struct QueryMatches<'a, 'tree: 'a, T: TextProvider<'a>> {
  176.    ptr: *mut ffi::TSQueryCursor,
  177.    query: &'a Query,
  178.     text_provider: T,
  179.     buffer1: Vec<u8>,
  180.     buffer2: Vec<u8>,
  181.     _tree: PhantomData<&'tree ()>,
  182. }
  183.  
  184. /// A sequence of `QueryCapture`s associated with a given `QueryCursor`.
  185. pub struct QueryCaptures<'a, 'tree: 'a, T: TextProvider<'a>> {
  186.    ptr: *mut ffi::TSQueryCursor,
  187.    query: &'a Query,
  188.     text_provider: T,
  189.     buffer1: Vec<u8>,
  190.     buffer2: Vec<u8>,
  191.     _tree: PhantomData<&'tree ()>,
  192. }
  193.  
  194. pub trait TextProvider<'a> {
  195.     type I: Iterator<Item = &'a [u8]> + 'a;
  196.     fn text(&mut self, node: Node) -> Self::I;
  197. }
  198.  
  199. /// A particular `Node` that has been captured with a particular name within a `Query`.
  200. #[derive(Clone, Copy, Debug)]
  201. #[repr(C)]
  202. pub struct QueryCapture<'a> {
  203.    pub node: Node<'a>,
  204.     pub index: u32,
  205. }
  206.  
  207. /// An error that occurred when trying to assign an incompatible `Language` to a `Parser`.
  208. #[derive(Debug, PartialEq, Eq)]
  209. pub struct LanguageError {
  210.     version: usize,
  211. }
  212.  
  213. /// An error that occurred in `Parser::set_included_ranges`.
  214. #[derive(Debug, PartialEq, Eq)]
  215. pub struct IncludedRangesError(pub usize);
  216.  
  217. /// An error that occurred when trying to create a `Query`.
  218. #[derive(Debug, PartialEq, Eq)]
  219. pub struct QueryError {
  220.     pub row: usize,
  221.     pub column: usize,
  222.     pub offset: usize,
  223.     pub message: String,
  224.     pub kind: QueryErrorKind,
  225. }
  226.  
  227. #[derive(Debug, PartialEq, Eq)]
  228. pub enum QueryErrorKind {
  229.     Syntax,
  230.     NodeType,
  231.     Field,
  232.     Capture,
  233.     Predicate,
  234.     Structure,
  235.     Language,
  236. }
  237.  
  238. #[derive(Debug)]
  239. enum TextPredicate {
  240.     CaptureEqString(u32, String, bool),
  241.     CaptureEqCapture(u32, u32, bool),
  242.     CaptureMatchString(u32, regex::bytes::Regex, bool),
  243. }
  244.  
  245. // TODO: Remove this struct at at some point. If `core::str::lossy::Utf8Lossy`
  246. // is ever stabilized.
  247. pub struct LossyUtf8<'a> {
  248.    bytes: &'a [u8],
  249.     in_replacement: bool,
  250. }
  251.  
  252. impl Language {
  253.     /// Get the ABI version number that indicates which version of the Tree-sitter CLI
  254.     /// that was used to generate this `Language`.
  255.     #[doc(alias = "ts_language_version")]
  256.     pub fn version(&self) -> usize {
  257.         unsafe { ffi::ts_language_version(self.0) as usize }
  258.     }
  259.  
  260.     /// Get the number of distinct node types in this language.
  261.     #[doc(alias = "ts_language_symbol_count")]
  262.     pub fn node_kind_count(&self) -> usize {
  263.         unsafe { ffi::ts_language_symbol_count(self.0) as usize }
  264.     }
  265.  
  266.     /// Get the name of the node kind for the given numerical id.
  267.     #[doc(alias = "ts_language_symbol_name")]
  268.     pub fn node_kind_for_id(&self, id: u16) -> Option<&'static str> {
  269.        let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
  270.        if ptr.is_null() {
  271.            None
  272.        } else {
  273.            Some(unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
  274.        }
  275.    }
  276.  
  277.    /// Get the numeric id for the given node kind.
  278.    #[doc(alias = "ts_language_symbol_for_name")]
  279.    pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
  280.        unsafe {
  281.            ffi::ts_language_symbol_for_name(
  282.                self.0,
  283.                kind.as_bytes().as_ptr() as *const c_char,
  284.                kind.len() as u32,
  285.                named,
  286.            )
  287.        }
  288.    }
  289.  
  290.    /// Check if the node type for the given numerical id is named (as opposed
  291.    /// to an anonymous node type).
  292.    pub fn node_kind_is_named(&self, id: u16) -> bool {
  293.        unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolType_TSSymbolTypeRegular }
  294.    }
  295.  
  296.    #[doc(alias = "ts_language_symbol_type")]
  297.    pub fn node_kind_is_visible(&self, id: u16) -> bool {
  298.        unsafe {
  299.            ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolType_TSSymbolTypeAnonymous
  300.        }
  301.    }
  302.  
  303.    /// Get the number of distinct field names in this language.
  304.    #[doc(alias = "ts_language_field_count")]
  305.    pub fn field_count(&self) -> usize {
  306.        unsafe { ffi::ts_language_field_count(self.0) as usize }
  307.    }
  308.  
  309.    /// Get the field names for the given numerical id.
  310.    #[doc(alias = "ts_language_field_name_for_id")]
  311.    pub fn field_name_for_id(&self, field_id: u16) -> Option<&'static str> {
  312.         let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
  313.         if ptr.is_null() {
  314.             None
  315.         } else {
  316.             Some(unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
  317.         }
  318.     }
  319.  
  320.     /// Get the numerical id for the given field name.
  321.     #[doc(alias = "ts_language_field_id_for_name")]
  322.     pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<u16> {
  323.         let field_name = field_name.as_ref();
  324.         let id = unsafe {
  325.             ffi::ts_language_field_id_for_name(
  326.                 self.0,
  327.                 field_name.as_ptr() as *const c_char,
  328.                 field_name.len() as u32,
  329.             )
  330.         };
  331.         if id == 0 {
  332.             None
  333.         } else {
  334.             Some(id)
  335.         }
  336.     }
  337. }
  338.  
  339. impl Parser {
  340.     /// Create a new parser.
  341.     pub fn new() -> Parser {
  342.         unsafe {
  343.             let parser = ffi::ts_parser_new();
  344.             Parser(NonNull::new_unchecked(parser))
  345.         }
  346.     }
  347.  
  348.     /// Set the language that the parser should use for parsing.
  349.     ///
  350.     /// Returns a Result indicating whether or not the language was successfully
  351.     /// assigned. True means assignment succeeded. False means there was a version
  352.     /// mismatch: the language was generated with an incompatible version of the
  353.     /// Tree-sitter CLI. Check the language's version using [Language::version]
  354.     /// and compare it to this library's [LANGUAGE_VERSION](LANGUAGE_VERSION) and
  355.     /// [MIN_COMPATIBLE_LANGUAGE_VERSION](MIN_COMPATIBLE_LANGUAGE_VERSION) constants.
  356.     #[doc(alias = "ts_parser_set_language")]
  357.     pub fn set_language(&mut self, language: Language) -> Result<(), LanguageError> {
  358.         let version = language.version();
  359.         if version < MIN_COMPATIBLE_LANGUAGE_VERSION || version > LANGUAGE_VERSION {
  360.             Err(LanguageError { version })
  361.         } else {
  362.             unsafe {
  363.                 ffi::ts_parser_set_language(self.0.as_ptr(), language.0);
  364.             }
  365.             Ok(())
  366.         }
  367.     }
  368.  
  369.     /// Get the parser's current language.
  370.     #[doc(alias = "ts_parser_language")]
  371.     pub fn language(&self) -> Option<Language> {
  372.         let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
  373.         if ptr.is_null() {
  374.             None
  375.         } else {
  376.             Some(Language(ptr))
  377.         }
  378.     }
  379.  
  380.     /// Get the parser's current logger.
  381.     #[doc(alias = "ts_parser_logger")]
  382.     pub fn logger(&self) -> Option<&Logger> {
  383.         let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
  384.         unsafe { (logger.payload as *mut Logger).as_ref() }
  385.     }
  386.  
  387.     /// Set the logging callback that a parser should use during parsing.
  388.     #[doc(alias = "ts_parser_set_logger")]
  389.     pub fn set_logger(&mut self, logger: Option<Logger>) {
  390.         let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
  391.         if !prev_logger.payload.is_null() {
  392.             drop(unsafe { Box::from_raw(prev_logger.payload as *mut Logger) });
  393.         }
  394.  
  395.         let c_logger;
  396.         if let Some(logger) = logger {
  397.             let container = Box::new(logger);
  398.  
  399.             unsafe extern "C" fn log(
  400.                 payload: *mut c_void,
  401.                 c_log_type: ffi::TSLogType,
  402.                 c_message: *const c_char,
  403.             ) {
  404.                 let callback = (payload as *mut Logger).as_mut().unwrap();
  405.                 if let Ok(message) = CStr::from_ptr(c_message).to_str() {
  406.                     let log_type = if c_log_type == ffi::TSLogType_TSLogTypeParse {
  407.                         LogType::Parse
  408.                     } else {
  409.                         LogType::Lex
  410.                     };
  411.                     callback(log_type, message);
  412.                 }
  413.             }
  414.  
  415.             let raw_container = Box::into_raw(container);
  416.  
  417.             c_logger = ffi::TSLogger {
  418.                 payload: raw_container as *mut c_void,
  419.                 log: Some(log),
  420.             };
  421.         } else {
  422.             c_logger = ffi::TSLogger {
  423.                 payload: ptr::null_mut(),
  424.                 log: None,
  425.             };
  426.         }
  427.  
  428.         unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
  429.     }
  430.  
  431.     /// Set the destination to which the parser should write debugging graphs
  432.     /// during parsing. The graphs are formatted in the DOT language. You may want
  433.     /// to pipe these graphs directly to a `dot(1)` process in order to generate
  434.     /// SVG output.
  435.     #[cfg(unix)]
  436.     #[doc(alias = "ts_parser_print_dot_graphs")]
  437.     pub fn print_dot_graphs(&mut self, file: &impl AsRawFd) {
  438.         let fd = file.as_raw_fd();
  439.         unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::dup(fd)) }
  440.     }
  441.  
  442.     /// Stop the parser from printing debugging graphs while parsing.
  443.     #[doc(alias = "ts_parser_print_dot_graphs")]
  444.     pub fn stop_printing_dot_graphs(&mut self) {
  445.         unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
  446.     }
  447.  
  448.     /// Parse a slice of UTF8 text.
  449.     ///
  450.     /// # Arguments:
  451.     /// * `text` The UTF8-encoded text to parse.
  452.     /// * `old_tree` A previous syntax tree parsed from the same document.
  453.     ///   If the text of the document has changed since `old_tree` was
  454.     ///   created, then you must edit `old_tree` to match the new text using
  455.     ///   [Tree::edit].
  456.     ///
  457.     /// Returns a [Tree] if parsing succeeded, or `None` if:
  458.     ///  * The parser has not yet had a language assigned with [Parser::set_language]
  459.     ///  * The timeout set with [Parser::set_timeout_micros] expired
  460.     ///  * The cancellation flag set with [Parser::set_cancellation_flag] was flipped
  461.     #[doc(alias = "ts_parser_parse")]
  462.     pub fn parse(&mut self, text: impl AsRef<[u8]>, old_tree: Option<&Tree>) -> Option<Tree> {
  463.         let bytes = text.as_ref();
  464.         let len = bytes.len();
  465.         self.parse_with(
  466.             &mut |i, _| if i < len { &bytes[i..] } else { &[] },
  467.             old_tree,
  468.         )
  469.     }
  470.  
  471.     /// Parse a slice of UTF16 text.
  472.     ///
  473.     /// # Arguments:
  474.     /// * `text` The UTF16-encoded text to parse.
  475.     /// * `old_tree` A previous syntax tree parsed from the same document.
  476.     ///   If the text of the document has changed since `old_tree` was
  477.     ///   created, then you must edit `old_tree` to match the new text using
  478.     ///   [Tree::edit].
  479.     pub fn parse_utf16(
  480.         &mut self,
  481.         input: impl AsRef<[u16]>,
  482.         old_tree: Option<&Tree>,
  483.     ) -> Option<Tree> {
  484.         let code_points = input.as_ref();
  485.         let len = code_points.len();
  486.         self.parse_utf16_with(
  487.             &mut |i, _| if i < len { &code_points[i..] } else { &[] },
  488.             old_tree,
  489.         )
  490.     }
  491.  
  492.     /// Parse UTF8 text provided in chunks by a callback.
  493.     ///
  494.     /// # Arguments:
  495.     /// * `callback` A function that takes a byte offset and position and
  496.     ///   returns a slice of UTF8-encoded text starting at that byte offset
  497.     ///   and position. The slices can be of any length. If the given position
  498.     ///   is at the end of the text, the callback should return an empty slice.
  499.     /// * `old_tree` A previous syntax tree parsed from the same document.
  500.     ///   If the text of the document has changed since `old_tree` was
  501.     ///   created, then you must edit `old_tree` to match the new text using
  502.     ///   [Tree::edit].
  503.     pub fn parse_with<'a, T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
  504.        &mut self,
  505.        callback: &mut F,
  506.        old_tree: Option<&Tree>,
  507.    ) -> Option<Tree> {
  508.        // A pointer to this payload is passed on every call to the `read` C function.
  509.        // The payload contains two things:
  510.        // 1. A reference to the rust `callback`.
  511.        // 2. The text that was returned from the previous call to `callback`.
  512.        //    This allows the callback to return owned values like vectors.
  513.        let mut payload: (&mut F, Option<T>) = (callback, None);
  514.  
  515.        // This C function is passed to Tree-sitter as the input callback.
  516.        unsafe extern "C" fn read<'a, T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
  517.             payload: *mut c_void,
  518.             byte_offset: u32,
  519.             position: ffi::TSPoint,
  520.             bytes_read: *mut u32,
  521.         ) -> *const c_char {
  522.             let (callback, text) = (payload as *mut (&mut F, Option<T>)).as_mut().unwrap();
  523.             *text = Some(callback(byte_offset as usize, position.into()));
  524.             let slice = text.as_ref().unwrap().as_ref();
  525.             *bytes_read = slice.len() as u32;
  526.             return slice.as_ptr() as *const c_char;
  527.         }
  528.  
  529.         let c_input = ffi::TSInput {
  530.             payload: &mut payload as *mut (&mut F, Option<T>) as *mut c_void,
  531.             read: Some(read::<T, F>),
  532.             encoding: ffi::TSInputEncoding_TSInputEncodingUTF8,
  533.         };
  534.  
  535.         let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
  536.         unsafe {
  537.             let c_new_tree = ffi::ts_parser_parse(self.0.as_ptr(), c_old_tree, c_input);
  538.             NonNull::new(c_new_tree).map(Tree)
  539.         }
  540.     }
  541.  
  542.     /// Parse UTF16 text provided in chunks by a callback.
  543.     ///
  544.     /// # Arguments:
  545.     /// * `callback` A function that takes a code point offset and position and
  546.     ///   returns a slice of UTF16-encoded text starting at that byte offset
  547.     ///   and position. The slices can be of any length. If the given position
  548.     ///   is at the end of the text, the callback should return an empty slice.
  549.     /// * `old_tree` A previous syntax tree parsed from the same document.
  550.     ///   If the text of the document has changed since `old_tree` was
  551.     ///   created, then you must edit `old_tree` to match the new text using
  552.     ///   [Tree::edit].
  553.     pub fn parse_utf16_with<'a, T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
  554.        &mut self,
  555.        callback: &mut F,
  556.        old_tree: Option<&Tree>,
  557.    ) -> Option<Tree> {
  558.        // A pointer to this payload is passed on every call to the `read` C function.
  559.        // The payload contains two things:
  560.        // 1. A reference to the rust `callback`.
  561.        // 2. The text that was returned from the previous call to `callback`.
  562.        //    This allows the callback to return owned values like vectors.
  563.        let mut payload: (&mut F, Option<T>) = (callback, None);
  564.  
  565.        // This C function is passed to Tree-sitter as the input callback.
  566.        unsafe extern "C" fn read<'a, T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
  567.             payload: *mut c_void,
  568.             byte_offset: u32,
  569.             position: ffi::TSPoint,
  570.             bytes_read: *mut u32,
  571.         ) -> *const c_char {
  572.             let (callback, text) = (payload as *mut (&mut F, Option<T>)).as_mut().unwrap();
  573.             *text = Some(callback(
  574.                 (byte_offset / 2) as usize,
  575.                 Point {
  576.                     row: position.row as usize,
  577.                     column: position.column as usize / 2,
  578.                 },
  579.             ));
  580.             let slice = text.as_ref().unwrap().as_ref();
  581.             *bytes_read = slice.len() as u32 * 2;
  582.             slice.as_ptr() as *const c_char
  583.         }
  584.  
  585.         let c_input = ffi::TSInput {
  586.             payload: &mut payload as *mut (&mut F, Option<T>) as *mut c_void,
  587.             read: Some(read::<T, F>),
  588.             encoding: ffi::TSInputEncoding_TSInputEncodingUTF16,
  589.         };
  590.  
  591.         let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
  592.         unsafe {
  593.             let c_new_tree = ffi::ts_parser_parse(self.0.as_ptr(), c_old_tree, c_input);
  594.             NonNull::new(c_new_tree).map(Tree)
  595.         }
  596.     }
  597.  
  598.     /// Instruct the parser to start the next parse from the beginning.
  599.     ///
  600.     /// If the parser previously failed because of a timeout or a cancellation, then
  601.     /// by default, it will resume where it left off on the next call to `parse` or
  602.     /// other parsing functions. If you don't want to resume, and instead intend to
  603.     /// use this parser to parse some other document, you must call `reset` first.
  604.     #[doc(alias = "ts_parser_reset")]
  605.     pub fn reset(&mut self) {
  606.         unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
  607.     }
  608.  
  609.     /// Get the duration in microseconds that parsing is allowed to take.
  610.     ///
  611.     /// This is set via [set_timeout_micros](Parser::set_timeout_micros).
  612.     #[doc(alias = "ts_parser_timeout_micros")]
  613.     pub fn timeout_micros(&self) -> u64 {
  614.         unsafe { ffi::ts_parser_timeout_micros(self.0.as_ptr()) }
  615.     }
  616.  
  617.     /// Set the maximum duration in microseconds that parsing should be allowed to
  618.     /// take before halting.
  619.     ///
  620.     /// If parsing takes longer than this, it will halt early, returning `None`.
  621.     /// See `parse` for more information.
  622.     #[doc(alias = "ts_parser_set_timeout_micros")]
  623.     pub fn set_timeout_micros(&mut self, timeout_micros: u64) {
  624.         unsafe { ffi::ts_parser_set_timeout_micros(self.0.as_ptr(), timeout_micros) }
  625.     }
  626.  
  627.     /// Set the ranges of text that the parser should include when parsing.
  628.     ///
  629.     /// By default, the parser will always include entire documents. This function
  630.     /// allows you to parse only a *portion* of a document but still return a syntax
  631.     /// tree whose ranges match up with the document as a whole. You can also pass
  632.     /// multiple disjoint ranges.
  633.     ///
  634.     /// If `ranges` is empty, then the entire document will be parsed. Otherwise,
  635.     /// the given ranges must be ordered from earliest to latest in the document,
  636.     /// and they must not overlap. That is, the following must hold for all
  637.     /// `i` < `length - 1`:
  638.     /// ```text
  639.     ///     ranges[i].end_byte <= ranges[i + 1].start_byte
  640.     /// ```
  641.     /// If this requirement is not satisfied, method will return IncludedRangesError
  642.     /// error with an offset in the passed ranges slice pointing to a first incorrect range.
  643.     #[doc(alias = "ts_parser_set_included_ranges")]
  644.     pub fn set_included_ranges<'a>(
  645.        &mut self,
  646.        ranges: &'a [Range],
  647.     ) -> Result<(), IncludedRangesError> {
  648.         let ts_ranges: Vec<ffi::TSRange> =
  649.             ranges.iter().cloned().map(|range| range.into()).collect();
  650.         let result = unsafe {
  651.             ffi::ts_parser_set_included_ranges(
  652.                 self.0.as_ptr(),
  653.                 ts_ranges.as_ptr(),
  654.                 ts_ranges.len() as u32,
  655.             )
  656.         };
  657.  
  658.         if result {
  659.             Ok(())
  660.         } else {
  661.             let mut prev_end_byte = 0;
  662.             for (i, range) in ranges.iter().enumerate() {
  663.                 if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
  664.                     return Err(IncludedRangesError(i));
  665.                 }
  666.                 prev_end_byte = range.end_byte;
  667.             }
  668.             Err(IncludedRangesError(0))
  669.         }
  670.     }
  671.  
  672.     /// Get the parser's current cancellation flag pointer.
  673.     #[doc(alias = "ts_parser_cancellation_flag")]
  674.     pub unsafe fn cancellation_flag(&self) -> Option<&AtomicUsize> {
  675.         (ffi::ts_parser_cancellation_flag(self.0.as_ptr()) as *const AtomicUsize).as_ref()
  676.     }
  677.  
  678.     /// Set the parser's current cancellation flag pointer.
  679.     ///
  680.     /// If a pointer is assigned, then the parser will periodically read from
  681.     /// this pointer during parsing. If it reads a non-zero value, it will halt early,
  682.     /// returning `None`. See [parse](Parser::parse) for more information.
  683.     #[doc(alias = "ts_parser_set_cancellation_flag")]
  684.     pub unsafe fn set_cancellation_flag(&mut self, flag: Option<&AtomicUsize>) {
  685.         if let Some(flag) = flag {
  686.             ffi::ts_parser_set_cancellation_flag(
  687.                 self.0.as_ptr(),
  688.                 flag as *const AtomicUsize as *const usize,
  689.             );
  690.         } else {
  691.             ffi::ts_parser_set_cancellation_flag(self.0.as_ptr(), ptr::null());
  692.         }
  693.     }
  694. }
  695.  
  696. impl Drop for Parser {
  697.     fn drop(&mut self) {
  698.         self.stop_printing_dot_graphs();
  699.         self.set_logger(None);
  700.         unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
  701.     }
  702. }
  703.  
  704. impl Tree {
  705.     /// Get the root node of the syntax tree.
  706.     #[doc(alias = "ts_tree_root_node")]
  707.     pub fn root_node(&self) -> Node {
  708.         Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
  709.     }
  710.  
  711.     /// Get the root node of the syntax tree, but with its position shifted
  712.     /// forward by the given offset.
  713.     #[doc(alias = "ts_tree_root_node_with_offset")]
  714.     pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
  715.         Node::new(unsafe {
  716.             ffi::ts_tree_root_node_with_offset(
  717.                 self.0.as_ptr(),
  718.                 offset_bytes as u32,
  719.                 offset_extent.into(),
  720.             )
  721.         })
  722.         .unwrap()
  723.     }
  724.  
  725.     /// Get the language that was used to parse the syntax tree.
  726.     #[doc(alias = "ts_tree_language")]
  727.     pub fn language(&self) -> Language {
  728.         Language(unsafe { ffi::ts_tree_language(self.0.as_ptr()) })
  729.     }
  730.  
  731.     /// Edit the syntax tree to keep it in sync with source code that has been
  732.     /// edited.
  733.     ///
  734.     /// You must describe the edit both in terms of byte offsets and in terms of
  735.     /// row/column coordinates.
  736.     #[doc(alias = "ts_tree_edit")]
  737.     pub fn edit(&mut self, edit: &InputEdit) {
  738.         let edit = edit.into();
  739.         unsafe { ffi::ts_tree_edit(self.0.as_ptr(), &edit) };
  740.     }
  741.  
  742.     /// Create a new [TreeCursor] starting from the root of the tree.
  743.     pub fn walk(&self) -> TreeCursor {
  744.         self.root_node().walk()
  745.     }
  746.  
  747.     /// Compare this old edited syntax tree to a new syntax tree representing the same
  748.     /// document, returning a sequence of ranges whose syntactic structure has changed.
  749.     ///
  750.     /// For this to work correctly, this syntax tree must have been edited such that its
  751.     /// ranges match up to the new tree. Generally, you'll want to call this method right
  752.     /// after calling one of the [Parser::parse] functions. Call it on the old tree that
  753.     /// was passed to parse, and pass the new tree that was returned from `parse`.
  754.     #[doc(alias = "ts_tree_get_changed_ranges")]
  755.     pub fn changed_ranges(&self, other: &Tree) -> impl ExactSizeIterator<Item = Range> {
  756.         let mut count = 0u32;
  757.         unsafe {
  758.             let ptr = ffi::ts_tree_get_changed_ranges(
  759.                 self.0.as_ptr(),
  760.                 other.0.as_ptr(),
  761.                 &mut count as *mut u32,
  762.             );
  763.             util::CBufferIter::new(ptr, count as usize).map(|r| r.into())
  764.         }
  765.     }
  766.  
  767.     /// Get the included ranges that were used to parse the syntax tree.
  768.     pub fn included_ranges(&self) -> Vec<Range> {
  769.         let mut count = 0u32;
  770.         unsafe {
  771.             let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), &mut count as *mut u32);
  772.             let ranges = slice::from_raw_parts(ptr, count as usize);
  773.             let result = ranges.iter().copied().map(|range| range.into()).collect();
  774.             (FREE_FN)(ptr as *mut c_void);
  775.             result
  776.         }
  777.     }
  778.  
  779.     /// Print a graph of the tree to the given file descriptor.
  780.     /// The graph is formatted in the DOT language. You may want to pipe this graph
  781.     /// directly to a `dot(1)` process in order to generate SVG output.
  782.     #[cfg(unix)]
  783.     #[doc(alias = "ts_tree_print_dot_graph")]
  784.     pub fn print_dot_graph(&self, file: &impl AsRawFd) {
  785.         let fd = file.as_raw_fd();
  786.         unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
  787.     }
  788. }
  789.  
  790. impl fmt::Debug for Tree {
  791.     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  792.         write!(f, "{{Tree {:?}}}", self.root_node())
  793.     }
  794. }
  795.  
  796. impl Drop for Tree {
  797.     fn drop(&mut self) {
  798.         unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
  799.     }
  800. }
  801.  
  802. impl Clone for Tree {
  803.     fn clone(&self) -> Tree {
  804.         unsafe { Tree(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
  805.     }
  806. }
  807.  
  808. impl<'tree> Node<'tree> {
  809.     fn new(node: ffi::TSNode) -> Option<Self> {
  810.         if node.id.is_null() {
  811.             None
  812.         } else {
  813.             Some(Node(node, PhantomData))
  814.         }
  815.     }
  816.  
  817.     /// Get a numeric id for this node that is unique.
  818.     ///
  819.     /// Within a given syntax tree, no two nodes have the same id. However, if
  820.     /// a new tree is created based on an older tree, and a node from the old
  821.     /// tree is reused in the process, then that node will have the same id in
  822.     /// both trees.
  823.     pub fn id(&self) -> usize {
  824.         self.0.id as usize
  825.     }
  826.  
  827.     /// Get this node's type as a numerical id.
  828.     #[doc(alias = "ts_node_symbol")]
  829.     pub fn kind_id(&self) -> u16 {
  830.         unsafe { ffi::ts_node_symbol(self.0) }
  831.     }
  832.  
  833.     /// Get this node's type as a string.
  834.     #[doc(alias = "ts_node_type")]
  835.     pub fn kind(&self) -> &'static str {
  836.        unsafe { CStr::from_ptr(ffi::ts_node_type(self.0)) }
  837.            .to_str()
  838.            .unwrap()
  839.    }
  840.  
  841.    /// Get the [Language] that was used to parse this node's syntax tree.
  842.     #[doc(alias = "ts_tree_language")]
  843.     pub fn language(&self) -> Language {
  844.         Language(unsafe { ffi::ts_tree_language(self.0.tree) })
  845.     }
  846.  
  847.     /// Check if this node is *named*.
  848.     ///
  849.     /// Named nodes correspond to named rules in the grammar, whereas *anonymous* nodes
  850.     /// correspond to string literals in the grammar.
  851.     #[doc(alias = "ts_node_is_named")]
  852.     pub fn is_named(&self) -> bool {
  853.         unsafe { ffi::ts_node_is_named(self.0) }
  854.     }
  855.  
  856.     /// Check if this node is *extra*.
  857.     ///
  858.     /// Extra nodes represent things like comments, which are not required the grammar,
  859.     /// but can appear anywhere.
  860.     #[doc(alias = "ts_node_is_extra")]
  861.     pub fn is_extra(&self) -> bool {
  862.         unsafe { ffi::ts_node_is_extra(self.0) }
  863.     }
  864.  
  865.     /// Check if this node has been edited.
  866.     #[doc(alias = "ts_node_has_changes")]
  867.     pub fn has_changes(&self) -> bool {
  868.         unsafe { ffi::ts_node_has_changes(self.0) }
  869.     }
  870.  
  871.     /// Check if this node represents a syntax error or contains any syntax errors anywhere
  872.     /// within it.
  873.     #[doc(alias = "ts_node_has_error")]
  874.     pub fn has_error(&self) -> bool {
  875.         unsafe { ffi::ts_node_has_error(self.0) }
  876.     }
  877.  
  878.     /// Check if this node represents a syntax error.
  879.     ///
  880.     /// Syntax errors represent parts of the code that could not be incorporated into a
  881.     /// valid syntax tree.
  882.     pub fn is_error(&self) -> bool {
  883.         self.kind_id() == u16::MAX
  884.     }
  885.  
  886.     /// Check if this node is *missing*.
  887.     ///
  888.     /// Missing nodes are inserted by the parser in order to recover from certain kinds of
  889.     /// syntax errors.
  890.     #[doc(alias = "ts_node_is_missing")]
  891.     pub fn is_missing(&self) -> bool {
  892.         unsafe { ffi::ts_node_is_missing(self.0) }
  893.     }
  894.  
  895.     /// Get the byte offsets where this node starts.
  896.     #[doc(alias = "ts_node_start_byte")]
  897.     pub fn start_byte(&self) -> usize {
  898.         unsafe { ffi::ts_node_start_byte(self.0) as usize }
  899.     }
  900.  
  901.     /// Get the byte offsets where this node end.
  902.     #[doc(alias = "ts_node_end_byte")]
  903.     pub fn end_byte(&self) -> usize {
  904.         unsafe { ffi::ts_node_end_byte(self.0) as usize }
  905.     }
  906.  
  907.     /// Get the byte range of source code that this node represents.
  908.     pub fn byte_range(&self) -> std::ops::Range<usize> {
  909.         self.start_byte()..self.end_byte()
  910.     }
  911.  
  912.     /// Get the range of source code that this node represents, both in terms of raw bytes
  913.     /// and of row/column coordinates.
  914.     pub fn range(&self) -> Range {
  915.         Range {
  916.             start_byte: self.start_byte(),
  917.             end_byte: self.end_byte(),
  918.             start_point: self.start_position(),
  919.             end_point: self.end_position(),
  920.         }
  921.     }
  922.  
  923.     /// Get this node's start position in terms of rows and columns.
  924.     #[doc(alias = "ts_node_start_point")]
  925.     pub fn start_position(&self) -> Point {
  926.         let result = unsafe { ffi::ts_node_start_point(self.0) };
  927.         result.into()
  928.     }
  929.  
  930.     /// Get this node's end position in terms of rows and columns.
  931.     #[doc(alias = "ts_node_end_point")]
  932.     pub fn end_position(&self) -> Point {
  933.         let result = unsafe { ffi::ts_node_end_point(self.0) };
  934.         result.into()
  935.     }
  936.  
  937.     /// Get the node's child at the given index, where zero represents the first
  938.     /// child.
  939.     ///
  940.     /// This method is fairly fast, but its cost is technically log(i), so you
  941.     /// if you might be iterating over a long list of children, you should use
  942.     /// [Node::children] instead.
  943.     #[doc(alias = "ts_node_child")]
  944.     pub fn child(&self, i: usize) -> Option<Self> {
  945.         Self::new(unsafe { ffi::ts_node_child(self.0, i as u32) })
  946.     }
  947.  
  948.     /// Get this node's number of children.
  949.     #[doc(alias = "ts_node_child_count")]
  950.     pub fn child_count(&self) -> usize {
  951.         unsafe { ffi::ts_node_child_count(self.0) as usize }
  952.     }
  953.  
  954.     /// Get this node's *named* child at the given index.
  955.     ///
  956.     /// See also [Node::is_named].
  957.     /// This method is fairly fast, but its cost is technically log(i), so you
  958.     /// if you might be iterating over a long list of children, you should use
  959.     /// [Node::named_children] instead.
  960.     #[doc(alias = "ts_node_named_child")]
  961.     pub fn named_child<'a>(&'a self, i: usize) -> Option<Self> {
  962.         Self::new(unsafe { ffi::ts_node_named_child(self.0, i as u32) })
  963.     }
  964.  
  965.     /// Get this node's number of *named* children.
  966.     ///
  967.     /// See also [Node::is_named].
  968.     #[doc(alias = "ts_node_named_child_count")]
  969.     pub fn named_child_count(&self) -> usize {
  970.         unsafe { ffi::ts_node_named_child_count(self.0) as usize }
  971.     }
  972.  
  973.     /// Get the first child with the given field name.
  974.     ///
  975.     /// If multiple children may have the same field name, access them using
  976.     /// [children_by_field_name](Node::children_by_field_name)
  977.     #[doc(alias = "ts_node_child_by_field_name")]
  978.     pub fn child_by_field_name(&self, field_name: impl AsRef<[u8]>) -> Option<Self> {
  979.         let field_name = field_name.as_ref();
  980.         Self::new(unsafe {
  981.             ffi::ts_node_child_by_field_name(
  982.                 self.0,
  983.                 field_name.as_ptr() as *const c_char,
  984.                 field_name.len() as u32,
  985.             )
  986.         })
  987.     }
  988.  
  989.     /// Get this node's child with the given numerical field id.
  990.     ///
  991.     /// See also [child_by_field_name](Node::child_by_field_name). You can convert a field name to
  992.     /// an id using [Language::field_id_for_name].
  993.     #[doc(alias = "ts_node_child_by_field_id")]
  994.     pub fn child_by_field_id(&self, field_id: u16) -> Option<Self> {
  995.         Self::new(unsafe { ffi::ts_node_child_by_field_id(self.0, field_id) })
  996.     }
  997.  
  998.     /// Get the field name of this node's child at the given index.
  999.     #[doc(alias = "ts_node_field_name_for_child")]
  1000.     pub fn field_name_for_child(&self, child_index: u32) -> Option<&'static str> {
  1001.        unsafe {
  1002.            let ptr = ffi::ts_node_field_name_for_child(self.0, child_index);
  1003.            if ptr.is_null() {
  1004.                None
  1005.            } else {
  1006.                Some(CStr::from_ptr(ptr).to_str().unwrap())
  1007.            }
  1008.        }
  1009.    }
  1010.  
  1011.    /// Iterate over this node's children.
  1012.     ///
  1013.     /// A [TreeCursor] is used to retrieve the children efficiently. Obtain
  1014.     /// a [TreeCursor] by calling [Tree::walk] or [Node::walk]. To avoid unnecessary
  1015.     /// allocations, you should reuse the same cursor for subsequent calls to
  1016.     /// this method.
  1017.     ///
  1018.     /// If you're walking the tree recursively, you may want to use the `TreeCursor`
  1019.     /// APIs directly instead.
  1020.     pub fn children<'a>(
  1021.        &self,
  1022.        cursor: &'a mut TreeCursor<'tree>,
  1023.    ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'a {
  1024.        cursor.reset(*self);
  1025.        cursor.goto_first_child();
  1026.        (0..self.child_count()).into_iter().map(move |_| {
  1027.            let result = cursor.node();
  1028.            cursor.goto_next_sibling();
  1029.            result
  1030.        })
  1031.    }
  1032.  
  1033.    /// Iterate over this node's named children.
  1034.     ///
  1035.     /// See also [Node::children].
  1036.     pub fn named_children<'a>(
  1037.        &self,
  1038.        cursor: &'a mut TreeCursor<'tree>,
  1039.    ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'a {
  1040.        cursor.reset(*self);
  1041.        cursor.goto_first_child();
  1042.        (0..self.named_child_count()).into_iter().map(move |_| {
  1043.            while !cursor.node().is_named() {
  1044.                if !cursor.goto_next_sibling() {
  1045.                    break;
  1046.                }
  1047.            }
  1048.            let result = cursor.node();
  1049.            cursor.goto_next_sibling();
  1050.            result
  1051.        })
  1052.    }
  1053.  
  1054.    /// Iterate over this node's children with a given field name.
  1055.     ///
  1056.     /// See also [Node::children].
  1057.     pub fn children_by_field_name<'a>(
  1058.        &self,
  1059.        field_name: &str,
  1060.        cursor: &'a mut TreeCursor<'tree>,
  1061.    ) -> impl Iterator<Item = Node<'tree>> + 'a {
  1062.        let field_id = self.language().field_id_for_name(field_name);
  1063.        self.children_by_field_id(field_id.unwrap_or(0), cursor)
  1064.    }
  1065.  
  1066.    /// Iterate over this node's children with a given field id.
  1067.     ///
  1068.     /// See also [Node::children_by_field_name].
  1069.     pub fn children_by_field_id<'a>(
  1070.        &self,
  1071.        field_id: u16,
  1072.        cursor: &'a mut TreeCursor<'tree>,
  1073.    ) -> impl Iterator<Item = Node<'tree>> + 'a {
  1074.        cursor.reset(*self);
  1075.        cursor.goto_first_child();
  1076.        let mut done = false;
  1077.        iter::from_fn(move || {
  1078.            while !done {
  1079.                while cursor.field_id() != Some(field_id) {
  1080.                    if !cursor.goto_next_sibling() {
  1081.                        return None;
  1082.                    }
  1083.                }
  1084.                let result = cursor.node();
  1085.                if !cursor.goto_next_sibling() {
  1086.                    done = true;
  1087.                }
  1088.                return Some(result);
  1089.            }
  1090.            None
  1091.        })
  1092.    }
  1093.  
  1094.    /// Get this node's immediate parent.
  1095.     #[doc(alias = "ts_node_parent")]
  1096.     pub fn parent(&self) -> Option<Self> {
  1097.         Self::new(unsafe { ffi::ts_node_parent(self.0) })
  1098.     }
  1099.  
  1100.     /// Get this node's next sibling.
  1101.     #[doc(alias = "ts_node_next_sibling")]
  1102.     pub fn next_sibling(&self) -> Option<Self> {
  1103.         Self::new(unsafe { ffi::ts_node_next_sibling(self.0) })
  1104.     }
  1105.  
  1106.     /// Get this node's previous sibling.
  1107.     #[doc(alias = "ts_node_prev_sibling")]
  1108.     pub fn prev_sibling(&self) -> Option<Self> {
  1109.         Self::new(unsafe { ffi::ts_node_prev_sibling(self.0) })
  1110.     }
  1111.  
  1112.     /// Get this node's next named sibling.
  1113.     #[doc(alias = "ts_node_next_named_sibling")]
  1114.     pub fn next_named_sibling(&self) -> Option<Self> {
  1115.         Self::new(unsafe { ffi::ts_node_next_named_sibling(self.0) })
  1116.     }
  1117.  
  1118.     /// Get this node's previous named sibling.
  1119.     #[doc(alias = "ts_node_prev_named_sibling")]
  1120.     pub fn prev_named_sibling(&self) -> Option<Self> {
  1121.         Self::new(unsafe { ffi::ts_node_prev_named_sibling(self.0) })
  1122.     }
  1123.  
  1124.     /// Get the smallest node within this node that spans the given range.
  1125.     #[doc(alias = "ts_node_descendant_for_byte_range")]
  1126.     pub fn descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
  1127.         Self::new(unsafe {
  1128.             ffi::ts_node_descendant_for_byte_range(self.0, start as u32, end as u32)
  1129.         })
  1130.     }
  1131.  
  1132.     /// Get the smallest named node within this node that spans the given range.
  1133.     #[doc(alias = "ts_node_named_descendant_for_byte_range")]
  1134.     pub fn named_descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
  1135.         Self::new(unsafe {
  1136.             ffi::ts_node_named_descendant_for_byte_range(self.0, start as u32, end as u32)
  1137.         })
  1138.     }
  1139.  
  1140.     /// Get the smallest node within this node that spans the given range.
  1141.     #[doc(alias = "ts_node_descendant_for_point_range")]
  1142.     pub fn descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
  1143.         Self::new(unsafe {
  1144.             ffi::ts_node_descendant_for_point_range(self.0, start.into(), end.into())
  1145.         })
  1146.     }
  1147.  
  1148.     /// Get the smallest named node within this node that spans the given range.
  1149.     #[doc(alias = "ts_node_named_descendant_for_point_range")]
  1150.     pub fn named_descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
  1151.         Self::new(unsafe {
  1152.             ffi::ts_node_named_descendant_for_point_range(self.0, start.into(), end.into())
  1153.         })
  1154.     }
  1155.  
  1156.     #[doc(alias = "ts_node_string")]
  1157.     pub fn to_sexp(&self) -> String {
  1158.         let c_string = unsafe { ffi::ts_node_string(self.0) };
  1159.         let result = unsafe { CStr::from_ptr(c_string) }
  1160.             .to_str()
  1161.             .unwrap()
  1162.             .to_string();
  1163.         unsafe { (FREE_FN)(c_string as *mut c_void) };
  1164.         result
  1165.     }
  1166.  
  1167.     pub fn utf8_text<'a>(&self, source: &'a [u8]) -> Result<&'a str, str::Utf8Error> {
  1168.        str::from_utf8(&source[self.start_byte()..self.end_byte()])
  1169.    }
  1170.  
  1171.    pub fn utf16_text<'a>(&self, source: &'a [u16]) -> &'a [u16] {
  1172.         &source.as_ref()[self.start_byte()..self.end_byte()]
  1173.     }
  1174.  
  1175.     /// Create a new [TreeCursor] starting from this node.
  1176.     #[doc(alias = "ts_tree_cursor_new")]
  1177.     pub fn walk(&self) -> TreeCursor<'tree> {
  1178.        TreeCursor(unsafe { ffi::ts_tree_cursor_new(self.0) }, PhantomData)
  1179.    }
  1180.  
  1181.    /// Edit this node to keep it in-sync with source code that has been edited.
  1182.    ///
  1183.    /// This function is only rarely needed. When you edit a syntax tree with the
  1184.    /// [Tree::edit] method, all of the nodes that you retrieve from the tree
  1185.    /// afterward will already reflect the edit. You only need to use [Node::edit]
  1186.    /// when you have a specific [Node] instance that you want to keep and continue
  1187.    /// to use after an edit.
  1188.    #[doc(alias = "ts_node_edit")]
  1189.    pub fn edit(&mut self, edit: &InputEdit) {
  1190.        let edit = edit.into();
  1191.        unsafe { ffi::ts_node_edit(&mut self.0 as *mut ffi::TSNode, &edit) }
  1192.    }
  1193. }
  1194.  
  1195. impl<'a> PartialEq for Node<'a> {
  1196.    fn eq(&self, other: &Self) -> bool {
  1197.        self.0.id == other.0.id
  1198.    }
  1199. }
  1200.  
  1201. impl<'a> Eq for Node<'a> {}
  1202.  
  1203. impl<'a> hash::Hash for Node<'a> {
  1204.    fn hash<H: hash::Hasher>(&self, state: &mut H) {
  1205.        self.0.id.hash(state);
  1206.        self.0.context[0].hash(state);
  1207.        self.0.context[1].hash(state);
  1208.        self.0.context[2].hash(state);
  1209.        self.0.context[3].hash(state);
  1210.    }
  1211. }
  1212.  
  1213. impl<'a> fmt::Debug for Node<'a> {
  1214.    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  1215.        write!(
  1216.            f,
  1217.            "{{Node {} {} - {}}}",
  1218.            self.kind(),
  1219.            self.start_position(),
  1220.            self.end_position()
  1221.        )
  1222.    }
  1223. }
  1224.  
  1225. impl<'a> TreeCursor<'a> {
  1226.    /// Get the tree cursor's current [Node].
  1227.     #[doc(alias = "ts_tree_cursor_current_node")]
  1228.     pub fn node(&self) -> Node<'a> {
  1229.        Node(
  1230.            unsafe { ffi::ts_tree_cursor_current_node(&self.0) },
  1231.            PhantomData,
  1232.        )
  1233.    }
  1234.  
  1235.    /// Get the numerical field id of this tree cursor's current node.
  1236.     ///
  1237.     /// See also [field_name](TreeCursor::field_name).
  1238.     #[doc(alias = "ts_tree_cursor_current_field_id")]
  1239.     pub fn field_id(&self) -> Option<u16> {
  1240.         unsafe {
  1241.             let id = ffi::ts_tree_cursor_current_field_id(&self.0);
  1242.             if id == 0 {
  1243.                 None
  1244.             } else {
  1245.                 Some(id)
  1246.             }
  1247.         }
  1248.     }
  1249.  
  1250.     /// Get the field name of this tree cursor's current node.
  1251.     #[doc(alias = "ts_tree_cursor_current_field_name")]
  1252.     pub fn field_name(&self) -> Option<&'static str> {
  1253.        unsafe {
  1254.            let ptr = ffi::ts_tree_cursor_current_field_name(&self.0);
  1255.            if ptr.is_null() {
  1256.                None
  1257.            } else {
  1258.                Some(CStr::from_ptr(ptr).to_str().unwrap())
  1259.            }
  1260.        }
  1261.    }
  1262.  
  1263.    /// Move this cursor to the first child of its current node.
  1264.    ///
  1265.    /// This returns `true` if the cursor successfully moved, and returns `false`
  1266.    /// if there were no children.
  1267.    #[doc(alias = "ts_tree_cursor_goto_first_child")]
  1268.    pub fn goto_first_child(&mut self) -> bool {
  1269.        return unsafe { ffi::ts_tree_cursor_goto_first_child(&mut self.0) };
  1270.    }
  1271.  
  1272.    /// Move this cursor to the parent of its current node.
  1273.    ///
  1274.    /// This returns `true` if the cursor successfully moved, and returns `false`
  1275.    /// if there was no parent node (the cursor was already on the root node).
  1276.    #[doc(alias = "ts_tree_cursor_goto_parent")]
  1277.    pub fn goto_parent(&mut self) -> bool {
  1278.        return unsafe { ffi::ts_tree_cursor_goto_parent(&mut self.0) };
  1279.    }
  1280.  
  1281.    /// Move this cursor to the next sibling of its current node.
  1282.    ///
  1283.    /// This returns `true` if the cursor successfully moved, and returns `false`
  1284.    /// if there was no next sibling node.
  1285.    #[doc(alias = "ts_tree_cursor_goto_next_sibling")]
  1286.    pub fn goto_next_sibling(&mut self) -> bool {
  1287.        return unsafe { ffi::ts_tree_cursor_goto_next_sibling(&mut self.0) };
  1288.    }
  1289.  
  1290.    /// Move this cursor to the first child of its current node that extends beyond
  1291.    /// the given byte offset.
  1292.    ///
  1293.    /// This returns the index of the child node if one was found, and returns `None`
  1294.    /// if no such child was found.
  1295.    #[doc(alias = "ts_tree_cursor_goto_first_child_for_byte")]
  1296.    pub fn goto_first_child_for_byte(&mut self, index: usize) -> Option<usize> {
  1297.        let result =
  1298.            unsafe { ffi::ts_tree_cursor_goto_first_child_for_byte(&mut self.0, index as u32) };
  1299.        if result < 0 {
  1300.            None
  1301.        } else {
  1302.            Some(result as usize)
  1303.        }
  1304.    }
  1305.  
  1306.    /// Move this cursor to the first child of its current node that extends beyond
  1307.    /// the given byte offset.
  1308.    ///
  1309.    /// This returns the index of the child node if one was found, and returns `None`
  1310.    /// if no such child was found.
  1311.    #[doc(alias = "ts_tree_cursor_goto_first_child_for_point")]
  1312.    pub fn goto_first_child_for_point(&mut self, point: Point) -> Option<usize> {
  1313.        let result =
  1314.            unsafe { ffi::ts_tree_cursor_goto_first_child_for_point(&mut self.0, point.into()) };
  1315.        if result < 0 {
  1316.            None
  1317.        } else {
  1318.            Some(result as usize)
  1319.        }
  1320.    }
  1321.  
  1322.    /// Re-initialize this tree cursor to start at a different node.
  1323.    #[doc(alias = "ts_tree_cursor_reset")]
  1324.    pub fn reset(&mut self, node: Node<'a>) {
  1325.         unsafe { ffi::ts_tree_cursor_reset(&mut self.0, node.0) };
  1326.     }
  1327. }
  1328.  
  1329. impl<'a> Clone for TreeCursor<'a> {
  1330.     fn clone(&self) -> Self {
  1331.         TreeCursor(unsafe { ffi::ts_tree_cursor_copy(&self.0) }, PhantomData)
  1332.     }
  1333. }
  1334.  
  1335. impl<'a> Drop for TreeCursor<'a> {
  1336.     fn drop(&mut self) {
  1337.         unsafe { ffi::ts_tree_cursor_delete(&mut self.0) }
  1338.     }
  1339. }
  1340.  
  1341. impl Query {
  1342.     /// Create a new query from a string containing one or more S-expression
  1343.     /// patterns.
  1344.     ///
  1345.     /// The query is associated with a particular language, and can only be run
  1346.     /// on syntax nodes parsed with that language. References to Queries can be
  1347.     /// shared between multiple threads.
  1348.     pub fn new(language: Language, source: &str) -> Result<Self, QueryError> {
  1349.         let mut error_offset = 0u32;
  1350.         let mut error_type: ffi::TSQueryError = 0;
  1351.         let bytes = source.as_bytes();
  1352.  
  1353.         // Compile the query.
  1354.         let ptr = unsafe {
  1355.             ffi::ts_query_new(
  1356.                 language.0,
  1357.                 bytes.as_ptr() as *const c_char,
  1358.                 bytes.len() as u32,
  1359.                 &mut error_offset as *mut u32,
  1360.                 &mut error_type as *mut ffi::TSQueryError,
  1361.             )
  1362.         };
  1363.  
  1364.         // On failure, build an error based on the error code and offset.
  1365.         if ptr.is_null() {
  1366.             if error_type == ffi::TSQueryError_TSQueryErrorLanguage {
  1367.                 return Err(QueryError {
  1368.                     row: 0,
  1369.                     column: 0,
  1370.                     offset: 0,
  1371.                     message: LanguageError {
  1372.                         version: language.version(),
  1373.                     }
  1374.                     .to_string(),
  1375.                     kind: QueryErrorKind::Language,
  1376.                 });
  1377.             }
  1378.  
  1379.             let offset = error_offset as usize;
  1380.             let mut line_start = 0;
  1381.             let mut row = 0;
  1382.             let mut line_containing_error = None;
  1383.             for line in source.split("\n") {
  1384.                 let line_end = line_start + line.len() + 1;
  1385.                 if line_end > offset {
  1386.                     line_containing_error = Some(line);
  1387.                     break;
  1388.                 }
  1389.                 line_start = line_end;
  1390.                 row += 1;
  1391.             }
  1392.             let column = offset - line_start;
  1393.  
  1394.             let kind;
  1395.             let message;
  1396.             match error_type {
  1397.                 // Error types that report names
  1398.                 ffi::TSQueryError_TSQueryErrorNodeType
  1399.                 | ffi::TSQueryError_TSQueryErrorField
  1400.                 | ffi::TSQueryError_TSQueryErrorCapture => {
  1401.                     let suffix = source.split_at(offset).1;
  1402.                     let end_offset = suffix
  1403.                         .find(|c| !char::is_alphanumeric(c) && c != '_' && c != '-')
  1404.                         .unwrap_or(source.len());
  1405.                     message = suffix.split_at(end_offset).0.to_string();
  1406.                     kind = match error_type {
  1407.                         ffi::TSQueryError_TSQueryErrorNodeType => QueryErrorKind::NodeType,
  1408.                         ffi::TSQueryError_TSQueryErrorField => QueryErrorKind::Field,
  1409.                         ffi::TSQueryError_TSQueryErrorCapture => QueryErrorKind::Capture,
  1410.                         _ => unreachable!(),
  1411.                     };
  1412.                 }
  1413.  
  1414.                 // Error types that report positions
  1415.                 _ => {
  1416.                     message = if let Some(line) = line_containing_error {
  1417.                         line.to_string() + "\n" + &" ".repeat(offset - line_start) + "^"
  1418.                     } else {
  1419.                         "Unexpected EOF".to_string()
  1420.                     };
  1421.                     kind = match error_type {
  1422.                         ffi::TSQueryError_TSQueryErrorStructure => QueryErrorKind::Structure,
  1423.                         _ => QueryErrorKind::Syntax,
  1424.                     };
  1425.                 }
  1426.             };
  1427.  
  1428.             return Err(QueryError {
  1429.                 row,
  1430.                 column,
  1431.                 offset,
  1432.                 kind,
  1433.                 message,
  1434.             });
  1435.         }
  1436.  
  1437.         let string_count = unsafe { ffi::ts_query_string_count(ptr) };
  1438.         let capture_count = unsafe { ffi::ts_query_capture_count(ptr) };
  1439.         let pattern_count = unsafe { ffi::ts_query_pattern_count(ptr) as usize };
  1440.         let mut result = Query {
  1441.             ptr: unsafe { NonNull::new_unchecked(ptr) },
  1442.             capture_names: Vec::with_capacity(capture_count as usize),
  1443.             capture_quantifiers: Vec::with_capacity(pattern_count as usize),
  1444.             text_predicates: Vec::with_capacity(pattern_count),
  1445.             property_predicates: Vec::with_capacity(pattern_count),
  1446.             property_settings: Vec::with_capacity(pattern_count),
  1447.             general_predicates: Vec::with_capacity(pattern_count),
  1448.         };
  1449.  
  1450.         // Build a vector of strings to store the capture names.
  1451.         for i in 0..capture_count {
  1452.             unsafe {
  1453.                 let mut length = 0u32;
  1454.                 let name =
  1455.                     ffi::ts_query_capture_name_for_id(ptr, i, &mut length as *mut u32) as *const u8;
  1456.                 let name = slice::from_raw_parts(name, length as usize);
  1457.                 let name = str::from_utf8_unchecked(name);
  1458.                 result.capture_names.push(name.to_string());
  1459.             }
  1460.         }
  1461.  
  1462.         // Build a vector to store capture qunatifiers.
  1463.         for i in 0..pattern_count {
  1464.             let mut capture_quantifiers = Vec::with_capacity(capture_count as usize);
  1465.             for j in 0..capture_count {
  1466.                 unsafe {
  1467.                     let quantifier = ffi::ts_query_capture_quantifier_for_id(ptr, i as u32, j);
  1468.                     capture_quantifiers.push(quantifier.into());
  1469.                 }
  1470.             }
  1471.             result.capture_quantifiers.push(capture_quantifiers);
  1472.         }
  1473.  
  1474.         // Build a vector of strings to represent literal values used in predicates.
  1475.         let string_values = (0..string_count)
  1476.             .map(|i| unsafe {
  1477.                 let mut length = 0u32;
  1478.                 let value =
  1479.                     ffi::ts_query_string_value_for_id(ptr, i as u32, &mut length as *mut u32)
  1480.                         as *const u8;
  1481.                 let value = slice::from_raw_parts(value, length as usize);
  1482.                 let value = str::from_utf8_unchecked(value);
  1483.                 value.to_string()
  1484.             })
  1485.             .collect::<Vec<_>>();
  1486.  
  1487.         // Build a vector of predicates for each pattern.
  1488.         for i in 0..pattern_count {
  1489.             let predicate_steps = unsafe {
  1490.                 let mut length = 0u32;
  1491.                 let raw_predicates =
  1492.                     ffi::ts_query_predicates_for_pattern(ptr, i as u32, &mut length as *mut u32);
  1493.                 if length > 0 {
  1494.                     slice::from_raw_parts(raw_predicates, length as usize)
  1495.                 } else {
  1496.                     &[]
  1497.                 }
  1498.             };
  1499.  
  1500.             let byte_offset = unsafe { ffi::ts_query_start_byte_for_pattern(ptr, i as u32) };
  1501.             let row = source
  1502.                 .char_indices()
  1503.                 .take_while(|(i, _)| *i < byte_offset as usize)
  1504.                 .filter(|(_, c)| *c == '\n')
  1505.                 .count();
  1506.  
  1507.             let type_done = ffi::TSQueryPredicateStepType_TSQueryPredicateStepTypeDone;
  1508.             let type_capture = ffi::TSQueryPredicateStepType_TSQueryPredicateStepTypeCapture;
  1509.             let type_string = ffi::TSQueryPredicateStepType_TSQueryPredicateStepTypeString;
  1510.  
  1511.             let mut text_predicates = Vec::new();
  1512.             let mut property_predicates = Vec::new();
  1513.             let mut property_settings = Vec::new();
  1514.             let mut general_predicates = Vec::new();
  1515.             for p in predicate_steps.split(|s| s.type_ == type_done) {
  1516.                 if p.is_empty() {
  1517.                     continue;
  1518.                 }
  1519.  
  1520.                 if p[0].type_ != type_string {
  1521.                     return Err(predicate_error(
  1522.                         row,
  1523.                         format!(
  1524.                             "Expected predicate to start with a function name. Got @{}.",
  1525.                             result.capture_names[p[0].value_id as usize],
  1526.                         ),
  1527.                     ));
  1528.                 }
  1529.  
  1530.                 // Build a predicate for each of the known predicate function names.
  1531.                 let operator_name = &string_values[p[0].value_id as usize];
  1532.                 match operator_name.as_str() {
  1533.                     "eq?" | "not-eq?" => {
  1534.                         if p.len() != 3 {
  1535.                             return Err(predicate_error(
  1536.                                 row,
  1537.                                 format!(
  1538.                                 "Wrong number of arguments to #eq? predicate. Expected 2, got {}.",
  1539.                                 p.len() - 1
  1540.                             ),
  1541.                             ));
  1542.                         }
  1543.                         if p[1].type_ != type_capture {
  1544.                             return Err(predicate_error(row, format!(
  1545.                                 "First argument to #eq? predicate must be a capture name. Got literal \"{}\".",
  1546.                                 string_values[p[1].value_id as usize],
  1547.                             )));
  1548.                         }
  1549.  
  1550.                         let is_positive = operator_name == "eq?";
  1551.                         text_predicates.push(if p[2].type_ == type_capture {
  1552.                             TextPredicate::CaptureEqCapture(
  1553.                                 p[1].value_id,
  1554.                                 p[2].value_id,
  1555.                                 is_positive,
  1556.                             )
  1557.                         } else {
  1558.                             TextPredicate::CaptureEqString(
  1559.                                 p[1].value_id,
  1560.                                 string_values[p[2].value_id as usize].clone(),
  1561.                                 is_positive,
  1562.                             )
  1563.                         });
  1564.                     }
  1565.  
  1566.                     "match?" | "not-match?" => {
  1567.                         if p.len() != 3 {
  1568.                             return Err(predicate_error(row, format!(
  1569.                                 "Wrong number of arguments to #match? predicate. Expected 2, got {}.",
  1570.                                 p.len() - 1
  1571.                             )));
  1572.                         }
  1573.                         if p[1].type_ != type_capture {
  1574.                             return Err(predicate_error(row, format!(
  1575.                                 "First argument to #match? predicate must be a capture name. Got literal \"{}\".",
  1576.                                 string_values[p[1].value_id as usize],
  1577.                             )));
  1578.                         }
  1579.                         if p[2].type_ == type_capture {
  1580.                             return Err(predicate_error(row, format!(
  1581.                                 "Second argument to #match? predicate must be a literal. Got capture @{}.",
  1582.                                 result.capture_names[p[2].value_id as usize],
  1583.                             )));
  1584.                         }
  1585.  
  1586.                         let is_positive = operator_name == "match?";
  1587.                         let regex = &string_values[p[2].value_id as usize];
  1588.                         text_predicates.push(TextPredicate::CaptureMatchString(
  1589.                             p[1].value_id,
  1590.                             regex::bytes::Regex::new(regex).map_err(|_| {
  1591.                                 predicate_error(row, format!("Invalid regex '{}'", regex))
  1592.                             })?,
  1593.                             is_positive,
  1594.                         ));
  1595.                     }
  1596.  
  1597.                     "set!" => property_settings.push(Self::parse_property(
  1598.                         row,
  1599.                         &operator_name,
  1600.                         &result.capture_names,
  1601.                         &string_values,
  1602.                         &p[1..],
  1603.                     )?),
  1604.  
  1605.                     "is?" | "is-not?" => property_predicates.push((
  1606.                         Self::parse_property(
  1607.                             row,
  1608.                             &operator_name,
  1609.                             &result.capture_names,
  1610.                             &string_values,
  1611.                             &p[1..],
  1612.                         )?,
  1613.                         operator_name == "is?",
  1614.                     )),
  1615.  
  1616.                     _ => general_predicates.push(QueryPredicate {
  1617.                         operator: operator_name.clone().into_boxed_str(),
  1618.                         args: p[1..]
  1619.                             .iter()
  1620.                             .map(|a| {
  1621.                                 if a.type_ == type_capture {
  1622.                                     QueryPredicateArg::Capture(a.value_id)
  1623.                                 } else {
  1624.                                     QueryPredicateArg::String(
  1625.                                         string_values[a.value_id as usize].clone().into_boxed_str(),
  1626.                                     )
  1627.                                 }
  1628.                             })
  1629.                             .collect(),
  1630.                     }),
  1631.                 }
  1632.             }
  1633.  
  1634.             result
  1635.                 .text_predicates
  1636.                 .push(text_predicates.into_boxed_slice());
  1637.             result
  1638.                 .property_predicates
  1639.                 .push(property_predicates.into_boxed_slice());
  1640.             result
  1641.                 .property_settings
  1642.                 .push(property_settings.into_boxed_slice());
  1643.             result
  1644.                 .general_predicates
  1645.                 .push(general_predicates.into_boxed_slice());
  1646.         }
  1647.         Ok(result)
  1648.     }
  1649.  
  1650.     /// Get the byte offset where the given pattern starts in the query's source.
  1651.     #[doc(alias = "ts_query_start_byte_for_pattern")]
  1652.     pub fn start_byte_for_pattern(&self, pattern_index: usize) -> usize {
  1653.         if pattern_index >= self.text_predicates.len() {
  1654.             panic!(
  1655.                 "Pattern index is {} but the pattern count is {}",
  1656.                 pattern_index,
  1657.                 self.text_predicates.len(),
  1658.             );
  1659.         }
  1660.         unsafe {
  1661.             ffi::ts_query_start_byte_for_pattern(self.ptr.as_ptr(), pattern_index as u32) as usize
  1662.         }
  1663.     }
  1664.  
  1665.     /// Get the number of patterns in the query.
  1666.     #[doc(alias = "ts_query_pattern_count")]
  1667.     pub fn pattern_count(&self) -> usize {
  1668.         unsafe { ffi::ts_query_pattern_count(self.ptr.as_ptr()) as usize }
  1669.     }
  1670.  
  1671.     /// Get the names of the captures used in the query.
  1672.     pub fn capture_names(&self) -> &[String] {
  1673.         &self.capture_names
  1674.     }
  1675.  
  1676.     /// Get the quantifiers of the captures used in the query.
  1677.     pub fn capture_quantifiers(&self, index: usize) -> &[CaptureQuantifier] {
  1678.         &self.capture_quantifiers[index]
  1679.     }
  1680.  
  1681.     /// Get the index for a given capture name.
  1682.     pub fn capture_index_for_name(&self, name: &str) -> Option<u32> {
  1683.         self.capture_names
  1684.             .iter()
  1685.             .position(|n| n == name)
  1686.             .map(|ix| ix as u32)
  1687.     }
  1688.  
  1689.     /// Get the properties that are checked for the given pattern index.
  1690.     ///
  1691.     /// This includes predicates with the operators `is?` and `is-not?`.
  1692.     pub fn property_predicates(&self, index: usize) -> &[(QueryProperty, bool)] {
  1693.         &self.property_predicates[index]
  1694.     }
  1695.  
  1696.     /// Get the properties that are set for the given pattern index.
  1697.     ///
  1698.     /// This includes predicates with the operator `set!`.
  1699.     pub fn property_settings(&self, index: usize) -> &[QueryProperty] {
  1700.         &self.property_settings[index]
  1701.     }
  1702.  
  1703.     /// Get the other user-defined predicates associated with the given index.
  1704.     ///
  1705.     /// This includes predicate with operators other than:
  1706.     /// * `match?`
  1707.     /// * `eq?` and `not-eq?`
  1708.     /// * `is?` and `is-not?`
  1709.     /// * `set!`
  1710.     pub fn general_predicates(&self, index: usize) -> &[QueryPredicate] {
  1711.         &self.general_predicates[index]
  1712.     }
  1713.  
  1714.     /// Disable a certain capture within a query.
  1715.     ///
  1716.     /// This prevents the capture from being returned in matches, and also avoids any
  1717.     /// resource usage associated with recording the capture.
  1718.     #[doc(alias = "ts_query_disable_capture")]
  1719.     pub fn disable_capture(&mut self, name: &str) {
  1720.         unsafe {
  1721.             ffi::ts_query_disable_capture(
  1722.                 self.ptr.as_ptr(),
  1723.                 name.as_bytes().as_ptr() as *const c_char,
  1724.                 name.len() as u32,
  1725.             );
  1726.         }
  1727.     }
  1728.  
  1729.     /// Disable a certain pattern within a query.
  1730.     ///
  1731.     /// This prevents the pattern from matching, and also avoids any resource usage
  1732.     /// associated with the pattern.
  1733.     #[doc(alias = "ts_query_disable_pattern")]
  1734.     pub fn disable_pattern(&mut self, index: usize) {
  1735.         unsafe { ffi::ts_query_disable_pattern(self.ptr.as_ptr(), index as u32) }
  1736.     }
  1737.  
  1738.     /// Check if a given pattern within a query has a single root node.
  1739.     #[doc(alias = "ts_query_is_pattern_rooted")]
  1740.     pub fn is_pattern_rooted(&self, index: usize) -> bool {
  1741.         unsafe { ffi::ts_query_is_pattern_rooted(self.ptr.as_ptr(), index as u32) }
  1742.     }
  1743.  
  1744.     /// Check if a given pattern within a query has a single root node.
  1745.     #[doc(alias = "ts_query_is_pattern_non_local")]
  1746.     pub fn is_pattern_non_local(&self, index: usize) -> bool {
  1747.         unsafe { ffi::ts_query_is_pattern_non_local(self.ptr.as_ptr(), index as u32) }
  1748.     }
  1749.  
  1750.     /// Check if a given step in a query is 'definite'.
  1751.     ///
  1752.     /// A query step is 'definite' if its parent pattern will be guaranteed to match
  1753.     /// successfully once it reaches the step.
  1754.     #[doc(alias = "ts_query_is_pattern_guaranteed_at_step")]
  1755.     pub fn is_pattern_guaranteed_at_step(&self, byte_offset: usize) -> bool {
  1756.         unsafe {
  1757.             ffi::ts_query_is_pattern_guaranteed_at_step(self.ptr.as_ptr(), byte_offset as u32)
  1758.         }
  1759.     }
  1760.  
  1761.     fn parse_property(
  1762.         row: usize,
  1763.         function_name: &str,
  1764.         capture_names: &[String],
  1765.         string_values: &[String],
  1766.         args: &[ffi::TSQueryPredicateStep],
  1767.     ) -> Result<QueryProperty, QueryError> {
  1768.         if args.len() == 0 || args.len() > 3 {
  1769.             return Err(predicate_error(
  1770.                 row,
  1771.                 format!(
  1772.                     "Wrong number of arguments to {} predicate. Expected 1 to 3, got {}.",
  1773.                     function_name,
  1774.                     args.len(),
  1775.                 ),
  1776.             ));
  1777.         }
  1778.  
  1779.         let mut capture_id = None;
  1780.         let mut key = None;
  1781.         let mut value = None;
  1782.  
  1783.         for arg in args {
  1784.             if arg.type_ == ffi::TSQueryPredicateStepType_TSQueryPredicateStepTypeCapture {
  1785.                 if capture_id.is_some() {
  1786.                     return Err(predicate_error(
  1787.                         row,
  1788.                         format!(
  1789.                             "Invalid arguments to {} predicate. Unexpected second capture name @{}",
  1790.                             function_name, capture_names[arg.value_id as usize]
  1791.                         ),
  1792.                     ));
  1793.                 }
  1794.                 capture_id = Some(arg.value_id as usize);
  1795.             } else if key.is_none() {
  1796.                 key = Some(&string_values[arg.value_id as usize]);
  1797.             } else if value.is_none() {
  1798.                 value = Some(string_values[arg.value_id as usize].as_str());
  1799.             } else {
  1800.                 return Err(predicate_error(
  1801.                     row,
  1802.                     format!(
  1803.                         "Invalid arguments to {} predicate. Unexpected third argument @{}",
  1804.                         function_name, string_values[arg.value_id as usize]
  1805.                     ),
  1806.                 ));
  1807.             }
  1808.         }
  1809.  
  1810.         if let Some(key) = key {
  1811.             Ok(QueryProperty::new(key, value, capture_id))
  1812.         } else {
  1813.             return Err(predicate_error(
  1814.                 row,
  1815.                 format!(
  1816.                     "Invalid arguments to {} predicate. Missing key argument",
  1817.                     function_name,
  1818.                 ),
  1819.             ));
  1820.         }
  1821.     }
  1822. }
  1823.  
  1824. impl QueryCursor {
  1825.     /// Create a new cursor for executing a given query.
  1826.     ///
  1827.     /// The cursor stores the state that is needed to iteratively search for matches.
  1828.     #[doc(alias = "ts_query_cursor_new")]
  1829.     pub fn new() -> Self {
  1830.         QueryCursor {
  1831.             ptr: unsafe { NonNull::new_unchecked(ffi::ts_query_cursor_new()) },
  1832.         }
  1833.     }
  1834.  
  1835.     /// Return the maximum number of in-progress matches for this cursor.
  1836.     #[doc(alias = "ts_query_cursor_match_limit")]
  1837.     pub fn match_limit(&self) -> u32 {
  1838.         unsafe { ffi::ts_query_cursor_match_limit(self.ptr.as_ptr()) }
  1839.     }
  1840.  
  1841.     /// Set the maximum number of in-progress matches for this cursor.  The limit must be > 0 and
  1842.     /// <= 65536.
  1843.     #[doc(alias = "ts_query_cursor_set_match_limit")]
  1844.     pub fn set_match_limit(&mut self, limit: u32) {
  1845.         unsafe {
  1846.             ffi::ts_query_cursor_set_match_limit(self.ptr.as_ptr(), limit);
  1847.         }
  1848.     }
  1849.  
  1850.     /// Check if, on its last execution, this cursor exceeded its maximum number of
  1851.     /// in-progress matches.
  1852.     #[doc(alias = "ts_query_cursor_did_exceed_match_limit")]
  1853.     pub fn did_exceed_match_limit(&self) -> bool {
  1854.         unsafe { ffi::ts_query_cursor_did_exceed_match_limit(self.ptr.as_ptr()) }
  1855.     }
  1856.  
  1857.     /// Iterate over all of the matches in the order that they were found.
  1858.     ///
  1859.     /// Each match contains the index of the pattern that matched, and a list of captures.
  1860.     /// Because multiple patterns can match the same set of nodes, one match may contain
  1861.     /// captures that appear *before* some of the captures from a previous match.
  1862.     #[doc(alias = "ts_query_cursor_exec")]
  1863.     pub fn matches<'a, 'tree: 'a, T: TextProvider<'a> + 'a>(
  1864.        &'a mut self,
  1865.         query: &'a Query,
  1866.        node: Node<'tree>,
  1867.         text_provider: T,
  1868.     ) -> QueryMatches<'a, 'tree, T> {
  1869.         let ptr = self.ptr.as_ptr();
  1870.         unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
  1871.         QueryMatches {
  1872.             ptr,
  1873.             query,
  1874.             text_provider,
  1875.             buffer1: Default::default(),
  1876.             buffer2: Default::default(),
  1877.             _tree: PhantomData,
  1878.         }
  1879.     }
  1880.  
  1881.     /// Iterate over all of the individual captures in the order that they appear.
  1882.     ///
  1883.     /// This is useful if you don't care about which pattern matched, and just want a single,
  1884.     /// ordered sequence of captures.
  1885.     #[doc(alias = "ts_query_cursor_exec")]
  1886.     pub fn captures<'a, 'tree: 'a, T: TextProvider<'a> + 'a>(
  1887.        &'a mut self,
  1888.         query: &'a Query,
  1889.        node: Node<'tree>,
  1890.         text_provider: T,
  1891.     ) -> QueryCaptures<'a, 'tree, T> {
  1892.         let ptr = self.ptr.as_ptr();
  1893.         unsafe { ffi::ts_query_cursor_exec(self.ptr.as_ptr(), query.ptr.as_ptr(), node.0) };
  1894.         QueryCaptures {
  1895.             ptr,
  1896.             query,
  1897.             text_provider,
  1898.             buffer1: Default::default(),
  1899.             buffer2: Default::default(),
  1900.             _tree: PhantomData,
  1901.         }
  1902.     }
  1903.  
  1904.     /// Set the range in which the query will be executed, in terms of byte offsets.
  1905.     #[doc(alias = "ts_query_cursor_set_byte_range")]
  1906.     pub fn set_byte_range(&mut self, range: ops::Range<usize>) -> &mut Self {
  1907.         unsafe {
  1908.             ffi::ts_query_cursor_set_byte_range(
  1909.                 self.ptr.as_ptr(),
  1910.                 range.start as u32,
  1911.                 range.end as u32,
  1912.             );
  1913.         }
  1914.         self
  1915.     }
  1916.  
  1917.     /// Set the range in which the query will be executed, in terms of rows and columns.
  1918.     #[doc(alias = "ts_query_cursor_set_point_range")]
  1919.     pub fn set_point_range(&mut self, range: ops::Range<Point>) -> &mut Self {
  1920.         unsafe {
  1921.             ffi::ts_query_cursor_set_point_range(
  1922.                 self.ptr.as_ptr(),
  1923.                 range.start.into(),
  1924.                 range.end.into(),
  1925.             );
  1926.         }
  1927.         self
  1928.     }
  1929. }
  1930.  
  1931. impl<'a, 'tree> QueryMatch<'a, 'tree> {
  1932.     pub fn id(&self) -> u32 {
  1933.         self.id
  1934.     }
  1935.  
  1936.     #[doc(alias = "ts_query_cursor_remove_match")]
  1937.     pub fn remove(self) {
  1938.         unsafe { ffi::ts_query_cursor_remove_match(self.cursor, self.id) }
  1939.     }
  1940.  
  1941.     pub fn nodes_for_capture_index(
  1942.         &self,
  1943.         capture_ix: u32,
  1944.     ) -> impl Iterator<Item = Node<'tree>> + '_ {
  1945.         self.captures.iter().filter_map(move |capture| {
  1946.             if capture.index == capture_ix {
  1947.                 Some(capture.node)
  1948.             } else {
  1949.                 None
  1950.             }
  1951.         })
  1952.     }
  1953.  
  1954.     fn new(m: ffi::TSQueryMatch, cursor: *mut ffi::TSQueryCursor) -> Self {
  1955.         QueryMatch {
  1956.             cursor,
  1957.             id: m.id,
  1958.             pattern_index: m.pattern_index as usize,
  1959.             captures: if m.capture_count > 0 {
  1960.                 unsafe {
  1961.                     slice::from_raw_parts(
  1962.                         m.captures as *const QueryCapture<'tree>,
  1963.                        m.capture_count as usize,
  1964.                    )
  1965.                }
  1966.            } else {
  1967.                &[]
  1968.            },
  1969.        }
  1970.    }
  1971.  
  1972.    fn satisfies_text_predicates(
  1973.        &self,
  1974.        query: &Query,
  1975.        buffer1: &mut Vec<u8>,
  1976.        buffer2: &mut Vec<u8>,
  1977.        text_provider: &mut impl TextProvider<'a>,
  1978.     ) -> bool {
  1979.         fn get_text<'a, 'b: 'a, I: Iterator<Item = &'b [u8]>>(
  1980.             buffer: &'a mut Vec<u8>,
  1981.            mut chunks: I,
  1982.        ) -> &'a [u8] {
  1983.             let first_chunk = chunks.next().unwrap_or(&[]);
  1984.             if let Some(next_chunk) = chunks.next() {
  1985.                 buffer.clear();
  1986.                 buffer.extend_from_slice(first_chunk);
  1987.                 buffer.extend_from_slice(next_chunk);
  1988.                 for chunk in chunks {
  1989.                     buffer.extend_from_slice(chunk);
  1990.                 }
  1991.                 buffer.as_slice()
  1992.             } else {
  1993.                 first_chunk
  1994.             }
  1995.         }
  1996.  
  1997.         query.text_predicates[self.pattern_index]
  1998.             .iter()
  1999.             .all(|predicate| match predicate {
  2000.                 TextPredicate::CaptureEqCapture(i, j, is_positive) => {
  2001.                     let node1 = self.nodes_for_capture_index(*i).next();
  2002.                     let node2 = self.nodes_for_capture_index(*j).next();
  2003.                     match (node1, node2) {
  2004.                         (Some(node1), Some(node2)) => {
  2005.                             let text1 = get_text(buffer1, text_provider.text(node1));
  2006.                             let text2 = get_text(buffer2, text_provider.text(node2));
  2007.                             (text1 == text2) == *is_positive
  2008.                         }
  2009.                         _ => true,
  2010.                     }
  2011.                 }
  2012.                 TextPredicate::CaptureEqString(i, s, is_positive) => {
  2013.                     let node = self.nodes_for_capture_index(*i).next();
  2014.                     match node {
  2015.                         Some(node) => {
  2016.                             let text = get_text(buffer1, text_provider.text(node));
  2017.                             (text == s.as_bytes()) == *is_positive
  2018.                         }
  2019.                         None => true,
  2020.                     }
  2021.                 }
  2022.                 TextPredicate::CaptureMatchString(i, r, is_positive) => {
  2023.                     let node = self.nodes_for_capture_index(*i).next();
  2024.                     match node {
  2025.                         Some(node) => {
  2026.                             let text = get_text(buffer1, text_provider.text(node));
  2027.                             r.is_match(text) == *is_positive
  2028.                         }
  2029.                         None => true,
  2030.                     }
  2031.                 }
  2032.             })
  2033.     }
  2034. }
  2035.  
  2036. impl QueryProperty {
  2037.     pub fn new(key: &str, value: Option<&str>, capture_id: Option<usize>) -> Self {
  2038.         QueryProperty {
  2039.             capture_id,
  2040.             key: key.to_string().into_boxed_str(),
  2041.             value: value.map(|s| s.to_string().into_boxed_str()),
  2042.         }
  2043.     }
  2044. }
  2045.  
  2046. impl<'a, 'tree, T: TextProvider<'a>> Iterator for QueryMatches<'a, 'tree, T> {
  2047.    type Item = QueryMatch<'a, 'tree>;
  2048.  
  2049.    fn next(&mut self) -> Option<Self::Item> {
  2050.        unsafe {
  2051.            loop {
  2052.                let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
  2053.                if ffi::ts_query_cursor_next_match(self.ptr, m.as_mut_ptr()) {
  2054.                    let result = QueryMatch::new(m.assume_init(), self.ptr);
  2055.                    if result.satisfies_text_predicates(
  2056.                        self.query,
  2057.                        &mut self.buffer1,
  2058.                        &mut self.buffer2,
  2059.                        &mut self.text_provider,
  2060.                    ) {
  2061.                        return Some(result);
  2062.                    }
  2063.                } else {
  2064.                    return None;
  2065.                }
  2066.            }
  2067.        }
  2068.    }
  2069. }
  2070.  
  2071. impl<'a, 'tree, T: TextProvider<'a>> Iterator for QueryCaptures<'a, 'tree, T> {
  2072.     type Item = (QueryMatch<'a, 'tree>, usize);
  2073.  
  2074.     fn next(&mut self) -> Option<Self::Item> {
  2075.         unsafe {
  2076.             loop {
  2077.                 let mut capture_index = 0u32;
  2078.                 let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
  2079.                 if ffi::ts_query_cursor_next_capture(
  2080.                     self.ptr,
  2081.                     m.as_mut_ptr(),
  2082.                     &mut capture_index as *mut u32,
  2083.                 ) {
  2084.                     let result = QueryMatch::new(m.assume_init(), self.ptr);
  2085.                     if result.satisfies_text_predicates(
  2086.                         self.query,
  2087.                         &mut self.buffer1,
  2088.                         &mut self.buffer2,
  2089.                         &mut self.text_provider,
  2090.                     ) {
  2091.                         return Some((result, capture_index as usize));
  2092.                     } else {
  2093.                         result.remove();
  2094.                     }
  2095.                 } else {
  2096.                     return None;
  2097.                 }
  2098.             }
  2099.         }
  2100.     }
  2101. }
  2102.  
  2103. impl<'a, 'tree, T: TextProvider<'a>> QueryMatches<'a, 'tree, T> {
  2104.    #[doc(alias = "ts_query_cursor_set_byte_range")]
  2105.    pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
  2106.        unsafe {
  2107.            ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
  2108.        }
  2109.    }
  2110.  
  2111.    #[doc(alias = "ts_query_cursor_set_point_range")]
  2112.    pub fn set_point_range(&mut self, range: ops::Range<Point>) {
  2113.        unsafe {
  2114.            ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
  2115.        }
  2116.    }
  2117. }
  2118.  
  2119. impl<'a, 'tree, T: TextProvider<'a>> QueryCaptures<'a, 'tree, T> {
  2120.     #[doc(alias = "ts_query_cursor_set_byte_range")]
  2121.     pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
  2122.         unsafe {
  2123.             ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
  2124.         }
  2125.     }
  2126.  
  2127.     #[doc(alias = "ts_query_cursor_set_point_range")]
  2128.     pub fn set_point_range(&mut self, range: ops::Range<Point>) {
  2129.         unsafe {
  2130.             ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
  2131.         }
  2132.     }
  2133. }
  2134.  
  2135. impl<'cursor, 'tree> fmt::Debug for QueryMatch<'cursor, 'tree> {
  2136.     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  2137.         write!(
  2138.             f,
  2139.             "QueryMatch {{ id: {}, pattern_index: {}, captures: {:?} }}",
  2140.             self.id, self.pattern_index, self.captures
  2141.         )
  2142.     }
  2143. }
  2144.  
  2145. impl<'a, F, I> TextProvider<'a> for F
  2146. where
  2147.     F: FnMut(Node) -> I,
  2148.     I: Iterator<Item = &'a [u8]> + 'a,
  2149. {
  2150.     type I = I;
  2151.  
  2152.     fn text(&mut self, node: Node) -> Self::I {
  2153.         (self)(node)
  2154.     }
  2155. }
  2156.  
  2157. impl<'a> TextProvider<'a> for &'a [u8] {
  2158.    type I = iter::Once<&'a [u8]>;
  2159.  
  2160.     fn text(&mut self, node: Node) -> Self::I {
  2161.         iter::once(&self[node.byte_range()])
  2162.     }
  2163. }
  2164.  
  2165. impl PartialEq for Query {
  2166.     fn eq(&self, other: &Self) -> bool {
  2167.         self.ptr == other.ptr
  2168.     }
  2169. }
  2170.  
  2171. impl Drop for Query {
  2172.     fn drop(&mut self) {
  2173.         unsafe { ffi::ts_query_delete(self.ptr.as_ptr()) }
  2174.     }
  2175. }
  2176.  
  2177. impl Drop for QueryCursor {
  2178.     fn drop(&mut self) {
  2179.         unsafe { ffi::ts_query_cursor_delete(self.ptr.as_ptr()) }
  2180.     }
  2181. }
  2182.  
  2183. impl Point {
  2184.     pub fn new(row: usize, column: usize) -> Self {
  2185.         Point { row, column }
  2186.     }
  2187. }
  2188.  
  2189. impl fmt::Display for Point {
  2190.     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  2191.         write!(f, "({}, {})", self.row, self.column)
  2192.     }
  2193. }
  2194.  
  2195. impl Into<ffi::TSPoint> for Point {
  2196.     fn into(self) -> ffi::TSPoint {
  2197.         ffi::TSPoint {
  2198.             row: self.row as u32,
  2199.             column: self.column as u32,
  2200.         }
  2201.     }
  2202. }
  2203.  
  2204. impl From<ffi::TSPoint> for Point {
  2205.     fn from(point: ffi::TSPoint) -> Self {
  2206.         Self {
  2207.             row: point.row as usize,
  2208.             column: point.column as usize,
  2209.         }
  2210.     }
  2211. }
  2212.  
  2213. impl Into<ffi::TSRange> for Range {
  2214.     fn into(self) -> ffi::TSRange {
  2215.         ffi::TSRange {
  2216.             start_byte: self.start_byte as u32,
  2217.             end_byte: self.end_byte as u32,
  2218.             start_point: self.start_point.into(),
  2219.             end_point: self.end_point.into(),
  2220.         }
  2221.     }
  2222. }
  2223.  
  2224. impl From<ffi::TSRange> for Range {
  2225.     fn from(range: ffi::TSRange) -> Self {
  2226.         Self {
  2227.             start_byte: range.start_byte as usize,
  2228.             end_byte: range.end_byte as usize,
  2229.             start_point: range.start_point.into(),
  2230.             end_point: range.end_point.into(),
  2231.         }
  2232.     }
  2233. }
  2234.  
  2235. impl<'a> Into<ffi::TSInputEdit> for &'a InputEdit {
  2236.     fn into(self) -> ffi::TSInputEdit {
  2237.         ffi::TSInputEdit {
  2238.             start_byte: self.start_byte as u32,
  2239.             old_end_byte: self.old_end_byte as u32,
  2240.             new_end_byte: self.new_end_byte as u32,
  2241.             start_point: self.start_position.into(),
  2242.             old_end_point: self.old_end_position.into(),
  2243.             new_end_point: self.new_end_position.into(),
  2244.         }
  2245.     }
  2246. }
  2247.  
  2248. impl<'a> LossyUtf8<'a> {
  2249.     pub fn new(bytes: &'a [u8]) -> Self {
  2250.        LossyUtf8 {
  2251.            bytes,
  2252.            in_replacement: false,
  2253.        }
  2254.    }
  2255. }
  2256.  
  2257. impl<'a> Iterator for LossyUtf8<'a> {
  2258.    type Item = &'a str;
  2259.  
  2260.     fn next(&mut self) -> Option<&'a str> {
  2261.        if self.bytes.is_empty() {
  2262.            return None;
  2263.        }
  2264.        if self.in_replacement {
  2265.            self.in_replacement = false;
  2266.            return Some("\u{fffd}");
  2267.        }
  2268.        match std::str::from_utf8(self.bytes) {
  2269.            Ok(valid) => {
  2270.                self.bytes = &[];
  2271.                Some(valid)
  2272.            }
  2273.            Err(error) => {
  2274.                if let Some(error_len) = error.error_len() {
  2275.                    let error_start = error.valid_up_to();
  2276.                    if error_start > 0 {
  2277.                        let result =
  2278.                            unsafe { std::str::from_utf8_unchecked(&self.bytes[..error_start]) };
  2279.                        self.bytes = &self.bytes[(error_start + error_len)..];
  2280.                        self.in_replacement = true;
  2281.                        Some(result)
  2282.                    } else {
  2283.                        self.bytes = &self.bytes[error_len..];
  2284.                        Some("\u{fffd}")
  2285.                    }
  2286.                } else {
  2287.                    None
  2288.                }
  2289.            }
  2290.        }
  2291.    }
  2292. }
  2293.  
  2294. fn predicate_error(row: usize, message: String) -> QueryError {
  2295.    QueryError {
  2296.        kind: QueryErrorKind::Predicate,
  2297.        row,
  2298.        column: 0,
  2299.        offset: 0,
  2300.        message,
  2301.    }
  2302. }
  2303.  
  2304. impl fmt::Display for IncludedRangesError {
  2305.    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  2306.        write!(f, "Incorrect range by index: {}", self.0)
  2307.    }
  2308. }
  2309.  
  2310. impl fmt::Display for LanguageError {
  2311.    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  2312.        write!(
  2313.            f,
  2314.            "Incompatible language version {}. Expected minimum {}, maximum {}",
  2315.            self.version, MIN_COMPATIBLE_LANGUAGE_VERSION, LANGUAGE_VERSION,
  2316.        )
  2317.    }
  2318. }
  2319.  
  2320. impl fmt::Display for QueryError {
  2321.    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  2322.        let msg = match self.kind {
  2323.            QueryErrorKind::Field => "Invalid field name ",
  2324.            QueryErrorKind::NodeType => "Invalid node type ",
  2325.            QueryErrorKind::Capture => "Invalid capture name ",
  2326.            QueryErrorKind::Predicate => "Invalid predicate: ",
  2327.            QueryErrorKind::Structure => "Impossible pattern:\n",
  2328.            QueryErrorKind::Syntax => "Invalid syntax:\n",
  2329.            QueryErrorKind::Language => "",
  2330.        };
  2331.        if msg.len() > 0 {
  2332.            write!(
  2333.                f,
  2334.                "Query error at {}:{}. {}{}",
  2335.                self.row + 1,
  2336.                self.column + 1,
  2337.                msg,
  2338.                self.message
  2339.            )
  2340.        } else {
  2341.            write!(f, "{}", self.message)
  2342.        }
  2343.    }
  2344. }
  2345.  
  2346. extern "C" {
  2347.    fn free(ptr: *mut c_void);
  2348. }
  2349.  
  2350. static mut FREE_FN: unsafe extern "C" fn(ptr: *mut c_void) = free;
  2351.  
  2352. #[doc(alias = "ts_set_allocator")]
  2353. pub unsafe fn set_allocator(
  2354.    new_malloc: Option<unsafe extern "C" fn(usize) -> *mut c_void>,
  2355.    new_calloc: Option<unsafe extern "C" fn(usize, usize) -> *mut c_void>,
  2356.    new_realloc: Option<unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void>,
  2357.    new_free: Option<unsafe extern "C" fn(*mut c_void)>,
  2358. ) {
  2359.    FREE_FN = new_free.unwrap_or(free);
  2360.    ffi::ts_set_allocator(new_malloc, new_calloc, new_realloc, new_free);
  2361. }
  2362.  
  2363. impl error::Error for IncludedRangesError {}
  2364. impl error::Error for LanguageError {}
  2365. impl error::Error for QueryError {}
  2366.  
  2367. unsafe impl Send for Language {}
  2368. unsafe impl Send for Parser {}
  2369. unsafe impl Send for Query {}
  2370. unsafe impl Send for QueryCursor {}
  2371. unsafe impl Send for Tree {}
  2372. unsafe impl Sync for Language {}
  2373. unsafe impl Sync for Parser {}
  2374. unsafe impl Sync for Query {}
  2375. unsafe impl Sync for QueryCursor {}
  2376. unsafe impl Sync for Tree {}
  2377.  
Advertisement
Add Comment
Please, Sign In to add comment