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
#![allow(clippy::unused_unit)]

// FIXME: Double check we construct object properties in order.

use core::cell::RefCell;
use js_sys::{Array, Error, Function, JsString, Object, Promise, Reflect, Uint8Array};
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::JsFuture;

trait JsValueExt {
    type Value;
    fn lift_error(self) -> Result<Self::Value, JsError>;
}

impl<T> JsValueExt for Result<T, JsValue> {
    type Value = T;

    fn lift_error(self) -> Result<Self::Value, JsError> {
        self.map_err(|err| {
            let message = match err.dyn_into::<Error>() {
                Ok(error) => error.message(),
                Err(value) => JsString::from(value),
            };
            JsError::new(&String::from(message))
        })
    }
}

#[cfg(feature = "node")]
#[wasm_bindgen]
extern {
    #[wasm_bindgen(js_name = "global")]
    static GLOBAL: Object;
}

#[cfg(feature = "node")]
#[wasm_bindgen(module = "web-tree-sitter-wasm-bindgen")]
extern {
    fn initialize_tree_sitter() -> Promise;
}

thread_local! {
    // Ensure `web-tree-sitter` is only initialized once
    static TREE_SITTER_INITIALIZED: RefCell<bool> = RefCell::new(false);
}

pub struct TreeSitter;

impl TreeSitter {
    #[cfg(feature = "node")]
    pub async fn init() -> Result<(), JsError> {
        #![allow(non_snake_case)]

        // Exit early if `web-tree-sitter` is already initialized
        if TREE_SITTER_INITIALIZED.with(|cell| *cell.borrow()) {
            return Ok(());
        }

        JsFuture::from(initialize_tree_sitter()).await.lift_error()?;

        // Set `web-tree-sitter` to initialized
        TREE_SITTER_INITIALIZED.with(|cell| cell.replace(true));

        Ok(())
    }

    #[cfg(feature = "web")]
    pub async fn init() -> Result<(), JsError> {
        #![allow(non_snake_case)]

        // Exit early if `web-tree-sitter` is already initialized
        if TREE_SITTER_INITIALIZED.with(|cell| *cell.borrow()) {
            return Ok(());
        }

        let scope = &web_sys::window().unwrap_throw();

        let tree_sitter = Reflect::get(&scope, &"TreeSitter".into()).and_then(|property| {
            if property.is_undefined() {
                let message = "window.TreeSitter is not defined; load the tree-sitter javascript module first";
                Err(JsError::new(message).into())
            } else {
                Ok(property)
            }
        })?;

        // Call `init` from `web-tree-sitter` to initialize emscripten
        let init = Reflect::get(&tree_sitter, &"init".into())
            .lift_error()?
            .unchecked_into::<Function>();
        JsFuture::from(
            init.call0(&JsValue::UNDEFINED)
                .lift_error()?
                .unchecked_into::<Promise>(),
        )
        .await
        .lift_error()?;

        let Language = Reflect::get(&tree_sitter, &"Language".into()).lift_error()?;
        let Parser = tree_sitter;

        // Manually define `Parser` and `Language` in a fashion that works with wasm-bindgen
        Reflect::set(scope, &"Parser".into(), &Parser).lift_error()?;
        Reflect::set(scope, &"Language".into(), &Language).lift_error()?;

        // Set `web-tree-sitter` to initialized
        TREE_SITTER_INITIALIZED.with(|cell| cell.replace(true));

        Ok(())
    }

    fn init_guard() {
        if !TREE_SITTER_INITIALIZED.with(|cell| *cell.borrow()) {
            wasm_bindgen::throw_str("TreeSitter::init must be called to initialize the library");
        }
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type Edit;

    // Instance Properties

    #[wasm_bindgen(method, getter, js_name = newEndIndex)]
    pub fn new_end_index(this: &Edit) -> u32;

    #[wasm_bindgen(method, getter, js_name = newEndPosition)]
    pub fn new_end_position(this: &Edit) -> Point;

    #[wasm_bindgen(method, getter, js_name = oldEndIndex)]
    pub fn old_end_index(this: &Edit) -> u32;

    #[wasm_bindgen(method, getter, js_name = oldEndPosition)]
    pub fn old_end_position(this: &Edit) -> Point;

    #[wasm_bindgen(method, getter, js_name = startIndex)]
    pub fn start_index(this: &Edit) -> u32;

    #[wasm_bindgen(method, getter, js_name = startPosition)]
    pub fn start_position(this: &Edit) -> Point;
}

impl Edit {
    pub fn new(
        start_index: u32,
        old_end_index: u32,
        new_end_index: u32,
        start_position: &Point,
        old_end_position: &Point,
        new_end_position: &Point,
    ) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"startIndex".into(), &start_index.into()).unwrap();
        Reflect::set(&obj, &"oldEndIndex".into(), &old_end_index.into()).unwrap();
        Reflect::set(&obj, &"newEndIndex".into(), &new_end_index.into()).unwrap();
        Reflect::set(&obj, &"startPosition".into(), &start_position.into()).unwrap();
        Reflect::set(&obj, &"oldEndPosition".into(), &old_end_position.into()).unwrap();
        Reflect::set(&obj, &"newEndPosition".into(), &new_end_position.into()).unwrap();
        JsCast::unchecked_into(obj)
    }
}

impl Default for Edit {
    fn default() -> Self {
        let start_index = Default::default();
        let old_end_index = Default::default();
        let new_end_index = Default::default();
        let start_position = &Default::default();
        let old_end_position = &Default::default();
        let new_end_position = &Default::default();
        Self::new(
            start_index,
            old_end_index,
            new_end_index,
            start_position,
            old_end_position,
            new_end_position,
        )
    }
}

pub type Input = Function;

pub type InputClosureType = dyn FnMut(u32, Option<Point>, Option<u32>) -> Option<JsString>;

pub type Logger = Function;

pub type LoggerClosureType = dyn FnMut(JsString, LoggerParams, JsString);

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type LoggerParams;

    #[wasm_bindgen(method, indexing_getter)]
    fn get(this: &LoggerParams, key: &JsString) -> JsString;

    #[wasm_bindgen(method, indexing_setter)]
    fn set(this: &LoggerParams, val: &JsString);

    #[wasm_bindgen(method, indexing_deleter)]
    fn delete(this: &LoggerParams, val: &JsString);
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, PartialEq)]
    pub type Language;

    // Static Methods

    #[wasm_bindgen(static_method_of = Language, js_name = load)]
    fn __load_bytes(bytes: &Uint8Array) -> Promise;

    #[wasm_bindgen(static_method_of = Language, js_name = load)]
    fn __load_path(path: &str) -> Promise;

    // Instance Properties

    #[wasm_bindgen(method, getter)]
    pub fn version(this: &Language) -> u32;

    #[wasm_bindgen(method, getter, js_name = fieldCount)]
    pub fn field_count(this: &Language) -> u16;

    #[wasm_bindgen(method, getter, js_name = nodeTypeCount)]
    pub fn node_kind_count(this: &Language) -> u16;

    // Instance Methods

    #[wasm_bindgen(method, js_name = fieldNameForId)]
    pub fn field_name_for_id(this: &Language, field_id: u16) -> Option<String>;

    #[wasm_bindgen(method, js_name = fieldIdForName)]
    pub fn field_id_for_name(this: &Language, field_name: &str) -> Option<u16>;

    #[wasm_bindgen(method, js_name = idForNodeType)]
    pub fn id_for_node_kind(this: &Language, kind: &str, named: bool) -> u16;

    #[wasm_bindgen(method, js_name = nodeTypeForId)]
    pub fn node_kind_for_id(this: &Language, kind_id: u16) -> Option<String>;

    #[wasm_bindgen(method, js_name = nodeTypeIsNamed)]
    pub fn node_kind_is_named(this: &Language, kind_id: u16) -> bool;

    #[wasm_bindgen(method, js_name = nodeTypeIsVisible)]
    pub fn node_kind_is_visible(this: &Language, kind_id: u16) -> bool;

    #[wasm_bindgen(catch, method)]
    pub fn query(this: &Language, source: &JsString) -> Result<Query, QueryError>;
}

impl Language {
    pub async fn load_bytes(bytes: &Uint8Array) -> Result<Language, LanguageError> {
        TreeSitter::init_guard();
        JsFuture::from(Language::__load_bytes(bytes))
            .await
            .map(JsCast::unchecked_into)
            .map_err(JsCast::unchecked_into)
    }

    pub async fn load_path(path: &str) -> Result<Language, LanguageError> {
        TreeSitter::init_guard();
        JsFuture::from(Language::__load_path(path))
            .await
            .map(JsCast::unchecked_into)
            .map_err(JsCast::unchecked_into)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Error)]
    pub type LanguageError;
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type ParseOptions;

    // Instance Properties

    // -> Range[]
    #[wasm_bindgen(method, getter, js_name = includedRanges)]
    pub fn included_ranges(this: &ParseOptions) -> Option<Array>;
}

impl ParseOptions {
    pub fn new(included_ranges: Option<&Array>) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"includedRanges".into(), &included_ranges.into()).unwrap();
        JsCast::unchecked_into(obj)
    }
}

impl Default for ParseOptions {
    fn default() -> Self {
        let included_ranges = Default::default();
        Self::new(included_ranges)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug)]
    #[wasm_bindgen(extends = Object)]
    pub type Point;

    // Instance Properties

    #[wasm_bindgen(method, getter)]
    pub fn column(this: &Point) -> u32;

    #[wasm_bindgen(method, getter)]
    pub fn row(this: &Point) -> u32;
}

impl Point {
    pub fn new(row: u32, column: u32) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"row".into(), &row.into()).unwrap();
        Reflect::set(&obj, &"column".into(), &column.into()).unwrap();
        JsCast::unchecked_into(obj)
    }

    #[inline(always)]
    fn spread(&self) -> (u32, u32) {
        (self.row(), self.column())
    }
}

impl Default for Point {
    fn default() -> Self {
        let row = Default::default();
        let column = Default::default();
        Self::new(row, column)
    }
}

impl Eq for Point {
}

impl std::hash::Hash for Point {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let this = self.spread();
        this.hash(state);
    }
}

impl Ord for Point {
    fn cmp(&self, that: &Self) -> std::cmp::Ordering {
        let this = self.spread();
        let that = that.spread();
        this.cmp(&that)
    }
}

impl PartialEq for Point {
    fn eq(&self, that: &Self) -> bool {
        let this = self.spread();
        let that = that.spread();
        this.eq(&that)
    }
}

impl PartialOrd for Point {
    fn partial_cmp(&self, that: &Point) -> Option<std::cmp::Ordering> {
        let this = self.spread();
        let that = that.spread();
        this.partial_cmp(&that)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type PredicateOperand;

    // Instance Properties

    #[wasm_bindgen(method, getter)]
    pub fn name(this: &PredicateOperand) -> JsString;

    #[wasm_bindgen(method, getter)]
    pub fn type_(this: &PredicateOperand) -> JsString;
}

impl PredicateOperand {
    pub fn new(type_: &JsString, name: &JsString) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"type".into(), &type_.into()).unwrap();
        Reflect::set(&obj, &"name".into(), &name.into()).unwrap();
        JsCast::unchecked_into(obj)
    }
}

impl Default for PredicateOperand {
    fn default() -> Self {
        let name = &<String as Default>::default().into();
        let type_ = &<String as Default>::default().into();
        Self::new(name, type_)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type PredicateResult;

    // Instance Properties

    #[wasm_bindgen(method, getter)]
    pub fn operator(this: &PredicateResult) -> JsString;

    // -> PredicateOperand[]
    #[wasm_bindgen(method, getter)]
    pub fn operands(this: &PredicateResult) -> Box<[JsValue]>;
}

impl PredicateResult {
    pub fn new(operator: &JsString, operands: &Array) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"operator".into(), &operator.into()).unwrap();
        Reflect::set(&obj, &"operands".into(), &operands.into()).unwrap();
        JsCast::unchecked_into(obj)
    }
}

impl Default for PredicateResult {
    fn default() -> Self {
        let operator = &<String as Default>::default().into();
        let operands = &<Vec<JsValue> as Default>::default().into_iter().collect();
        Self::new(operator, operands)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug)]
    pub type Query;

    // Instance Properties

    // -> JsString[]
    #[wasm_bindgen(method, getter, js_name = captureNames)]
    pub fn capture_names(this: &Query) -> Box<[JsValue]>;

    // Instance Methods

    #[wasm_bindgen(method)]
    pub fn delete(this: &Query);

    // -> QueryMatch[]
    #[wasm_bindgen(method)]
    pub fn matches(
        this: &Query,
        node: &SyntaxNode,
        start_position: Option<&Point>,
        end_position: Option<&Point>,
    ) -> Box<[JsValue]>;

    // -> QueryCapture[]
    #[wasm_bindgen(method)]
    pub fn captures(
        this: &Query,
        node: &SyntaxNode,
        start_position: Option<&Point>,
        end_position: Option<&Point>,
    ) -> Box<[JsValue]>;

    // -> PredicateResult[]
    #[wasm_bindgen(method, js_name = predicatesForPattern)]
    pub fn predicates_for_pattern(this: &Query, pattern_index: u32) -> Box<[JsValue]>;
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type QueryCapture;

    // Instance Properties

    #[wasm_bindgen(method, getter)]
    pub fn name(this: &QueryCapture) -> JsString;

    #[wasm_bindgen(method, getter)]
    pub fn node(this: &QueryCapture) -> SyntaxNode;
}

impl QueryCapture {
    pub fn new(name: &JsString, node: &SyntaxNode) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"name".into(), &name.into()).unwrap();
        Reflect::set(&obj, &"node".into(), &node.into()).unwrap();
        JsCast::unchecked_into(obj)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Error)]
    pub type QueryError;
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Object)]
    pub type QueryMatch;

    // Instance Properties

    #[wasm_bindgen(method, getter)]
    pub fn pattern(this: &QueryMatch) -> u32;

    // -> QueryCapture[]
    #[wasm_bindgen(method, getter)]
    pub fn captures(this: &QueryMatch) -> Box<[JsValue]>;
}

impl QueryMatch {
    pub fn new(pattern: u32, captures: &Array) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"pattern".into(), &pattern.into()).unwrap();
        Reflect::set(&obj, &"captures".into(), &captures.into()).unwrap();
        JsCast::unchecked_into(obj)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug)]
    #[wasm_bindgen(extends = Object)]
    pub type Range;

    // Instance Properties

    #[wasm_bindgen(method, getter, js_name = endIndex)]
    pub fn end_index(this: &Range) -> u32;

    #[wasm_bindgen(method, getter, js_name = endPosition)]
    pub fn end_position(this: &Range) -> Point;

    #[wasm_bindgen(method, getter, js_name = startIndex)]
    pub fn start_index(this: &Range) -> u32;

    #[wasm_bindgen(method, getter, js_name = startPosition)]
    pub fn start_position(this: &Range) -> Point;
}

impl Range {
    pub fn new(start_position: &Point, end_position: &Point, start_index: u32, end_index: u32) -> Self {
        let obj = Object::new();
        Reflect::set(&obj, &"startPosition".into(), &start_position.into()).unwrap();
        Reflect::set(&obj, &"endPosition".into(), &end_position.into()).unwrap();
        Reflect::set(&obj, &"startIndex".into(), &start_index.into()).unwrap();
        Reflect::set(&obj, &"endIndex".into(), &end_index.into()).unwrap();
        JsCast::unchecked_into(obj)
    }

    #[inline(always)]
    fn spread(&self) -> (u32, u32, Point, Point) {
        (
            self.start_index(),
            self.end_index(),
            self.start_position(),
            self.end_position(),
        )
    }
}

impl Default for Range {
    fn default() -> Range {
        let start_position = Default::default();
        let end_position = Default::default();
        let start_index = Default::default();
        let end_index = Default::default();
        Self::new(&start_position, &end_position, start_index, end_index)
    }
}

impl Eq for Range {
}

impl std::hash::Hash for Range {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let this = self.spread();
        this.hash(state)
    }
}

impl Ord for Range {
    fn cmp(&self, that: &Self) -> std::cmp::Ordering {
        let this = self.spread();
        let that = that.spread();
        this.cmp(&that)
    }
}

impl PartialEq<Range> for Range {
    fn eq(&self, that: &Self) -> bool {
        let this = self.spread();
        let that = that.spread();
        this.eq(&that)
    }
}

impl PartialOrd<Range> for Range {
    fn partial_cmp(&self, that: &Self) -> Option<std::cmp::Ordering> {
        let this = self.spread();
        let that = that.spread();
        this.partial_cmp(&that)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug)]
    pub type SyntaxNode;

    // Instance Properties

    #[wasm_bindgen(method, getter, js_name = childCount)]
    pub fn child_count(this: &SyntaxNode) -> u32;

    #[wasm_bindgen(method, getter)]
    pub fn children(this: &SyntaxNode) -> Box<[JsValue]>;

    #[wasm_bindgen(method, getter, js_name = endIndex)]
    pub fn end_index(this: &SyntaxNode) -> u32;

    #[wasm_bindgen(method, getter, js_name = endPosition)]
    pub fn end_position(this: &SyntaxNode) -> Point;

    #[wasm_bindgen(method, getter, js_name = firstChild)]
    pub fn first_child(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = firstNamedChild)]
    pub fn first_named_child(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter)]
    pub fn id(this: &SyntaxNode) -> u32;

    #[wasm_bindgen(method, getter, js_name = lastChild)]
    pub fn last_child(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = lastNamedChild)]
    pub fn last_named_child(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = namedChildCount)]
    pub fn named_child_count(this: &SyntaxNode) -> u32;

    #[wasm_bindgen(method, getter, js_name = namedChildren)]
    pub fn named_children(this: &SyntaxNode) -> Box<[JsValue]>;

    #[wasm_bindgen(method, getter, js_name = nextNamedSibling)]
    pub fn next_named_sibling(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = nextSibling)]
    pub fn next_sibling(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter)]
    pub fn parent(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = previousNamedSibling)]
    pub fn previous_named_sibling(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = previousSibling)]
    pub fn previous_sibling(this: &SyntaxNode) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, getter, js_name = startIndex)]
    pub fn start_index(this: &SyntaxNode) -> u32;

    #[wasm_bindgen(method, getter, js_name = startPosition)]
    pub fn start_position(this: &SyntaxNode) -> Point;

    #[wasm_bindgen(method, getter)]
    pub fn text(this: &SyntaxNode) -> JsString;

    #[wasm_bindgen(method, getter)]
    pub fn tree(this: &SyntaxNode) -> Tree;

    #[wasm_bindgen(method, getter, js_name = type)]
    pub fn type_(this: &SyntaxNode) -> JsString;

    #[wasm_bindgen(method, getter, js_name = typeId)]
    pub fn type_id(this: &SyntaxNode) -> u16;

    // Instance Methods

    #[wasm_bindgen(method)]
    pub fn child(this: &SyntaxNode, index: u32) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = childForFieldId)]
    pub fn child_for_field_id(this: &SyntaxNode, field_id: u16) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = childForFieldName)]
    pub fn child_for_field_name(this: &SyntaxNode, field_name: &str) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = descendantForIndex)]
    pub fn descendant_for_index(this: &SyntaxNode, index: u32) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = descendantForIndex)]
    pub fn descendant_for_index_range(this: &SyntaxNode, start_index: u32, end_index: u32) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = descendantForPosition)]
    pub fn descendant_for_position(this: &SyntaxNode, position: &Point) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = descendantForPosition)]
    pub fn descendant_for_position_range(
        this: &SyntaxNode,
        start_position: &Point,
        end_position: &Point,
    ) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = descendantsOfType)]
    pub fn descendants_of_type_array(
        this: &SyntaxNode,
        type_: Box<[JsValue]>,
        start_position: Option<&Point>,
        end_position: Option<&Point>,
    ) -> Box<[JsValue]>;

    // -> SyntaxNode[]
    #[wasm_bindgen(method, js_name = descendantsOfType)]
    pub fn descendants_of_type_string(
        this: &SyntaxNode,
        type_: &str,
        start_position: Option<&Point>,
        end_position: Option<&Point>,
    ) -> Box<[JsValue]>;

    #[wasm_bindgen(method)]
    pub fn equals(this: &SyntaxNode, other: &SyntaxNode) -> bool;

    #[wasm_bindgen(method, js_name = hasChanges)]
    pub fn has_changes(this: &SyntaxNode) -> bool;

    #[wasm_bindgen(method, js_name = hasError)]
    pub fn has_error(this: &SyntaxNode) -> bool;

    #[wasm_bindgen(method, js_name = isMissing)]
    pub fn is_missing(this: &SyntaxNode) -> bool;

    #[wasm_bindgen(method, js_name = isNamed)]
    pub fn is_named(this: &SyntaxNode) -> bool;

    #[wasm_bindgen(method, js_name = namedChild)]
    pub fn named_child(this: &SyntaxNode, index: u32) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = namedDescendantForIndex)]
    pub fn named_descendant_for_index(this: &SyntaxNode, index: u32) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = namedDescendantForIndex)]
    pub fn named_descendant_for_index_range(this: &SyntaxNode, start_index: u32, end_index: u32) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = namedDescendantForPosition)]
    pub fn named_descendant_for_position(this: &SyntaxNode, position: &Point) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = namedDescendantForPosition)]
    pub fn named_descendant_for_position_range(
        this: &SyntaxNode,
        start_position: &Point,
        end_position: &Point,
    ) -> Option<SyntaxNode>;

    #[wasm_bindgen(method, js_name = toString)]
    pub fn to_string(this: &SyntaxNode) -> JsString;

    #[wasm_bindgen(method)]
    pub fn walk(this: &SyntaxNode) -> TreeCursor;
}

impl PartialEq<SyntaxNode> for SyntaxNode {
    fn eq(&self, other: &SyntaxNode) -> bool {
        self.equals(other)
    }
}

impl Eq for SyntaxNode {
}

impl std::hash::Hash for SyntaxNode {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id().hash(state);
    }
}

#[wasm_bindgen]
extern {
    #[derive(Debug)]
    pub type Tree;

    // Instance Properties

    #[wasm_bindgen(method, getter, js_name = rootNode)]
    pub fn root_node(this: &Tree) -> SyntaxNode;

    // Instance Methods

    #[wasm_bindgen(method)]
    pub fn copy(this: &Tree) -> Tree;

    #[wasm_bindgen(method)]
    pub fn delete(this: &Tree);

    #[wasm_bindgen(method)]
    pub fn edit(this: &Tree, delta: &Edit) -> Tree;

    #[wasm_bindgen(method)]
    pub fn walk(this: &Tree) -> TreeCursor;

    // -> Range[]
    #[wasm_bindgen(method, js_name = getChangedRanges)]
    pub fn get_changed_ranges(this: &Tree, other: &Tree) -> Box<[JsValue]>;

    #[wasm_bindgen(method, js_name = getLanguage)]
    pub fn get_language(this: &Tree) -> Language;
}

impl Clone for Tree {
    fn clone(&self) -> Tree {
        self.copy()
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug)]
    pub type TreeCursor;

    // Instance Properties

    #[wasm_bindgen(method, getter, js_name = endIndex)]
    pub fn end_index(this: &TreeCursor) -> u32;

    #[wasm_bindgen(method, getter, js_name = endPosition)]
    pub fn end_position(this: &TreeCursor) -> Point;

    #[wasm_bindgen(method, getter, js_name = nodeIsNamed)]
    pub fn node_is_named(this: &TreeCursor) -> bool;

    #[wasm_bindgen(method, getter, js_name = nodeText)]
    pub fn node_text(this: &TreeCursor) -> JsString;

    #[wasm_bindgen(method, getter, js_name = nodeType)]
    pub fn node_type(this: &TreeCursor) -> JsString;

    #[wasm_bindgen(method, getter, js_name = startIndex)]
    pub fn start_index(this: &TreeCursor) -> u32;

    #[wasm_bindgen(method, getter, js_name = startPosition)]
    pub fn start_position(this: &TreeCursor) -> Point;

    // Instance Methods

    #[wasm_bindgen(method, js_name = currentFieldId)]
    pub fn current_field_id(this: &TreeCursor) -> Option<u16>;

    #[wasm_bindgen(method, js_name = currentFieldName)]
    pub fn current_field_name(this: &TreeCursor) -> Option<JsString>;

    #[wasm_bindgen(method, js_name = currentNode)]
    pub fn current_node(this: &TreeCursor) -> SyntaxNode;

    #[wasm_bindgen(method)]
    pub fn delete(this: &TreeCursor);

    #[wasm_bindgen(method, js_name = gotoFirstChild)]
    pub fn goto_first_child(this: &TreeCursor) -> bool;

    #[wasm_bindgen(method, js_name = gotoNextSibling)]
    pub fn goto_next_sibling(this: &TreeCursor) -> bool;

    #[wasm_bindgen(method, js_name = gotoParent)]
    pub fn goto_parent(this: &TreeCursor) -> bool;

    #[wasm_bindgen(method)]
    pub fn reset(this: &TreeCursor, node: &SyntaxNode);
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug)]
    pub type Parser;

    // Static Methods

    // Constructor

    #[wasm_bindgen(catch, constructor)]
    fn __new() -> Result<Parser, ParserError>;

    // Instance Methods

    #[wasm_bindgen(method)]
    pub fn delete(this: &Parser);

    #[wasm_bindgen(method, js_name = getLanguage)]
    pub fn get_language(this: &Parser) -> Option<Language>;

    #[wasm_bindgen(method, js_name = getLogger)]
    pub fn get_logger(this: &Parser) -> Option<Logger>;

    #[wasm_bindgen(method, js_name = getTimeoutMicros)]
    pub fn get_timeout_micros(this: &Parser) -> f64;

    #[wasm_bindgen(catch, method, js_name = parse)]
    pub fn parse_with_function(
        this: &Parser,
        input: &Input,
        previous_tree: Option<&Tree>,
        options: Option<&ParseOptions>,
    ) -> Result<Option<Tree>, ParserError>;

    #[wasm_bindgen(catch, method, js_name = parse)]
    pub fn parse_with_string(
        this: &Parser,
        input: &JsString,
        previous_tree: Option<&Tree>,
        options: Option<&ParseOptions>,
    ) -> Result<Option<Tree>, ParserError>;

    #[wasm_bindgen(method)]
    pub fn reset(this: &Parser);

    #[wasm_bindgen(catch, method, js_name = setLanguage)]
    pub fn set_language(this: &Parser, language: Option<&Language>) -> Result<(), LanguageError>;

    #[wasm_bindgen(method, js_name = setLogger)]
    pub fn set_logger(this: &Parser, logger: Option<&Logger>);

    #[wasm_bindgen(method, js_name = setTimeoutMicros)]
    pub fn set_timeout_micros(this: &Parser, timeout_micros: f64);
}

impl Parser {
    pub fn new() -> Result<Parser, ParserError> {
        TreeSitter::init_guard();
        let result = Parser::__new()?;
        Ok(result)
    }
}

#[wasm_bindgen]
extern {
    #[derive(Clone, Debug, Eq, PartialEq)]
    #[wasm_bindgen(extends = Error)]
    pub type ParserError;
}