Debian Codegraph @

Xtree-house/bindings/src/query.rs

raw symbols SCIP
1 use std::fmt::{self, Display};
2 use std::ops::Range;
3 use std::ptr::NonNull;
4 use std::{slice, str};
5
6 use crate::query::predicate::TextPredicate;
7 pub use crate::query::predicate::{InvalidPredicateError, Predicate};
8 use crate::Grammar;
9
10 mod predicate;
11 mod property;
12
13 #[derive(Debug)]
14 pub enum UserPredicate<'a> {
15 IsPropertySet {
16 negate: bool,
17 key: &'a str,
18 val: Option<&'a str>,
19 },
20 SetProperty {
21 key: &'a str,
22 val: Option<&'a str>,
23 },
24 Other(Predicate<'a>),
25 }
26
27 impl Display for UserPredicate<'_> {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 match *self {
30 UserPredicate::IsPropertySet { negate, key, val } => {
31 let predicate = if negate { "is-not?" } else { "is?" };
32 let spacer = if val.is_some() { " " } else { "" };
33 write!(f, " (#{predicate} {key}{spacer}{})", val.unwrap_or(""))
34 }
35 UserPredicate::SetProperty { key, val } => {
36 let spacer = if val.is_some() { " " } else { "" };
37 write!(f, "(#set! {key}{spacer}{})", val.unwrap_or(""))
38 }
39 UserPredicate::Other(ref predicate) => {
40 write!(f, "#{}", predicate.name())
41 }
42 }
43 }
44 }
45
46 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
47 pub struct Pattern(pub(crate) u32);
48
49 impl Pattern {
50 pub const SENTINEL: Pattern = Pattern(u32::MAX);
51
52 pub fn idx(&self) -> usize {
53 self.0 as usize
54 }
55 }
56
57 pub enum QueryData {}
58
59 #[derive(Debug)]
60 pub(super) struct PatternData {
61 text_predicates: Range<u32>,
62 }
63
64 #[derive(Debug)]
65 pub struct Query {
66 pub(crate) raw: NonNull<QueryData>,
67 num_captures: u32,
68 num_strings: u32,
69 text_predicates: Vec<TextPredicate>,
70 patterns: Box<[PatternData]>,
71 }
72
73 unsafe impl Send for Query {}
74 unsafe impl Sync for Query {}
75
76 impl Query {
77 /// Create a new query from a string containing one or more S-expression
78 /// patterns.
79 ///
80 /// The query is associated with a particular grammar, and can only be run
81 /// on syntax nodes parsed with that grammar. References to Queries can be
82 /// shared between multiple threads.
83 pub fn new(
84 grammar: Grammar,
85 source: &str,
86 mut custom_predicate: impl FnMut(Pattern, UserPredicate) -> Result<(), InvalidPredicateError>,
87 ) -> Result<Self, ParseError> {
88 assert!(
89 source.len() <= i32::MAX as usize,
90 "TreeSitter queries must be smaller then 2 GiB (is {})",
91 source.len() as f64 / 1024.0 / 1024.0 / 1024.0
92 );
93 let mut error_offset = 0u32;
94 let mut error_kind = RawQueryError::None;
95 let bytes = source.as_bytes();
96
97 // Compile the query.
98 let ptr = unsafe {
99 ts_query_new(
100 grammar,
101 bytes.as_ptr(),
102 bytes.len() as u32,
103 &mut error_offset,
104 &mut error_kind,
105 )
106 };
107
108 let Some(raw) = ptr else {
109 let offset = error_offset as usize;
110 let error_word = || {
111 source[offset..]
112 .chars()
113 .take_while(|&c| c.is_alphanumeric() || matches!(c, '_' | '-'))
114 .collect()
115 };
116 let err = match error_kind {
117 RawQueryError::NodeType => {
118 let node: String = error_word();
119 ParseError::InvalidNodeType {
120 location: ParserErrorLocation::new(source, offset, node.chars().count()),
121 node,
122 }
123 }
124 RawQueryError::Field => {
125 let field = error_word();
126 ParseError::InvalidFieldName {
127 location: ParserErrorLocation::new(source, offset, field.chars().count()),
128 field,
129 }
130 }
131 RawQueryError::Capture => {
132 let capture = error_word();
133 ParseError::InvalidCaptureName {
134 location: ParserErrorLocation::new(source, offset, capture.chars().count()),
135 capture,
136 }
137 }
138 RawQueryError::Syntax => {
139 ParseError::SyntaxError(ParserErrorLocation::new(source, offset, 0))
140 }
141 RawQueryError::Structure => {
142 ParseError::ImpossiblePattern(ParserErrorLocation::new(source, offset, 0))
143 }
144 RawQueryError::None => {
145 unreachable!("tree-sitter returned a null pointer but did not set an error")
146 }
147 RawQueryError::Language => unreachable!("should be handled at grammar load"),
148 };
149 return Err(err);
150 };
151
152 // I am not going to bother with safety comments here, all of these are
153 // safe as long as TS is not buggy because raw is a properly constructed query
154 let num_captures = unsafe { ts_query_capture_count(raw) };
155 let num_strings = unsafe { ts_query_string_count(raw) };
156 let num_patterns = unsafe { ts_query_pattern_count(raw) };
157
158 let mut query = Query {
159 raw,
160 num_captures,
161 num_strings,
162 text_predicates: Vec::new(),
163 patterns: Box::default(),
164 };
165 let patterns: Result<_, ParseError> = (0..num_patterns)
166 .map(|pattern| {
167 query
168 .parse_pattern_predicates(Pattern(pattern), &mut custom_predicate)
169 .map_err(|err| {
170 let pattern_start =
171 unsafe { ts_query_start_byte_for_pattern(query.raw, pattern) as usize };
172 match err {
173 InvalidPredicateError::UnknownPredicate { name } => {
174 let offset = source[pattern_start..]
175 .find(&*name)
176 .expect("predicate name is a substring of the query text")
177 + pattern_start
178 // Subtract a byte for b'#'.
179 - 1;
180 ParseError::InvalidPredicate {
181 message: format!("unknown predicate #{name}"),
182 location: ParserErrorLocation::new(
183 source,
184 offset,
185 // Add one char for the '#'.
186 name.chars().count() + 1,
187 ),
188 }
189 }
190 InvalidPredicateError::UnknownProperty { property } => {
191 // TODO: this is naive. We should ensure that it is within a
192 // `#set!` or `#is(-not)?`.
193 let offset = source[pattern_start..]
194 .find(&*property)
195 .expect("property name is a substring of the query text")
196 + pattern_start;
197 ParseError::InvalidPredicate {
198 message: format!("unknown property '{property}'"),
199 location: ParserErrorLocation::new(
200 source,
201 offset,
202 property.chars().count(),
203 ),
204 }
205 }
206 InvalidPredicateError::Other { msg } => ParseError::InvalidPredicate {
207 message: msg.into(),
208 location: ParserErrorLocation::new(source, pattern_start, 0),
209 },
210 }
211 })
212 })
213 .collect();
214 query.patterns = patterns?;
215 Ok(query)
216 }
217
218 #[inline]
219 fn get_string(&self, str: QueryStr) -> &str {
220 let value_id = str.0;
221 // need an assertions because the ts c api does not do bounds check
222 assert!(value_id < self.num_strings, "invalid value index");
223 unsafe {
224 let mut len = 0;
225 let ptr = ts_query_string_value_for_id(self.raw, value_id, &mut len);
226 let data = slice::from_raw_parts(ptr, len as usize);
227 // safety: we only allow passing valid str(ings) as arguments to query::new
228 // name is always a substring of that. Treesitter does proper utf8 segmentation
229 // so any substrings it produces are codepoint aligned and therefore valid utf8
230 str::from_utf8_unchecked(data)
231 }
232 }
233
234 #[inline]
235 pub fn capture_name(&self, capture_idx: Capture) -> &str {
236 let capture_idx = capture_idx.0;
237 // need an assertions because the ts c api does not do bounds check
238 assert!(capture_idx < self.num_captures, "invalid capture index");
239 let mut length = 0;
240 unsafe {
241 let ptr = ts_query_capture_name_for_id(self.raw, capture_idx, &mut length);
242 let name = slice::from_raw_parts(ptr, length as usize);
243 // safety: we only allow passing valid str(ings) as arguments to query::new
244 // name is always a substring of that. Treesitter does proper utf8 segmentation
245 // so any substrings it produces are codepoint aligned and therefore valid utf8
246 str::from_utf8_unchecked(name)
247 }
248 }
249
250 #[inline]
251 pub fn captures(&self) -> impl ExactSizeIterator<Item = (Capture, &str)> {
252 (0..self.num_captures).map(|cap| (Capture(cap), self.capture_name(Capture(cap))))
253 }
254
255 #[inline]
256 pub fn num_captures(&self) -> u32 {
257 self.num_captures
258 }
259
260 #[inline]
261 pub fn get_capture(&self, capture_name: &str) -> Option<Capture> {
262 for capture in 0..self.num_captures {
263 if capture_name == self.capture_name(Capture(capture)) {
264 return Some(Capture(capture));
265 }
266 }
267 None
268 }
269
270 pub(crate) fn pattern_text_predicates(&self, pattern_idx: u16) -> &[TextPredicate] {
271 let range = self.patterns[pattern_idx as usize].text_predicates.clone();
272 &self.text_predicates[range.start as usize..range.end as usize]
273 }
274
275 /// Get the byte offset where the given pattern starts in the query's
276 /// source.
277 #[doc(alias = "ts_query_start_byte_for_pattern")]
278 #[must_use]
279 pub fn start_byte_for_pattern(&self, pattern: Pattern) -> usize {
280 assert!(
281 pattern.0 < self.patterns.len() as u32,
282 "Pattern index is {pattern:?} but the pattern count is {}",
283 self.patterns.len(),
284 );
285 unsafe { ts_query_start_byte_for_pattern(self.raw, pattern.0) as usize }
286 }
287
288 /// Get the number of patterns in the query.
289 #[must_use]
290 pub fn pattern_count(&self) -> usize {
291 unsafe { ts_query_pattern_count(self.raw) as usize }
292 }
293 /// Get the number of patterns in the query.
294 #[must_use]
295 pub fn patterns(&self) -> impl ExactSizeIterator<Item = Pattern> {
296 (0..self.pattern_count() as u32).map(Pattern)
297 }
298
299 /// Disable a certain capture within a query.
300 ///
301 /// This prevents the capture from being returned in matches, and also avoids
302 /// any resource usage associated with recording the capture. Currently, there
303 /// is no way to undo this.
304 pub fn disable_capture(&mut self, name: &str) {
305 let bytes = name.as_bytes();
306 unsafe {
307 ts_query_disable_capture(self.raw, bytes.as_ptr(), bytes.len() as u32);
308 }
309 }
310
311 /// Disable a certain pattern within a query.
312 ///
313 /// This prevents the pattern from matching and removes most of the overhead
314 /// associated with the pattern. Currently, there is no way to undo this.
315 pub fn disable_pattern(&mut self, pattern: Pattern) {
316 unsafe {
317 ts_query_disable_pattern(self.raw, pattern.0);
318 }
319 }
320 }
321
322 impl Drop for Query {
323 fn drop(&mut self) {
324 unsafe { ts_query_delete(self.raw) }
325 }
326 }
327
328 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
329 #[repr(transparent)]
330 pub struct Capture(u32);
331
332 impl Capture {
333 pub fn name(self, query: &Query) -> &str {
334 query.capture_name(self)
335 }
336 pub fn idx(self) -> usize {
337 self.0 as usize
338 }
339 }
340
341 /// A reference to a string stored in a query
342 #[derive(Clone, Copy, Debug)]
343 pub struct QueryStr(u32);
344
345 impl QueryStr {
346 pub fn get(self, query: &Query) -> &str {
347 query.get_string(self)
348 }
349 }
350
351 #[derive(Debug, PartialEq, Eq)]
352 pub struct ParserErrorLocation {
353 /// at which line the error occurred
354 pub line: u32,
355 /// at which codepoints/columns the errors starts in the line
356 pub column: u32,
357 /// how many codepoints/columns the error takes up
358 pub len: u32,
359 line_content: String,
360 line_before: Option<String>,
361 line_after: Option<String>,
362 }
363
364 impl ParserErrorLocation {
365 pub fn new(source: &str, start: usize, len: usize) -> ParserErrorLocation {
366 let mut line = 0;
367 let mut column = 0;
368 let mut line_content = String::new();
369 let mut line_before = None;
370 let mut line_after = None;
371
372 let mut byte_offset = 0;
373 for (this_line_no, this_line) in source.split('\n').enumerate() {
374 let line_start = byte_offset;
375 let line_end = line_start + this_line.len();
376 if line_start <= start && start <= line_end {
377 line = this_line_no;
378 line_content = this_line
379 .strip_suffix('\r')
380 .unwrap_or(this_line)
381 .to_string();
382 column = source[line_start..start].chars().count();
383 line_before = source[..line_start]
384 .lines()
385 .next_back()
386 .filter(|s| !s.is_empty())
387 .map(ToOwned::to_owned);
388 line_after = source
389 .get(line_end + 1..)
390 .and_then(|rest| rest.lines().next())
391 .filter(|s| !s.is_empty())
392 .map(ToOwned::to_owned);
393 break;
394 }
395 byte_offset += this_line.len() + 1;
396 }
397
398 ParserErrorLocation {
399 line: line as u32,
400 column: column as u32,
401 len: len as u32,
402 line_content: line_content.to_owned(),
403 line_before,
404 line_after,
405 }
406 }
407 }
408
409 impl Display for ParserErrorLocation {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 writeln!(f, " --> {}:{}", self.line + 1, self.column + 1)?;
412
413 let max_line_number = if self.line_after.is_some() {
414 self.line + 2
415 } else {
416 self.line + 1
417 };
418 let line_number_column_len = max_line_number.to_string().len();
419 let line = (self.line + 1).to_string();
420 let prefix = format!(" {:width$} |", "", width = line_number_column_len);
421
422 writeln!(f, "{prefix}")?;
423 if let Some(before) = self.line_before.as_ref() {
424 writeln!(f, " {} | {}", self.line, before)?;
425 }
426 writeln!(f, " {line} | {}", self.line_content)?;
427 writeln!(
428 f,
429 "{prefix}{:width$} {:^<len$}",
430 "",
431 "^",
432 width = self.column as usize,
433 len = self.len as usize
434 )?;
435 if let Some(after) = self.line_after.as_ref() {
436 writeln!(f, " {} | {}", self.line + 2, after)?;
437 }
438 writeln!(f, "{prefix}")
439 }
440 }
441
442 #[derive(thiserror::Error, Debug, PartialEq, Eq)]
443 pub enum ParseError {
444 #[error("unexpected EOF")]
445 UnexpectedEof,
446 #[error("invalid query syntax\n{0}")]
447 SyntaxError(ParserErrorLocation),
448 #[error("invalid node type {node:?}\n{location}")]
449 InvalidNodeType {
450 node: String,
451 location: ParserErrorLocation,
452 },
453 #[error("invalid field name {field:?}\n{location}")]
454 InvalidFieldName {
455 field: String,
456 location: ParserErrorLocation,
457 },
458 #[error("invalid capture name {capture:?}\n{location}")]
459 InvalidCaptureName {
460 capture: String,
461 location: ParserErrorLocation,
462 },
463 #[error("{message}\n{location}")]
464 InvalidPredicate {
465 message: String,
466 location: ParserErrorLocation,
467 },
468 #[error("impossible pattern\n{0}")]
469 ImpossiblePattern(ParserErrorLocation),
470 }
471
472 #[repr(C)]
473 // warns about never being constructed but it's constructed by C code
474 // and wrwitten into a mutable reference
475 #[allow(dead_code)]
476 enum RawQueryError {
477 None = 0,
478 Syntax = 1,
479 NodeType = 2,
480 Field = 3,
481 Capture = 4,
482 Structure = 5,
483 Language = 6,
484 }
485
486 extern "C" {
487 /// Create a new query from a string containing one or more S-expression
488 /// patterns. The query is associated with a particular language, and can
489 /// only be run on syntax nodes parsed with that language. If all of the
490 /// given patterns are valid, this returns a `TSQuery`. If a pattern is
491 /// invalid, this returns `NULL`, and provides two pieces of information
492 /// about the problem: 1. The byte offset of the error is written to
493 /// the `error_offset` parameter. 2. The type of error is written to the
494 /// `error_type` parameter.
495 fn ts_query_new(
496 grammar: Grammar,
497 source: *const u8,
498 source_len: u32,
499 error_offset: &mut u32,
500 error_type: &mut RawQueryError,
501 ) -> Option<NonNull<QueryData>>;
502
503 /// Delete a query, freeing all of the memory that it used.
504 fn ts_query_delete(query: NonNull<QueryData>);
505
506 /// Get the number of patterns, captures, or string literals in the query.
507 fn ts_query_pattern_count(query: NonNull<QueryData>) -> u32;
508 fn ts_query_capture_count(query: NonNull<QueryData>) -> u32;
509 fn ts_query_string_count(query: NonNull<QueryData>) -> u32;
510
511 /// Get the byte offset where the given pattern starts in the query's
512 /// source. This can be useful when combining queries by concatenating their
513 /// source code strings.
514 fn ts_query_start_byte_for_pattern(query: NonNull<QueryData>, pattern_index: u32) -> u32;
515
516 // fn ts_query_is_pattern_rooted(query: NonNull<QueryData>, pattern_index: u32) -> bool;
517 // fn ts_query_is_pattern_non_local(query: NonNull<QueryData>, pattern_index: u32) -> bool;
518 // fn ts_query_is_pattern_guaranteed_at_step(query: NonNull<QueryData>, byte_offset: u32) -> bool;
519 /// Get the name and length of one of the query's captures, or one of the
520 /// query's string literals. Each capture and string is associated with a
521 /// numeric id based on the order that it appeared in the query's source.
522 fn ts_query_capture_name_for_id(
523 query: NonNull<QueryData>,
524 index: u32,
525 length: &mut u32,
526 ) -> *const u8;
527
528 fn ts_query_string_value_for_id(
529 self_: NonNull<QueryData>,
530 index: u32,
531 length: &mut u32,
532 ) -> *const u8;
533
534 /// Disable a certain capture within a query.
535 ///
536 /// This prevents the capture from being returned in matches, and also avoids
537 /// any resource usage associated with recording the capture. Currently, there
538 /// is no way to undo this.
539 fn ts_query_disable_capture(self_: NonNull<QueryData>, name: *const u8, length: u32);
540 /// Disable a certain pattern within a query.
541 ///
542 /// This prevents the pattern from matching and removes most of the overhead
543 /// associated with the pattern. Currently, there is no way to undo this.
544 fn ts_query_disable_pattern(self_: NonNull<QueryData>, pattern_index: u32);
545 }