forked from tree-sitter/tree-sitter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
3048 lines (2748 loc) · 106 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![doc = include_str!("./README.md")]
pub mod ffi;
mod util;
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
#[cfg(windows)]
use std::os::windows::io::AsRawHandle;
use std::{
char, error,
ffi::CStr,
fmt::{self, Write},
hash, iter,
marker::PhantomData,
mem::MaybeUninit,
num::NonZeroU16,
ops::{self, Deref},
os::raw::{c_char, c_void},
ptr::{self, NonNull},
slice, str,
sync::atomic::AtomicUsize,
u16,
};
#[cfg(feature = "wasm")]
mod wasm_language;
#[cfg(feature = "wasm")]
pub use wasm_language::*;
/// The latest ABI version that is supported by the current version of the
/// library.
///
/// When Languages are generated by the Tree-sitter CLI, they are
/// assigned an ABI version number that corresponds to the current CLI version.
/// The Tree-sitter library is generally backwards-compatible with languages
/// generated using older CLI versions, but is not forwards-compatible.
#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;
/// The earliest ABI version that is supported by the current version of the
/// library.
#[doc(alias = "TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION")]
pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize =
ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION as usize;
pub const ARRAY_HEADER: &str = include_str!("../src/array.h");
pub const PARSER_HEADER: &str = include_str!("../src/parser.h");
/// An opaque object that defines how to parse a particular language. The code for each
/// `Language` is generated by the Tree-sitter CLI.
#[doc(alias = "TSLanguage")]
#[derive(Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Language(*const ffi::TSLanguage);
pub struct LanguageRef<'a>(*const ffi::TSLanguage, PhantomData<&'a ()>);
/// A tree that represents the syntactic structure of a source code file.
#[doc(alias = "TSTree")]
pub struct Tree(NonNull<ffi::TSTree>);
/// A position in a multi-line text document, in terms of rows and columns.
///
/// Rows and columns are zero-based.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Point {
pub row: usize,
pub column: usize,
}
/// A range of positions in a multi-line text document, both in terms of bytes and of
/// rows and columns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Range {
pub start_byte: usize,
pub end_byte: usize,
pub start_point: Point,
pub end_point: Point,
}
/// A summary of a change to a text document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InputEdit {
pub start_byte: usize,
pub old_end_byte: usize,
pub new_end_byte: usize,
pub start_position: Point,
pub old_end_position: Point,
pub new_end_position: Point,
}
/// A single node within a syntax [`Tree`].
#[doc(alias = "TSNode")]
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>);
/// A stateful object that this is used to produce a [`Tree`] based on some source code.
#[doc(alias = "TSParser")]
pub struct Parser(NonNull<ffi::TSParser>);
/// A stateful object that is used to look up symbols valid in a specific parse state
#[doc(alias = "TSLookaheadIterator")]
pub struct LookaheadIterator(NonNull<ffi::TSLookaheadIterator>);
struct LookaheadNamesIterator<'a>(&'a mut LookaheadIterator);
/// A type of log message.
#[derive(Debug, PartialEq, Eq)]
pub enum LogType {
Parse,
Lex,
}
type FieldId = NonZeroU16;
/// A callback that receives log messages during parser.
type Logger<'a> = Box<dyn FnMut(LogType, &str) + 'a>;
/// A stateful object for walking a syntax [`Tree`] efficiently.
#[doc(alias = "TSTreeCursor")]
pub struct TreeCursor<'cursor>(ffi::TSTreeCursor, PhantomData<&'cursor ()>);
/// A set of patterns that match nodes in a syntax tree.
#[doc(alias = "TSQuery")]
#[derive(Debug)]
#[allow(clippy::type_complexity)]
pub struct Query {
ptr: NonNull<ffi::TSQuery>,
capture_names: Box<[&'static str]>,
capture_quantifiers: Box<[Box<[CaptureQuantifier]>]>,
text_predicates: Box<[Box<[TextPredicateCapture]>]>,
property_settings: Box<[Box<[QueryProperty]>]>,
property_predicates: Box<[Box<[(QueryProperty, bool)]>]>,
general_predicates: Box<[Box<[QueryPredicate]>]>,
}
/// A quantifier for captures
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum CaptureQuantifier {
Zero,
ZeroOrOne,
ZeroOrMore,
One,
OneOrMore,
}
impl From<ffi::TSQuantifier> for CaptureQuantifier {
fn from(value: ffi::TSQuantifier) -> Self {
match value {
ffi::TSQuantifierZero => Self::Zero,
ffi::TSQuantifierZeroOrOne => Self::ZeroOrOne,
ffi::TSQuantifierZeroOrMore => Self::ZeroOrMore,
ffi::TSQuantifierOne => Self::One,
ffi::TSQuantifierOneOrMore => Self::OneOrMore,
_ => panic!("Unrecognized quantifier: {value}"),
}
}
}
/// A stateful object for executing a [`Query`] on a syntax [`Tree`].
#[doc(alias = "TSQueryCursor")]
pub struct QueryCursor {
ptr: NonNull<ffi::TSQueryCursor>,
}
/// A key-value pair associated with a particular pattern in a [`Query`].
#[derive(Debug, PartialEq, Eq)]
pub struct QueryProperty {
pub key: Box<str>,
pub value: Option<Box<str>>,
pub capture_id: Option<usize>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum QueryPredicateArg {
Capture(u32),
String(Box<str>),
}
/// A key-value pair associated with a particular pattern in a [`Query`].
#[derive(Debug, PartialEq, Eq)]
pub struct QueryPredicate {
pub operator: Box<str>,
pub args: Box<[QueryPredicateArg]>,
}
/// A match of a [`Query`] to a particular set of [`Node`]s.
pub struct QueryMatch<'cursor, 'tree> {
pub pattern_index: usize,
pub captures: &'cursor [QueryCapture<'tree>],
id: u32,
cursor: *mut ffi::TSQueryCursor,
}
/// A sequence of [`QueryMatch`]es associated with a given [`QueryCursor`].
pub struct QueryMatches<'query, 'cursor, T: TextProvider<I>, I: AsRef<[u8]>> {
ptr: *mut ffi::TSQueryCursor,
query: &'query Query,
text_provider: T,
buffer1: Vec<u8>,
buffer2: Vec<u8>,
_phantom: PhantomData<(&'cursor (), I)>,
}
/// A sequence of [`QueryCapture`]s associated with a given [`QueryCursor`].
pub struct QueryCaptures<'query, 'cursor, T: TextProvider<I>, I: AsRef<[u8]>> {
ptr: *mut ffi::TSQueryCursor,
query: &'query Query,
text_provider: T,
buffer1: Vec<u8>,
buffer2: Vec<u8>,
_phantom: PhantomData<(&'cursor (), I)>,
}
pub trait TextProvider<I>
where
I: AsRef<[u8]>,
{
type I: Iterator<Item = I>;
fn text(&mut self, node: Node) -> Self::I;
}
/// A particular [`Node`] that has been captured with a particular name within a [`Query`].
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct QueryCapture<'tree> {
pub node: Node<'tree>,
pub index: u32,
}
/// An error that occurred when trying to assign an incompatible [`Language`] to a [`Parser`].
#[derive(Debug, PartialEq, Eq)]
pub struct LanguageError {
version: usize,
}
/// An error that occurred in [`Parser::set_included_ranges`].
#[derive(Debug, PartialEq, Eq)]
pub struct IncludedRangesError(pub usize);
/// An error that occurred when trying to create a [`Query`].
#[derive(Debug, PartialEq, Eq)]
pub struct QueryError {
pub row: usize,
pub column: usize,
pub offset: usize,
pub message: String,
pub kind: QueryErrorKind,
}
#[derive(Debug, PartialEq, Eq)]
pub enum QueryErrorKind {
Syntax,
NodeType,
Field,
Capture,
Predicate,
Structure,
Language,
}
#[derive(Debug)]
/// The first item is the capture index
/// The next is capture specific, depending on what item is expected
/// The first bool is if the capture is positive
/// The last item is a bool signifying whether or not it's meant to match
/// any or all captures
enum TextPredicateCapture {
EqString(u32, Box<str>, bool, bool),
EqCapture(u32, u32, bool, bool),
MatchString(u32, regex::bytes::Regex, bool, bool),
AnyString(u32, Box<[Box<str>]>, bool),
}
// TODO: Remove this struct at at some point. If `core::str::lossy::Utf8Lossy`
// is ever stabilized.
pub struct LossyUtf8<'a> {
bytes: &'a [u8],
in_replacement: bool,
}
impl Language {
/// Get the ABI version number that indicates which version of the Tree-sitter CLI
/// that was used to generate this [`Language`].
#[doc(alias = "ts_language_version")]
#[must_use]
pub fn version(&self) -> usize {
unsafe { ffi::ts_language_version(self.0) as usize }
}
/// Get the number of distinct node types in this language.
#[doc(alias = "ts_language_symbol_count")]
#[must_use]
pub fn node_kind_count(&self) -> usize {
unsafe { ffi::ts_language_symbol_count(self.0) as usize }
}
/// Get the number of valid states in this language.
#[doc(alias = "ts_language_state_count")]
#[must_use]
pub fn parse_state_count(&self) -> usize {
unsafe { ffi::ts_language_state_count(self.0) as usize }
}
/// Get the name of the node kind for the given numerical id.
#[doc(alias = "ts_language_symbol_name")]
#[must_use]
pub fn node_kind_for_id(&self, id: u16) -> Option<&'static str> {
let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
(!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
}
/// Get the numeric id for the given node kind.
#[doc(alias = "ts_language_symbol_for_name")]
#[must_use]
pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
unsafe {
ffi::ts_language_symbol_for_name(
self.0,
kind.as_bytes().as_ptr().cast::<c_char>(),
kind.len() as u32,
named,
)
}
}
/// Check if the node type for the given numerical id is named (as opposed
/// to an anonymous node type).
#[must_use]
pub fn node_kind_is_named(&self, id: u16) -> bool {
unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeRegular }
}
#[doc(alias = "ts_language_symbol_type")]
#[must_use]
pub fn node_kind_is_visible(&self, id: u16) -> bool {
unsafe { ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolTypeAnonymous }
}
/// Get the number of distinct field names in this language.
#[doc(alias = "ts_language_field_count")]
#[must_use]
pub fn field_count(&self) -> usize {
unsafe { ffi::ts_language_field_count(self.0) as usize }
}
/// Get the field names for the given numerical id.
#[doc(alias = "ts_language_field_name_for_id")]
#[must_use]
pub fn field_name_for_id(&self, field_id: u16) -> Option<&'static str> {
let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
(!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
}
/// Get the numerical id for the given field name.
#[doc(alias = "ts_language_field_id_for_name")]
#[must_use]
pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId> {
let field_name = field_name.as_ref();
let id = unsafe {
ffi::ts_language_field_id_for_name(
self.0,
field_name.as_ptr().cast::<c_char>(),
field_name.len() as u32,
)
};
FieldId::new(id)
}
/// Get the next parse state. Combine this with
/// [`lookahead_iterator`](Language::lookahead_iterator) to
/// generate completion suggestions or valid symbols in error nodes.
///
/// Example:
/// ```
/// let state = language.next_state(node.parse_state(), node.grammar_id());
/// ```
#[doc(alias = "ts_language_next_state")]
#[must_use]
pub fn next_state(&self, state: u16, id: u16) -> u16 {
unsafe { ffi::ts_language_next_state(self.0, state, id) }
}
/// Create a new lookahead iterator for this language and parse state.
///
/// This returns `None` if state is invalid for this language.
///
/// Iterating [`LookaheadIterator`] will yield valid symbols in the given
/// parse state. Newly created lookahead iterators will return the `ERROR`
/// symbol from [`LookaheadIterator::current_symbol`].
///
/// Lookahead iterators can be useful to generate suggestions and improve
/// syntax error diagnostics. To get symbols valid in an ERROR node, use the
/// lookahead iterator on its first leaf node state. For `MISSING` nodes, a
/// lookahead iterator created on the previous non-extra leaf node may be
/// appropriate.
#[doc(alias = "ts_lookahead_iterator_new")]
#[must_use]
pub fn lookahead_iterator(&self, state: u16) -> Option<LookaheadIterator> {
let ptr = unsafe { ffi::ts_lookahead_iterator_new(self.0, state) };
(!ptr.is_null()).then(|| unsafe { LookaheadIterator::from_raw(ptr) })
}
}
impl Clone for Language {
fn clone(&self) -> Self {
unsafe { Self(ffi::ts_language_copy(self.0)) }
}
}
impl Drop for Language {
fn drop(&mut self) {
unsafe { ffi::ts_language_delete(self.0) }
}
}
impl<'a> Deref for LanguageRef<'a> {
type Target = Language;
fn deref(&self) -> &Self::Target {
unsafe { &*(std::ptr::addr_of!(self.0).cast::<Language>()) }
}
}
impl Default for Parser {
fn default() -> Self {
Self::new()
}
}
impl Parser {
/// Create a new parser.
#[doc(alias = "ts_parser_new")]
#[must_use]
pub fn new() -> Self {
unsafe {
let parser = ffi::ts_parser_new();
Self(NonNull::new_unchecked(parser))
}
}
/// Set the language that the parser should use for parsing.
///
/// Returns a Result indicating whether or not the language was successfully
/// assigned. True means assignment succeeded. False means there was a version
/// mismatch: the language was generated with an incompatible version of the
/// Tree-sitter CLI. Check the language's version using [`Language::version`]
/// and compare it to this library's [`LANGUAGE_VERSION`](LANGUAGE_VERSION) and
/// [`MIN_COMPATIBLE_LANGUAGE_VERSION`](MIN_COMPATIBLE_LANGUAGE_VERSION) constants.
#[doc(alias = "ts_parser_set_language")]
pub fn set_language(&mut self, language: &Language) -> Result<(), LanguageError> {
let version = language.version();
if (MIN_COMPATIBLE_LANGUAGE_VERSION..=LANGUAGE_VERSION).contains(&version) {
unsafe {
ffi::ts_parser_set_language(self.0.as_ptr(), language.0);
}
Ok(())
} else {
Err(LanguageError { version })
}
}
/// Get the parser's current language.
#[doc(alias = "ts_parser_language")]
#[must_use]
pub fn language(&self) -> Option<Language> {
let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
(!ptr.is_null()).then(|| Language(ptr))
}
/// Get the parser's current logger.
#[doc(alias = "ts_parser_logger")]
#[must_use]
pub fn logger(&self) -> Option<&Logger> {
let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
unsafe { logger.payload.cast::<Logger>().as_ref() }
}
/// Set the logging callback that a parser should use during parsing.
#[doc(alias = "ts_parser_set_logger")]
pub fn set_logger(&mut self, logger: Option<Logger>) {
let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
if !prev_logger.payload.is_null() {
drop(unsafe { Box::from_raw(prev_logger.payload.cast::<Logger>()) });
}
let c_logger;
if let Some(logger) = logger {
let container = Box::new(logger);
unsafe extern "C" fn log(
payload: *mut c_void,
c_log_type: ffi::TSLogType,
c_message: *const c_char,
) {
let callback = payload.cast::<Logger>().as_mut().unwrap();
if let Ok(message) = CStr::from_ptr(c_message).to_str() {
let log_type = if c_log_type == ffi::TSLogTypeParse {
LogType::Parse
} else {
LogType::Lex
};
callback(log_type, message);
}
}
let raw_container = Box::into_raw(container);
c_logger = ffi::TSLogger {
payload: raw_container.cast::<c_void>(),
log: Some(log),
};
} else {
c_logger = ffi::TSLogger {
payload: ptr::null_mut(),
log: None,
};
}
unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
}
/// Set the destination to which the parser should write debugging graphs
/// during parsing. The graphs are formatted in the DOT language. You may want
/// to pipe these graphs directly to a `dot(1)` process in order to generate
/// SVG output.
#[doc(alias = "ts_parser_print_dot_graphs")]
pub fn print_dot_graphs(
&mut self,
#[cfg(not(windows))] file: &impl AsRawFd,
#[cfg(windows)] file: &impl AsRawHandle,
) {
#[cfg(not(windows))]
{
let fd = file.as_raw_fd();
unsafe {
ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(fd));
}
}
#[cfg(windows)]
{
let handle = file.as_raw_handle();
unsafe {
ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(handle));
}
}
}
/// Stop the parser from printing debugging graphs while parsing.
#[doc(alias = "ts_parser_print_dot_graphs")]
pub fn stop_printing_dot_graphs(&mut self) {
unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
}
/// Parse a slice of UTF8 text.
///
/// # Arguments:
/// * `text` The UTF8-encoded text to parse.
/// * `old_tree` A previous syntax tree parsed from the same document.
/// If the text of the document has changed since `old_tree` was
/// created, then you must edit `old_tree` to match the new text using
/// [`Tree::edit`].
///
/// Returns a [`Tree`] if parsing succeeded, or `None` if:
/// * The parser has not yet had a language assigned with [`Parser::set_language`]
/// * The timeout set with [`Parser::set_timeout_micros`] expired
/// * The cancellation flag set with [`Parser::set_cancellation_flag`] was flipped
#[doc(alias = "ts_parser_parse")]
pub fn parse(&mut self, text: impl AsRef<[u8]>, old_tree: Option<&Tree>) -> Option<Tree> {
let bytes = text.as_ref();
let len = bytes.len();
self.parse_with(
&mut |i, _| (i < len).then(|| &bytes[i..]).unwrap_or_default(),
old_tree,
)
}
/// Parse a slice of UTF16 text.
///
/// # Arguments:
/// * `text` The UTF16-encoded text to parse.
/// * `old_tree` A previous syntax tree parsed from the same document.
/// If the text of the document has changed since `old_tree` was
/// created, then you must edit `old_tree` to match the new text using
/// [`Tree::edit`].
pub fn parse_utf16(
&mut self,
input: impl AsRef<[u16]>,
old_tree: Option<&Tree>,
) -> Option<Tree> {
let code_points = input.as_ref();
let len = code_points.len();
self.parse_utf16_with(
&mut |i, _| (i < len).then(|| &code_points[i..]).unwrap_or_default(),
old_tree,
)
}
/// Parse UTF8 text provided in chunks by a callback.
///
/// # Arguments:
/// * `callback` A function that takes a byte offset and position and
/// returns a slice of UTF8-encoded text starting at that byte offset
/// and position. The slices can be of any length. If the given position
/// is at the end of the text, the callback should return an empty slice.
/// * `old_tree` A previous syntax tree parsed from the same document.
/// If the text of the document has changed since `old_tree` was
/// created, then you must edit `old_tree` to match the new text using
/// [`Tree::edit`].
pub fn parse_with<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
&mut self,
callback: &mut F,
old_tree: Option<&Tree>,
) -> Option<Tree> {
// A pointer to this payload is passed on every call to the `read` C function.
// The payload contains two things:
// 1. A reference to the rust `callback`.
// 2. The text that was returned from the previous call to `callback`.
// This allows the callback to return owned values like vectors.
let mut payload: (&mut F, Option<T>) = (callback, None);
// This C function is passed to Tree-sitter as the input callback.
unsafe extern "C" fn read<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
payload: *mut c_void,
byte_offset: u32,
position: ffi::TSPoint,
bytes_read: *mut u32,
) -> *const c_char {
let (callback, text) = payload.cast::<(&mut F, Option<T>)>().as_mut().unwrap();
*text = Some(callback(byte_offset as usize, position.into()));
let slice = text.as_ref().unwrap().as_ref();
*bytes_read = slice.len() as u32;
slice.as_ptr().cast::<c_char>()
}
let c_input = ffi::TSInput {
payload: std::ptr::addr_of_mut!(payload).cast::<c_void>(),
read: Some(read::<T, F>),
encoding: ffi::TSInputEncodingUTF8,
};
let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
unsafe {
let c_new_tree = ffi::ts_parser_parse(self.0.as_ptr(), c_old_tree, c_input);
NonNull::new(c_new_tree).map(Tree)
}
}
/// Parse UTF16 text provided in chunks by a callback.
///
/// # Arguments:
/// * `callback` A function that takes a code point offset and position and
/// returns a slice of UTF16-encoded text starting at that byte offset
/// and position. The slices can be of any length. If the given position
/// is at the end of the text, the callback should return an empty slice.
/// * `old_tree` A previous syntax tree parsed from the same document.
/// If the text of the document has changed since `old_tree` was
/// created, then you must edit `old_tree` to match the new text using
/// [`Tree::edit`].
pub fn parse_utf16_with<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
&mut self,
callback: &mut F,
old_tree: Option<&Tree>,
) -> Option<Tree> {
// A pointer to this payload is passed on every call to the `read` C function.
// The payload contains two things:
// 1. A reference to the rust `callback`.
// 2. The text that was returned from the previous call to `callback`.
// This allows the callback to return owned values like vectors.
let mut payload: (&mut F, Option<T>) = (callback, None);
// This C function is passed to Tree-sitter as the input callback.
unsafe extern "C" fn read<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
payload: *mut c_void,
byte_offset: u32,
position: ffi::TSPoint,
bytes_read: *mut u32,
) -> *const c_char {
let (callback, text) = payload.cast::<(&mut F, Option<T>)>().as_mut().unwrap();
*text = Some(callback(
(byte_offset / 2) as usize,
Point {
row: position.row as usize,
column: position.column as usize / 2,
},
));
let slice = text.as_ref().unwrap().as_ref();
*bytes_read = slice.len() as u32 * 2;
slice.as_ptr().cast::<c_char>()
}
let c_input = ffi::TSInput {
payload: std::ptr::addr_of_mut!(payload).cast::<c_void>(),
read: Some(read::<T, F>),
encoding: ffi::TSInputEncodingUTF16,
};
let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
unsafe {
let c_new_tree = ffi::ts_parser_parse(self.0.as_ptr(), c_old_tree, c_input);
NonNull::new(c_new_tree).map(Tree)
}
}
/// Instruct the parser to start the next parse from the beginning.
///
/// If the parser previously failed because of a timeout or a cancellation, then by default, it
/// will resume where it left off on the next call to [`parse`](Parser::parse) or other parsing
/// functions. If you don't want to resume, and instead intend to use this parser to parse some
/// other document, you must call `reset` first.
#[doc(alias = "ts_parser_reset")]
pub fn reset(&mut self) {
unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
}
/// Get the duration in microseconds that parsing is allowed to take.
///
/// This is set via [`set_timeout_micros`](Parser::set_timeout_micros).
#[doc(alias = "ts_parser_timeout_micros")]
#[must_use]
pub fn timeout_micros(&self) -> u64 {
unsafe { ffi::ts_parser_timeout_micros(self.0.as_ptr()) }
}
/// Set the maximum duration in microseconds that parsing should be allowed to
/// take before halting.
///
/// If parsing takes longer than this, it will halt early, returning `None`.
/// See [`parse`](Parser::parse) for more information.
#[doc(alias = "ts_parser_set_timeout_micros")]
pub fn set_timeout_micros(&mut self, timeout_micros: u64) {
unsafe { ffi::ts_parser_set_timeout_micros(self.0.as_ptr(), timeout_micros) }
}
/// Set the ranges of text that the parser should include when parsing.
///
/// By default, the parser will always include entire documents. This function
/// allows you to parse only a *portion* of a document but still return a syntax
/// tree whose ranges match up with the document as a whole. You can also pass
/// multiple disjoint ranges.
///
/// If `ranges` is empty, then the entire document will be parsed. Otherwise,
/// the given ranges must be ordered from earliest to latest in the document,
/// and they must not overlap. That is, the following must hold for all
/// `i` < `length - 1`:
/// ```text
/// ranges[i].end_byte <= ranges[i + 1].start_byte
/// ```
/// If this requirement is not satisfied, method will return [`IncludedRangesError`]
/// error with an offset in the passed ranges slice pointing to a first incorrect range.
#[doc(alias = "ts_parser_set_included_ranges")]
pub fn set_included_ranges(&mut self, ranges: &[Range]) -> Result<(), IncludedRangesError> {
let ts_ranges = ranges
.iter()
.copied()
.map(std::convert::Into::into)
.collect::<Vec<_>>();
let result = unsafe {
ffi::ts_parser_set_included_ranges(
self.0.as_ptr(),
ts_ranges.as_ptr(),
ts_ranges.len() as u32,
)
};
if result {
Ok(())
} else {
let mut prev_end_byte = 0;
for (i, range) in ranges.iter().enumerate() {
if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
return Err(IncludedRangesError(i));
}
prev_end_byte = range.end_byte;
}
Err(IncludedRangesError(0))
}
}
/// Get the ranges of text that the parser will include when parsing.
#[doc(alias = "ts_parser_included_ranges")]
#[must_use]
pub fn included_ranges(&self) -> Vec<Range> {
let mut count = 0u32;
unsafe {
let ptr =
ffi::ts_parser_included_ranges(self.0.as_ptr(), std::ptr::addr_of_mut!(count));
let ranges = slice::from_raw_parts(ptr, count as usize);
let result = ranges
.iter()
.copied()
.map(std::convert::Into::into)
.collect();
result
}
}
/// Get the parser's current cancellation flag pointer.
///
/// # Safety
///
/// It uses FFI
#[doc(alias = "ts_parser_cancellation_flag")]
#[must_use]
pub unsafe fn cancellation_flag(&self) -> Option<&AtomicUsize> {
ffi::ts_parser_cancellation_flag(self.0.as_ptr())
.cast::<AtomicUsize>()
.as_ref()
}
/// Set the parser's current cancellation flag pointer.
///
/// If a pointer is assigned, then the parser will periodically read from
/// this pointer during parsing. If it reads a non-zero value, it will halt early,
/// returning `None`. See [`parse`](Parser::parse) for more information.
///
/// # Safety
///
/// It uses FFI
#[doc(alias = "ts_parser_set_cancellation_flag")]
pub unsafe fn set_cancellation_flag(&mut self, flag: Option<&AtomicUsize>) {
if let Some(flag) = flag {
ffi::ts_parser_set_cancellation_flag(
self.0.as_ptr(),
(flag as *const AtomicUsize).cast::<usize>(),
);
} else {
ffi::ts_parser_set_cancellation_flag(self.0.as_ptr(), ptr::null());
}
}
}
impl Drop for Parser {
fn drop(&mut self) {
self.stop_printing_dot_graphs();
self.set_logger(None);
unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
}
}
impl Tree {
/// Get the root node of the syntax tree.
#[doc(alias = "ts_tree_root_node")]
#[must_use]
pub fn root_node(&self) -> Node {
Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
}
/// Get the root node of the syntax tree, but with its position shifted
/// forward by the given offset.
#[doc(alias = "ts_tree_root_node_with_offset")]
#[must_use]
pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
Node::new(unsafe {
ffi::ts_tree_root_node_with_offset(
self.0.as_ptr(),
offset_bytes as u32,
offset_extent.into(),
)
})
.unwrap()
}
/// Get the language that was used to parse the syntax tree.
#[doc(alias = "ts_tree_language")]
#[must_use]
pub fn language(&self) -> LanguageRef {
LanguageRef(
unsafe { ffi::ts_tree_language(self.0.as_ptr()) },
PhantomData,
)
}
/// Edit the syntax tree to keep it in sync with source code that has been
/// edited.
///
/// You must describe the edit both in terms of byte offsets and in terms of
/// row/column coordinates.
#[doc(alias = "ts_tree_edit")]
pub fn edit(&mut self, edit: &InputEdit) {
let edit = edit.into();
unsafe { ffi::ts_tree_edit(self.0.as_ptr(), &edit) };
}
/// Create a new [`TreeCursor`] starting from the root of the tree.
#[must_use]
pub fn walk(&self) -> TreeCursor {
self.root_node().walk()
}
/// Compare this old edited syntax tree to a new syntax tree representing the same
/// document, returning a sequence of ranges whose syntactic structure has changed.
///
/// For this to work correctly, this syntax tree must have been edited such that its
/// ranges match up to the new tree. Generally, you'll want to call this method right
/// after calling one of the [`Parser::parse`] functions. Call it on the old tree that
/// was passed to parse, and pass the new tree that was returned from `parse`.
#[doc(alias = "ts_tree_get_changed_ranges")]
#[must_use]
pub fn changed_ranges(&self, other: &Self) -> impl ExactSizeIterator<Item = Range> {
let mut count = 0u32;
unsafe {
let ptr = ffi::ts_tree_get_changed_ranges(
self.0.as_ptr(),
other.0.as_ptr(),
std::ptr::addr_of_mut!(count),
);
util::CBufferIter::new(ptr, count as usize).map(std::convert::Into::into)
}
}
/// Get the included ranges that were used to parse the syntax tree.
#[doc(alias = "ts_tree_included_ranges")]
#[must_use]
pub fn included_ranges(&self) -> Vec<Range> {
let mut count = 0u32;
unsafe {
let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), std::ptr::addr_of_mut!(count));
let ranges = slice::from_raw_parts(ptr, count as usize);
let result = ranges
.iter()
.copied()
.map(std::convert::Into::into)
.collect();
(FREE_FN)(ptr.cast::<c_void>());
result
}
}
/// Print a graph of the tree to the given file descriptor.
/// The graph is formatted in the DOT language. You may want to pipe this graph
/// directly to a `dot(1)` process in order to generate SVG output.
#[doc(alias = "ts_tree_print_dot_graph")]
pub fn print_dot_graph(
&self,
#[cfg(unix)] file: &impl AsRawFd,
#[cfg(windows)] file: &impl AsRawHandle,
) {
#[cfg(unix)]
{
let fd = file.as_raw_fd();
unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
}
#[cfg(windows)]
{
let handle = file.as_raw_handle();
unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), handle as i32) }
}
}
}
impl fmt::Debug for Tree {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{Tree {:?}}}", self.root_node())
}
}
impl Drop for Tree {
fn drop(&mut self) {
unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
}
}
impl Clone for Tree {
fn clone(&self) -> Self {
unsafe { Self(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
}
}
impl<'tree> Node<'tree> {
fn new(node: ffi::TSNode) -> Option<Self> {
(!node.id.is_null()).then_some(Node(node, PhantomData))
}
/// Get a numeric id for this node that is unique.
///
/// Within a given syntax tree, no two nodes have the same id. However, if
/// a new tree is created based on an older tree, and a node from the old
/// tree is reused in the process, then that node will have the same id in
/// both trees.
#[must_use]
pub fn id(&self) -> usize {
self.0.id as usize
}
/// Get this node's type as a numerical id.
#[doc(alias = "ts_node_symbol")]
#[must_use]
pub fn kind_id(&self) -> u16 {
unsafe { ffi::ts_node_symbol(self.0) }
}
/// Get the node's type as a numerical id as it appears in the grammar
/// ignoring aliases.
#[doc(alias = "ts_node_grammar_symbol")]
#[must_use]