pbls 1.2.2

Protobuf Language Server
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
use anyhow::{Context, Result};
use ropey::Rope;
use std::sync::OnceLock;
use tree_sitter::StreamingIterator;

fn language() -> &'static tree_sitter::Language {
    static LANGUAGE: OnceLock<tree_sitter::Language> = OnceLock::new();
    LANGUAGE.get_or_init(|| tree_sitter_proto::LANGUAGE.into())
}

#[derive(Debug, PartialEq)]
pub enum SymbolKind {
    Message,
    Enum,
}

#[derive(Debug, PartialEq)]
pub struct Symbol {
    pub kind: SymbolKind,
    pub name: String,
    pub range: tree_sitter::Range,
}

#[derive(Debug, PartialEq)]
pub struct FieldNumberContext {
    pub used: Vec<u32>,
    pub reserved: Vec<std::ops::RangeInclusive<u32>>,
}

impl FieldNumberContext {
    pub fn next_free(&self) -> u32 {
        let mut candidate = 1u32;
        loop {
            if !self.used.contains(&candidate)
                && !self.reserved.iter().any(|r| r.contains(&candidate))
            {
                return candidate;
            }
            candidate += 1;
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum CompletionContext<'a> {
    Message(&'a str),
    Enum(&'a str),
    FieldNumber(FieldNumberContext),
    Rpc,
    Import,
    Keyword,
    Syntax,
    Option,
}

#[derive(Debug, PartialEq)]
pub struct GotoTypeContext<'a> {
    pub name: &'a str,
    pub parent: Option<String>,
}

#[derive(Debug, PartialEq)]
pub enum GotoContext<'a> {
    Type(GotoTypeContext<'a>),
    Import(&'a str),
}

pub struct File {
    tree: tree_sitter::Tree,
    text: String,
    rope: Rope,
}

impl File {
    pub fn new(text: String) -> Result<File> {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(language())
            .expect("Error loading proto language");

        let tree = parser.parse(&text, None).context("Parse failed")?;
        log::trace!("Parsed: {}", tree.root_node().to_sexp());
        let rope = Rope::from_str(&text);
        Ok(File { tree, text, rope })
    }

    /// Convert a tree-sitter Point (row + byte column) to an LSP Position (line + UTF-16 character).
    pub fn ts_to_lsp_pos(&self, pos: tree_sitter::Point) -> lsp_types::Position {
        let line = self.rope.line(pos.row);
        let char_offset = line.byte_to_char(pos.column);
        let utf16_offset = line.char_to_utf16_cu(char_offset);
        lsp_types::Position::new(pos.row as u32, utf16_offset as u32)
    }

    /// Convert an LSP Position (line + UTF-16 character) to a tree-sitter Point (row + byte column).
    pub fn lsp_to_ts_pos(&self, pos: lsp_types::Position) -> tree_sitter::Point {
        let line = self.rope.line(pos.line as usize);
        let char_offset = line.utf16_cu_to_char(pos.character as usize);
        let byte_offset = line.char_to_byte(char_offset);
        tree_sitter::Point::new(pos.line as usize, byte_offset)
    }

    /// Convert a tree-sitter Range to an LSP Range.
    pub fn ts_to_lsp_range(&self, range: tree_sitter::Range) -> lsp_types::Range {
        lsp_types::Range {
            start: self.ts_to_lsp_pos(range.start_point),
            end: self.ts_to_lsp_pos(range.end_point),
        }
    }

    /// Convert an LSP Position to an absolute byte offset in the text.
    fn lsp_pos_to_byte(&self, pos: lsp_types::Position) -> usize {
        let point = self.lsp_to_ts_pos(pos);
        self.rope.line_to_byte(point.row) + point.column
    }

    pub fn edit(&mut self, changes: Vec<lsp_types::TextDocumentContentChangeEvent>) -> Result<()> {
        for change in changes {
            let range = change
                .range
                .with_context(|| format!("No range in change notification {change:?}"))?;
            let start_byte = self.lsp_pos_to_byte(range.start);
            let end_byte = self.lsp_pos_to_byte(range.end);

            log::trace!(
                "Computing change {start_byte}..{end_byte} with text {}",
                change.text
            );

            self.text.replace_range(start_byte..end_byte, &change.text);
            self.rope = Rope::from_str(&self.text);
        }
        log::trace!("Edited text to: {}", self.text);

        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(language())
            .expect("Error loading proto language");
        self.tree = parser.parse(&self.text, None).context("Parse failed")?;
        log::trace!("Edited tree to: {}", self.tree.root_node().to_sexp());

        Ok(())
    }

    fn get_text(&self, node: tree_sitter::Node) -> &str {
        node.utf8_text(self.text.as_bytes()).unwrap()
    }

    pub fn text(&self) -> &str {
        self.text.as_str()
    }

    pub fn package(&self) -> Option<&str> {
        static QUERY: OnceLock<tree_sitter::Query> = OnceLock::new();
        let query = QUERY.get_or_init(|| {
            tree_sitter::Query::new(language(), "(package (full_ident) @id)").unwrap()
        });

        let mut qc = tree_sitter::QueryCursor::new();
        let mut matches = qc.matches(query, self.tree.root_node(), self.text.as_bytes());
        matches
            .next()
            .map(|m| m.captures[0].node)
            .map(|n| self.get_text(n))
    }

    pub fn imports(&self, qc: &mut tree_sitter::QueryCursor) -> Vec<&str> {
        static QUERY: OnceLock<tree_sitter::Query> = OnceLock::new();
        let query = QUERY.get_or_init(|| {
            tree_sitter::Query::new(language(), "(import (string) @path)").unwrap()
        });

        let mut matches = qc.matches(query, self.tree.root_node(), self.text.as_bytes());
        let mut result = Vec::new();
        while let Some(m) = matches.next() {
            result.push(self.get_text(m.captures[0].node).trim_matches('"'));
        }
        result
    }

    pub fn symbols(&self, qc: &mut tree_sitter::QueryCursor) -> Vec<Symbol> {
        static QUERY: OnceLock<tree_sitter::Query> = OnceLock::new();
        let query = QUERY.get_or_init(|| {
            tree_sitter::Query::new(
                language(),
                "[
                     (message (message_name (identifier) @id))
                     (enum (enum_name (identifier) @id))
                 ] @def",
            )
            .unwrap()
        });

        let mut matches = qc.matches(query, self.tree.root_node(), self.text.as_bytes());
        let mut result = Vec::new();
        while let Some(m) = matches.next() {
            let def = m.captures[0].node;
            let id = m.captures[1].node;
            let name = self.get_text(id).to_string();
            let name = if let Some(p) = self.parent_name(def) {
                p + "." + &name
            } else {
                name
            };
            result.push(Symbol {
                kind: match def.kind() {
                    "message" => SymbolKind::Message,
                    _ => SymbolKind::Enum,
                },
                name,
                range: def.range(),
            });
        }
        result
    }

    // Return all symbols adjusted relative to a message.
    // For example, given base_name=Foo.Bar:
    // symbols()          -> [Foo, Foo.Bar, Foo.Bar.Baz, Foo.Bar.Baz.Biz]
    // relative_symbols() -> [Foo, Bar    , Baz        , Baz.Biz]
    pub fn relative_symbols(
        &self,
        base_name: &str,
        qc: &mut tree_sitter::QueryCursor,
    ) -> Vec<Symbol> {
        self.symbols(qc)
            .into_iter()
            .map(|s| Symbol {
                name: relative_name(base_name, &s.name),
                ..s
            })
            .collect()
    }

    // Given an "ident" or "enumMessageType", node representing a type, find the name of the type.
    fn field_type(&self, node: Option<tree_sitter::Node>) -> Option<&str> {
        log::trace!("Finding type of {node:?}");
        match node {
            None => None,
            Some(n) if n.kind() == "type" || n.kind() == "message_or_enum_type" => {
                Some(self.get_text(n))
            }
            Some(n) => self.field_type(n.parent()),
        }
    }

    fn parent_context(&self, node: Option<tree_sitter::Node<'_>>) -> Option<CompletionContext<'_>> {
        log::trace!(
            "Checking parent context: {node:?} - {}",
            node.map_or("".into(), |n| n.to_sexp())
        );
        match node {
            // Hit the document root
            None => None,
            // Don't complete if we're typing a field name or number
            // Don't complete field names (parent is a named field node)
            Some(n)
                if n.kind() == "identifier"
                    && n.parent().is_some_and(|p| {
                        matches!(p.kind(), "field" | "oneof_field" | "map_field")
                    }) =>
            {
                None
            }
            // Don't complete field names in error-recovered incomplete fields:
            // identifier immediately following a `type` sibling is a field name
            Some(n)
                if n.kind() == "identifier"
                    && n.prev_named_sibling().is_some_and(|s| s.kind() == "type") =>
            {
                None
            }
            Some(n)
                if n.kind() == "message_name"
                    || n.kind() == "enum_name"
                    || n.kind() == "service_name" =>
            {
                None
            }
            Some(n) if n.kind() == "enum_body" => n
                .parent() // enum
                .and_then(|p| self.type_name(p))
                .map(CompletionContext::Enum),
            // Fallback: reach the enum node directly when enum_body is absent (error recovery)
            Some(n) if n.kind() == "enum" => self.type_name(n).map(CompletionContext::Enum),
            Some(n) if n.kind() == "message_body" => n
                .parent() // message
                .and_then(|p| self.type_name(p))
                .map(CompletionContext::Message),
            // Fallback: reach the message node directly when message_body is absent
            Some(n) if n.kind() == "message" => self.type_name(n).map(CompletionContext::Message),
            // In the new grammar there is no service_body wrapper; rpc nodes are direct children
            Some(n) if n.kind() == "service" => Some(CompletionContext::Rpc),
            // ERROR containing "oneof <name>" means we're typing an oneof name, not a type
            Some(n) if n.is_error() && self.get_text(n).starts_with("oneof ") => None,
            Some(n) => self.parent_context(n.parent()),
        }
    }

    fn extract_field_number(&self, node: tree_sitter::Node) -> Option<u32> {
        let mut cursor = node.walk();
        // Assign to a variable so the iterator (and its borrow of `cursor`) is dropped before
        // we create a second cursor below.
        let fn_node = node
            .named_children(&mut cursor)
            .find(|c| c.kind() == "field_number")?;
        let mut c2 = fn_node.walk();
        let int_node = fn_node
            .named_children(&mut c2)
            .find(|c| c.kind() == "int_lit")?;
        self.get_text(int_node).parse::<u32>().ok()
    }

    fn collect_field_numbers(&self, message_body: tree_sitter::Node) -> FieldNumberContext {
        let mut used = Vec::new();
        let mut reserved = Vec::new();
        let mut cursor = message_body.walk();

        for child in message_body.named_children(&mut cursor) {
            match child.kind() {
                "field" | "map_field" => {
                    if let Some(num) = self.extract_field_number(child) {
                        used.push(num);
                    }
                }
                "oneof" => {
                    let mut c2 = child.walk();
                    for oneof_child in child.named_children(&mut c2) {
                        if oneof_child.kind() == "oneof_field" {
                            if let Some(num) = self.extract_field_number(oneof_child) {
                                used.push(num);
                            }
                        }
                    }
                }
                "reserved" => {
                    let mut c2 = child.walk();
                    for ranges_node in child.named_children(&mut c2) {
                        if ranges_node.kind() == "ranges" {
                            let mut c3 = ranges_node.walk();
                            for range_node in ranges_node.named_children(&mut c3) {
                                if range_node.kind() == "range" {
                                    let mut c4 = range_node.walk();
                                    let ints: Vec<u32> = range_node
                                        .named_children(&mut c4)
                                        .filter(|c| c.kind() == "int_lit")
                                        .filter_map(|c| self.get_text(c).parse::<u32>().ok())
                                        .collect();
                                    match ints.as_slice() {
                                        [n] => reserved.push(*n..=*n),
                                        [low, high] => reserved.push(*low..=*high),
                                        _ => {}
                                    }
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        FieldNumberContext { used, reserved }
    }

    fn field_number_completion_context(
        &self,
        node: tree_sitter::Node,
    ) -> Option<CompletionContext<'_>> {
        let mut n = Some(node);
        while let Some(current) = n {
            match current.kind() {
                "message_body" => {
                    return Some(CompletionContext::FieldNumber(
                        self.collect_field_numbers(current),
                    ));
                }
                // Don't cross into enum body — enum field numbers are semantic values, not positions
                "enum_body" => return None,
                _ => {}
            }
            n = current.parent();
        }
        None
    }

    pub fn completion_context(
        &self,
        row: usize,
        col: usize,
    ) -> Result<Option<CompletionContext<'_>>> {
        if self.tree.root_node().kind() != "source_file" || self.text.trim().is_empty() {
            // If the whole document is invalid or empty, we need to define a syntax.
            return Ok(Some(CompletionContext::Syntax));
        }

        let pos = tree_sitter::Point {
            row,
            // Generally, the node before the cursor is more interesting for context.
            column: col.saturating_sub(1),
        };
        let node = self
            .tree
            .root_node()
            .named_descendant_for_point_range(pos, pos)
            .with_context(|| format!("No descendant for range {pos:?}"))?;

        log::debug!(
            "Getting completion context for node={node:?} parent={:?}",
            node.parent(),
        );

        log::trace!(
            "Getting completion context for node text: {}",
            self.get_text(node),
        );

        Ok(if node.kind() == "option" {
            // option | -> (option)
            Some(CompletionContext::Option)
        } else if is_sexp(node, &["option", "identifier"])
            || is_sexp(node, &["option", "full_ident", "identifier"])
        {
            // option c| -> (option (identifier)) or (option (full_ident (identifier)))
            Some(CompletionContext::Option)
        } else if (node.is_error() && self.get_text(node).starts_with("option "))
            || node
                .parent()
                .is_some_and(|p| p.is_error() && self.get_text(p).starts_with("option "))
        {
            // option | -> (ERROR)
            Some(CompletionContext::Option)
        } else if node.is_error() && self.get_text(node).starts_with("import ") {
            // import "| -> (ERROR)
            Some(CompletionContext::Import)
        } else if is_sexp(node, &["import", "string"]) {
            // import "foo|.proto" -> (import (string))
            Some(CompletionContext::Import)
        } else if node.kind() == "type"
            || (node.kind() == "identifier" && !node.parent().is_some_and(|p| p.kind() == "oneof"))
        {
            // message Foo { Bar| -> (identifier)
            // message Foo { string| -> (type)
            self.parent_context(Some(node))
        } else if is_sexp(node, &["field_number", "int_lit"])
            || is_sexp(node, &["field_number", "int_lit", "decimal_lit"])
        {
            // message Foo { string d = 1| -> (field (field_number (int_lit (decimal_lit))))
            self.field_number_completion_context(node)
        } else if let Some(ctx) = {
            // Cursor is after '=' on a field number position. This covers several parse states:
            //   - ERROR node (incomplete field): node text contains '='
            //   - field/message_body node: space after '=' lands on a non-ERROR node
            // Check the line before the cursor ends with '=' then walk up for message_body.
            let line = self.text.lines().nth(row).unwrap_or("");
            let before = &line[..col.min(line.len())];
            if before.trim_end().ends_with('=') {
                self.field_number_completion_context(node)
            } else {
                None
            }
        } {
            Some(ctx)
        } else if node.is_error() && !is_top_level_error(node) && !self.get_text(node).contains('=')
        {
            // Nested ERROR node (e.g. a new identifier being typed inside enum_body/message_body).
            // If the error text contains '=', we are in a partial assignment (value position) where
            // no type completion is appropriate.
            self.parent_context(node.parent())
        } else if is_top_level_error(node) {
            // typically means we're typing the first word of a line
            // mes| -> (source_file (ERROR (ERROR)))
            Some(CompletionContext::Keyword)
        } else if node.kind() == "source_file" {
            // NOTE: Not very efficient, but we're in a difficult spot here.
            let full_line = self
                .text
                .lines()
                .nth(row)
                .with_context(|| format!("Line {row} out of range"))?;
            let line = &full_line[..col.min(full_line.len())];
            let line = line.trim_start();

            log::trace!("Checking keyword completion for line {line}");

            if line.starts_with("option ") {
                Some(CompletionContext::Option)
            } else if line.split(char::is_whitespace).count() <= 1 {
                // first word of the line
                Some(CompletionContext::Keyword)
            } else {
                None
            }
        } else {
            None
        })
    }

    pub fn type_references(
        &self,
        pkg: Option<&str>,
        typ: &GotoTypeContext,
    ) -> Vec<tree_sitter::Range> {
        static QUERY: OnceLock<tree_sitter::Query> = OnceLock::new();
        let query = QUERY
            .get_or_init(|| tree_sitter::Query::new(language(), "(field (type) @name)").unwrap());
        let typ = typ.name;
        log::trace!("Searching for references to {typ} in package {pkg:?}");

        let mut qc = tree_sitter::QueryCursor::new();
        let mut matches = qc.matches(query, self.tree.root_node(), self.text.as_bytes());
        let mut result = Vec::new();
        while let Some(m) = matches.next() {
            let node = m.captures[0].node;
            log::trace!("Check {node:?}: {} == {typ}", self.get_text(node));
            let text = self.get_text(node);
            let matches = text == typ
                || match pkg {
                    Some(pkg) => {
                        log::trace!("Trying to match '{typ}' to '{text}' without package {pkg}");
                        text.strip_prefix(pkg)
                            .and_then(|text| text.strip_prefix("."))
                            .map(|text| typ == text)
                            .unwrap_or(false)
                    }
                    None => false,
                };
            if matches {
                result.push(node.range());
            }
        }
        result
    }

    pub fn import_references(&self, file: &str) -> Vec<tree_sitter::Range> {
        static QUERY: OnceLock<tree_sitter::Query> = OnceLock::new();
        let query = QUERY.get_or_init(|| {
            tree_sitter::Query::new(language(), "(import (string) @name)").unwrap()
        });

        let mut qc = tree_sitter::QueryCursor::new();
        let mut matches = qc.matches(query, self.tree.root_node(), self.text.as_bytes());
        let mut result = Vec::new();
        while let Some(m) = matches.next() {
            let n = m.captures[0].node;
            if self.get_text(n).trim_matches('"') == file {
                result.push(n.range());
            }
        }
        result
    }

    pub fn type_at(&self, row: usize, column: usize) -> Option<GotoContext<'_>> {
        log::trace!("Getting type at row: {row} col: {column}");

        let pos = tree_sitter::Point { row, column };
        let node = self
            .tree
            .root_node()
            .named_descendant_for_point_range(pos, pos)?;

        log::debug!("Getting type at node: {node:?} parent: {:?}", node.parent());

        if node.kind() == "string" && node.parent().is_some_and(|p| p.kind() == "import") {
            return Some(GotoContext::Import(self.get_text(node).trim_matches('"')));
        }

        // Cursor is over a message or enum name.
        if is_sexp(node, &["enum", "enum_name", "identifier"])
            || is_sexp(node, &["message", "message_name", "identifier"])
        {
            return Some(GotoContext::Type(GotoTypeContext {
                name: self.get_text(node.parent().unwrap()),
                parent: None,
            }));
        }

        // Cursor is over a field type.
        if node.kind() == "identifier" || node.kind() == "message_or_enum_type" {
            if let Some(name) = self.field_type(Some(node)) {
                return Some(GotoContext::Type(GotoTypeContext {
                    name,
                    parent: self.parent_name(node),
                }));
            }
        }

        None
    }

    fn parent_name(&self, node: tree_sitter::Node) -> Option<String> {
        log::trace!("Finding parent name for {node:?}");
        let mut node = node;
        let mut res = Vec::<&str>::new();
        while let Some(parent) = node.parent() {
            if parent.kind() == "message" {
                let name = self.type_name(parent);
                log::trace!("Appending parent name {name:?}");
                if let Some(n) = name {
                    res.push(n)
                }
            }
            node = parent;
        }

        if res.is_empty() {
            None
        } else {
            res.reverse();
            Some(res.join("."))
        }
    }

    // Get the name of a Enum or Message node.
    fn type_name(&self, node: tree_sitter::Node) -> Option<&str> {
        debug_assert!(
            node.kind() == "enum" || node.kind() == "message" || node.kind() == "service",
            "{node:?}"
        );
        let mut cursor = node.walk();
        let child = node.named_children(&mut cursor).find(|c| {
            c.kind() == "message_name" || c.kind() == "enum_name" || c.kind() == "service_name"
        });
        child.and_then(|c| c.utf8_text(self.text.as_bytes()).ok())
    }
}

fn is_top_level_error(node: tree_sitter::Node) -> bool {
    if node.is_error() || node.is_missing() {
        match node.parent() {
            None => true,
            Some(n) if n.kind() == "source_file" => true,
            Some(n) if n.is_error() || n.is_missing() => is_top_level_error(n),
            _ => false,
        }
    } else {
        false
    }
}

// Find the shortest form of a type name relative to a message
// relative_name("Foo", "Foo.Bar.Baz") -> "Bar.Baz"
// relative_name("Foo.Bar", "Foo.Bar.Baz") -> "Baz"
// relative_name("Foo.Bar", "Foo.Bar") -> "Bar"
// relative_name("Foo.Bar", "Foo") -> "Foo"
fn relative_name(message: &str, name: &str) -> String {
    let prefix = name
        .split(".")
        .zip(message.split("."))
        .take_while(|(a, b)| a == b)
        .map(|(a, _)| a)
        .collect::<Vec<_>>()
        .join(".");

    if prefix.len() == name.len() {
        let Some((_, name)) = name.rsplit_once(".") else {
            return name.to_string();
        };
        name.to_string()
    } else {
        name.strip_prefix(prefix.as_str())
            .unwrap_or(name)
            .strip_prefix(".")
            .unwrap_or(name)
            .to_string()
    }
}

fn is_sexp(node: tree_sitter::Node, sexp: &[&str]) -> bool {
    let Some((kind, rest)) = sexp.split_last() else {
        return true; // got to end, whole sexp matched
    };

    if &node.kind() != kind {
        return false;
    }

    if let Some(parent) = node.parent() {
        is_sexp(parent, rest)
    } else {
        false
    }
}


#[cfg(test)]
mod tests {
    use tree_sitter::Point;

    use super::*;
    use pretty_assertions::assert_eq;

    // Takes a string with '|' characters representing cursors.
    // Builds a file from the string with '|' removed, and returns the positions of the cursors.
    fn cursors(text: &str) -> (File, Vec<Point>) {
        let cursors = text
            .lines()
            .enumerate()
            .flat_map(|(row, line)| {
                line.match_indices('|')
                    .enumerate()
                    .map(move |(i, (column, _))| Point {
                        row,
                        // subtract 1 for each '|' before in this row,
                        // as those offset the position of following '|'
                        column: column - i,
                    })
            })
            .collect();
        (File::new(text.replace('|', "")).unwrap(), cursors)
    }

    // Like cursors, but expect exactly one |
    fn cursor(text: &str) -> (File, Point) {
        let cursor = text
            .lines()
            .enumerate()
            .flat_map(|(row, line)| {
                line.match_indices('|')
                    .enumerate()
                    .map(move |(i, (column, _))| Point {
                        row,
                        // subtract 1 for each '|' before in this row,
                        // as those offset the position of following '|'
                        column: column - i,
                    })
            })
            .next()
            .unwrap();
        (File::new(text.replace('|', "")).unwrap(), cursor)
    }

    #[test]
    fn test_package() {
        let _ = env_logger::builder().is_test(true).try_init();
        let text = r#"syntax="proto3"; package main;"#;
        let file = File::new(text.to_string()).unwrap();
        assert_eq!(file.package(), Some("main"));

        let text = r#"syntax="proto3"; package main; package other"#;
        let file = File::new(text.to_string()).unwrap();
        assert_eq!(file.package(), Some("main"));

        let text = r#"syntax="proto3"; package foo.bar.baz;"#;
        let file = File::new(text.to_string()).unwrap();
        assert_eq!(file.package(), Some("foo.bar.baz"));

        let text = r#"syntax="proto3";"#;
        let file = File::new(text.to_string()).unwrap();
        assert_eq!(file.package(), None);
    }

    #[test]
    fn test_imports() {
        let _ = env_logger::builder().is_test(true).try_init();
        let text = r#"
            syntax="proto3";
            package main;
            import "foo.proto";
            import "bar.proto";
            import "ba
        "#;
        let file = File::new(text.to_string()).unwrap();
        let mut qc = tree_sitter::QueryCursor::new();
        assert_eq!(file.imports(&mut qc), vec!["foo.proto", "bar.proto"]);
    }

    #[test]
    fn test_symbols() {
        let _ = env_logger::builder().is_test(true).try_init();
        let text = r#"
            syntax="proto3";
            package main;
            message Foo{}
            enum Bar{}
            message Baz{
                message Biz{
                    message Buz{}
                }
            }
        "#;
        let file = File::new(text.to_string()).unwrap();
        let mut qc = tree_sitter::QueryCursor::new();
        assert_eq!(
            file.symbols(&mut qc),
            vec![
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Foo".into(),
                    range: tree_sitter::Range {
                        start_byte: 68,
                        end_byte: 81,
                        start_point: Point { row: 3, column: 12 },
                        end_point: Point { row: 3, column: 25 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Enum,
                    name: "Bar".into(),
                    range: tree_sitter::Range {
                        start_byte: 94,
                        end_byte: 104,
                        start_point: Point { row: 4, column: 12 },
                        end_point: Point { row: 4, column: 22 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Baz".into(),
                    range: tree_sitter::Range {
                        start_byte: 117,
                        end_byte: 224,
                        start_point: Point { row: 5, column: 12 },
                        end_point: Point { row: 9, column: 13 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Baz.Biz".into(),
                    range: tree_sitter::Range {
                        start_byte: 146,
                        end_byte: 210,
                        start_point: Point { row: 6, column: 16 },
                        end_point: Point { row: 8, column: 17 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Baz.Biz.Buz".into(),
                    range: tree_sitter::Range {
                        start_byte: 179,
                        end_byte: 192,
                        start_point: Point { row: 7, column: 20 },
                        end_point: Point { row: 7, column: 33 },
                    },
                },
            ]
        );
    }

    #[test]
    fn test_relative_symbols() {
        let _ = env_logger::builder().is_test(true).try_init();
        let text = r#"
            syntax="proto3";
            package main;
            message Foo{}
            enum Bar{}
            message Baz{
                message Biz{}
            }
        "#;
        let file = File::new(text.to_string()).unwrap();
        let mut qc = tree_sitter::QueryCursor::new();
        assert_eq!(
            file.relative_symbols("Foo", &mut qc),
            vec![
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Foo".into(),
                    range: tree_sitter::Range {
                        start_byte: 68,
                        end_byte: 81,
                        start_point: Point { row: 3, column: 12 },
                        end_point: Point { row: 3, column: 25 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Enum,
                    name: "Bar".into(),
                    range: tree_sitter::Range {
                        start_byte: 94,
                        end_byte: 104,
                        start_point: Point { row: 4, column: 12 },
                        end_point: Point { row: 4, column: 22 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Baz".into(),
                    range: tree_sitter::Range {
                        start_byte: 117,
                        end_byte: 173,
                        start_point: Point { row: 5, column: 12 },
                        end_point: Point { row: 7, column: 13 },
                    },
                },
                Symbol {
                    kind: SymbolKind::Message,
                    name: "Baz.Biz".into(),
                    range: tree_sitter::Range {
                        start_byte: 146,
                        end_byte: 159,
                        start_point: Point { row: 6, column: 16 },
                        end_point: Point { row: 6, column: 29 },
                    },
                }
            ]
        );
    }

    #[test]
    fn test_completion_context() {
        let _ = env_logger::builder().is_test(true).try_init();
        let (file, points) = cursors(
            r#"|
            synt|ax = "proto3";

            import "other|.proto";

            message Foo {
                uint32 i = 1;
                st|ring s = 2;
            }

            message Bar {
                message Buz {
                    b|
                }

                Buz b = 1;
                Ba|
            }

            |

            enum Enum {
                ENUM_ONE_TWO = |
                ENUM_TWO_|
                |
            }

            service Greeter {
              rpc| SayHello (Hello|Request) returns (Hello|Reply) {}
            }
            "#,
        );

        assert_eq!(
            points
                .iter()
                .map(|p| file.completion_context(p.row, p.column).unwrap())
                .collect::<Vec<Option<CompletionContext>>>(),
            vec![
                Some(CompletionContext::Keyword),
                None,
                Some(CompletionContext::Import),
                Some(CompletionContext::Message("Foo")),
                Some(CompletionContext::Message("Buz")),
                Some(CompletionContext::Message("Bar")),
                Some(CompletionContext::Keyword),
                None,
                Some(CompletionContext::Enum("Enum")),
                None,
                None,
                Some(CompletionContext::Rpc),
                Some(CompletionContext::Rpc),
            ]
        );
    }

    #[test]
    fn test_completion_context_syntax() {
        let _ = env_logger::builder().is_test(true).try_init();
        let (file, pos) = cursor("|");

        assert_eq!(
            file.completion_context(pos.row, pos.column).unwrap(),
            Some(CompletionContext::Syntax),
        );
    }

    #[test]
    fn test_completion_context_import() {
        let _ = env_logger::builder().is_test(true).try_init();

        let (file, pos) = cursor(
            r#"
            syntax = "proto3";
            import "|
            "#,
        );
        assert_eq!(
            file.completion_context(pos.row, pos.column).unwrap(),
            Some(CompletionContext::Import),
        );

        let (file, pos) = cursor(
            r#"
            syntax = "proto3";
            import "fo|o";
            "#,
        );
        assert_eq!(
            file.completion_context(pos.row, pos.column).unwrap(),
            Some(CompletionContext::Import),
        );

        let (file, pos) = cursor(
            r#"
            syntax = "proto3";
            import "foo.proto";
            import "|
            "#,
        );
        assert_eq!(
            file.completion_context(pos.row, pos.column).unwrap(),
            Some(CompletionContext::Import),
        );
    }

    #[test]
    fn test_completion_context_keyword() {
        let _ = env_logger::builder().is_test(true).try_init();

        fn test(lines: &[&str], expected: Option<CompletionContext>) {
            let text = lines.join("\n");
            let (file, point) = cursor(text.as_str());
            assert_eq!(
                file.completion_context(point.row, point.column).unwrap(),
                expected,
                "text:\n{}",
                text
            );
        }

        // first word of the line
        test(
            &[r#"syntax = "proto3";"#, "|", ""],
            Some(CompletionContext::Keyword),
        );
        test(
            &[r#"syntax = "proto3";"#, "mes|", ""],
            Some(CompletionContext::Keyword),
        );

        // following words of the line
        test(&[r#"syntax = "proto3";"#, "message |", ""], None);
        test(&[r#"syntax = "proto3";"#, "message Fo|", ""], None);
        test(&[r#"syntax = "proto3";"#, "message Foo |", ""], None);

        // new line
        test(
            &[r#"syntax = "proto3";"#, "message Foo{}", "mes|"],
            Some(CompletionContext::Keyword),
        );
    }

    #[test]
    fn test_completion_context_message() {
        let _ = env_logger::builder().is_test(true).try_init();

        fn test(lines: &[&str], expected: Option<CompletionContext>) {
            let text = format!("syntax = \"proto3\";\n{}\n", lines.join("\n"));
            let (file, point) = cursor(text.as_str());
            assert_eq!(
                file.completion_context(point.row, point.column).unwrap(),
                expected,
                "text:\n{}",
                text
            );
        }

        test(&["message Foo{ | }", ""], None);
        test(
            &["message Foo{ B| }", ""],
            Some(CompletionContext::Message("Foo")),
        );
        test(
            &["message Foo{ B|ar }", ""],
            Some(CompletionContext::Message("Foo")),
        );
        test(
            &["message Foo{ s|tring }", ""],
            Some(CompletionContext::Message("Foo")),
        );
        test(&["message Foo{ Bar | }"], None);
        test(&["message Foo{ Bar b| }"], None);
        test(&["message Foo{ Bar b|ar }"], None);
        test(&["message Foo{ Bar bar |}"], None);
        test(&["message Foo{ Bar bar | }"], None);
        test(&["message Foo{ Bar bar |= }"], None);
        test(
            &["message Foo{ Bar bar =| }"],
            Some(CompletionContext::FieldNumber(FieldNumberContext {
                used: vec![],
                reserved: vec![],
            })),
        );
        test(
            &["message Foo{ Bar bar = | }"],
            Some(CompletionContext::FieldNumber(FieldNumberContext {
                used: vec![],
                reserved: vec![],
            })),
        );
        test(
            &["message Foo{ Bar bar = |1 }"],
            Some(CompletionContext::FieldNumber(FieldNumberContext {
                used: vec![1],
                reserved: vec![],
            })),
        );
        test(
            &["message Foo{ Bar bar = 1| }"],
            Some(CompletionContext::FieldNumber(FieldNumberContext {
                used: vec![1],
                reserved: vec![],
            })),
        );
        test(
            &["message Foo{ Bar bar = 1|; }"],
            Some(CompletionContext::FieldNumber(FieldNumberContext {
                used: vec![1],
                reserved: vec![],
            })),
        );
        test(&["message Foo{ Bar bar = 1;| }"], None);
        test(&["message Foo{ oneof th| }"], None);
        // Enum values should NOT trigger field number completion
        test(&["enum Foo{ BAR = | }"], None);
        test(&["enum Foo{ BAR = |0 }"], None);
    }

    #[test]
    fn test_field_number_context() {
        let _ = env_logger::builder().is_test(true).try_init();

        fn next_free(lines: &[&str]) -> u32 {
            let text = format!("syntax = \"proto3\";\n{}\n", lines.join("\n"));
            let (file, point) = cursor(text.as_str());
            match file.completion_context(point.row, point.column).unwrap() {
                Some(CompletionContext::FieldNumber(ctx)) => ctx.next_free(),
                other => panic!("Expected FieldNumber, got {other:?}"),
            }
        }

        // Simple: next after existing fields (} on same line)
        assert_eq!(
            next_free(&["message Foo { int32 a = 1; int32 b = 2; int32 c = | }"]),
            3
        );
        // Cursor at end of line, } on next line
        assert_eq!(
            next_free(&["message Foo {", "  int32 a = 1;", "  int32 c = |", "}"]),
            2
        );
        // Gap: skips reserved single number
        assert_eq!(
            next_free(&["message Foo { reserved 2; int32 a = 1; int32 c = | }"]),
            3
        );
        // Gap: skips reserved range
        assert_eq!(
            next_free(&["message Foo { reserved 2 to 4; int32 a = 1; int32 c = | }"]),
            5
        );
        // Finds first gap between existing fields
        assert_eq!(
            next_free(&["message Foo { int32 a = 1; int32 c = 3; int32 d = | }"]),
            2
        );
        // Skips multiple reserved ranges and used numbers
        assert_eq!(
            next_free(&[
                "message Foo {",
                "  reserved 4, 6 to 8;",
                "  int32 a = 1;",
                "  int32 b = 2;",
                "  int32 c = 3;",
                "  string d = |",
                "}"
            ]),
            5
        );
    }

    #[test]
    fn test_completion_context_option() {
        let _ = env_logger::builder().is_test(true).try_init();

        fn test(lines: &[&str]) {
            let text = format!("syntax = \"proto3\";\n{}\n", lines.join("\n"));
            let (file, point) = cursor(text.as_str());
            assert_eq!(
                file.completion_context(point.row, point.column).unwrap(),
                Some(CompletionContext::Option),
                "text:\n{}",
                text
            );
        }

        test(&["option |"]);
        test(&["option java|"]);
        test(&["option |java"]);
        test(&["import \"blah.proto\";", "option |java"]);
        test(&["option |java", "import \"blah.proto\";"]);
        test(&["message Foo{}", "option |java"]);
        test(&["option |java", "message Foo{}"]);
    }

    #[test]
    fn test_type_at() {
        let _ = env_logger::builder().is_test(true).try_init();
        let (file, points) = cursors(
            r#"
            synt|ax = "proto3";

            import "other|.proto";

            message F|oo {
                st|ring s = 1;
                int|32 i = 2;
                B|ar |b = 3;
                Baz.|Buz b = |4;
                foo.bar|.|Buz.Boz g = 5|;
            }

            service G|reeter {
              rpc SayH|ello (Hel|loRequest) retu|rns (Hell|oReply) {}
            }
            "#,
        );

        assert_eq!(
            points
                .iter()
                .map(|p| file.type_at(p.row, p.column))
                .collect::<Vec<Option<GotoContext>>>(),
            vec![
                None,
                Some(GotoContext::Import("other.proto")),
                Some(GotoContext::Type(GotoTypeContext {
                    name: "Foo",
                    parent: None
                })),
                None,
                None,
                Some(GotoContext::Type(GotoTypeContext {
                    name: "Bar",
                    parent: Some("Foo".into()),
                })),
                None,
                Some(GotoContext::Type(GotoTypeContext {
                    name: "Baz.Buz",
                    parent: Some("Foo".into()),
                })),
                None,
                Some(GotoContext::Type(GotoTypeContext {
                    name: "foo.bar.Buz.Boz",
                    parent: Some("Foo".into()),
                })),
                Some(GotoContext::Type(GotoTypeContext {
                    name: "foo.bar.Buz.Boz",
                    parent: Some("Foo".into()),
                })),
                None,
                None,
                None,
                Some(GotoContext::Type(GotoTypeContext {
                    name: "HelloRequest",
                    parent: None,
                })),
                None,
                Some(GotoContext::Type(GotoTypeContext {
                    name: "HelloReply",
                    parent: None,
                })),
            ]
        );
    }

    #[test]
    fn test_import_references() {
        let _ = env_logger::builder().is_test(true).try_init();
        let file = File::new(
            [
                "syntax = \"proto3\";",
                "package thing;",
                "import \"foo.proto\";",
                "import \"bar.proto\";",
                "message Foo {",
                "    Bar b = 1;",
                "    Biz.Buz bb = 2;",
                "    buf.Buf buf = 3;",
                "}",
                "",
            ]
            .join("\n"),
        )
        .unwrap();

        assert_eq!(
            file.import_references("foo.proto"),
            vec![tree_sitter::Range {
                start_byte: 41,
                end_byte: 52,
                start_point: Point { row: 2, column: 7 },
                end_point: Point { row: 2, column: 18 }
            }]
        );

        assert_eq!(
            file.import_references("bar.proto"),
            vec![tree_sitter::Range {
                start_byte: 61,
                end_byte: 72,
                start_point: Point { row: 3, column: 7 },
                end_point: Point { row: 3, column: 18 }
            }]
        );

        assert_eq!(file.import_references("baz.proto"), vec![]);
    }

    #[test]
    fn test_type_references() {
        let _ = env_logger::builder().is_test(true).try_init();
        let file = File::new(
            [
                "syntax = \"proto3\";",
                "package thing;",
                "import \"foo.proto\";",
                "import \"bar.proto\";",
                "message Foo {",
                "    Bar b = 1;",
                "    Biz.Buz bb = 2;",
                "    buf.Buf buf = 3;",
                "}",
                "",
            ]
            .join("\n"),
        )
        .unwrap();

        assert_eq!(
            file.type_references(
                None,
                &GotoTypeContext {
                    name: "Bar",
                    parent: None
                }
            ),
            vec![tree_sitter::Range {
                start_byte: 92,
                end_byte: 95,
                start_point: Point { row: 5, column: 4 },
                end_point: Point { row: 5, column: 7 }
            }]
        );

        assert_eq!(
            file.type_references(
                Some("thing"),
                &GotoTypeContext {
                    name: "Biz.Buz",
                    parent: None
                }
            ),
            vec![tree_sitter::Range {
                start_byte: 107,
                end_byte: 114,
                start_point: Point { row: 6, column: 4 },
                end_point: Point { row: 6, column: 11 }
            }]
        );

        assert_eq!(
            file.type_references(
                Some("buf"),
                &GotoTypeContext {
                    name: "Buf",
                    parent: None
                }
            ),
            vec![tree_sitter::Range {
                start_byte: 127,
                end_byte: 134,
                start_point: Point { row: 7, column: 4 },
                end_point: Point { row: 7, column: 11 }
            }]
        );

        assert_eq!(
            file.type_references(
                Some("thing"),
                &GotoTypeContext {
                    name: "Buf",
                    parent: None
                }
            ),
            vec![]
        );

        assert_eq!(
            file.type_references(
                Some("thing"),
                &GotoTypeContext {
                    name: "buf",
                    parent: None
                }
            ),
            vec![]
        );
    }

    #[test]
    fn test_relative_name() {
        assert_eq!(relative_name("Foo", "Biz.Bar.Baz"), "Biz.Bar.Baz");
        assert_eq!(relative_name("Foo.Bar", "Biz.Bar.Baz"), "Biz.Bar.Baz");
        assert_eq!(relative_name("Foo.Bar.Baz", "Biz.Bar.Baz"), "Biz.Bar.Baz");

        assert_eq!(relative_name("Foo.Bar.Baz", "Foo.Bar.Baz"), "Baz");
        assert_eq!(relative_name("Foo.Bar.Baz", "Foo.Bar"), "Bar");
        assert_eq!(relative_name("Foo.Bar.Baz", "Foo"), "Foo");

        assert_eq!(relative_name("Foo.Bar", "Foo.Bar.Baz"), "Baz");
        assert_eq!(relative_name("Foo.Bar", "Foo.Bar"), "Bar");
        assert_eq!(relative_name("Foo.Bar", "Foo"), "Foo");

        assert_eq!(relative_name("Foo", "Foo.Bar.Baz"), "Bar.Baz");
        assert_eq!(relative_name("Foo", "Foo.Bar"), "Bar");
        assert_eq!(relative_name("Foo", "Foo"), "Foo");
    }

    #[test]
    fn test_edit() {
        let text = "yn";
        let mut file = File::new(text.into()).unwrap();
        assert_eq!(file.text, text);

        let change = |(start_line, start_char), (end_line, end_char), text: &str| {
            lsp_types::TextDocumentContentChangeEvent {
                range: Some(lsp_types::Range {
                    start: lsp_types::Position {
                        line: start_line,
                        character: start_char,
                    },
                    end: lsp_types::Position {
                        line: end_line,
                        character: end_char,
                    },
                }),
                range_length: None,
                text: text.into(),
            }
        };

        file.edit(vec![]).unwrap();
        assert_eq!(file.text, text);

        file.edit(vec![change((0, 0), (0, 0), "s")]).unwrap();
        assert_eq!(file.text, "syn");

        file.edit(vec![change((0, 3), (0, 3), "tax = \"proto2\";\n")])
            .unwrap();
        assert_eq!(file.text, "syntax = \"proto2\";\n");

        file.edit(vec![change((0, 10), (0, 16), "proto3")]).unwrap();
        assert_eq!(file.text, "syntax = \"proto3\";\n");

        file.edit(vec![change((1, 0), (1, 0), "message Foo {}\n")])
            .unwrap();
        assert_eq!(file.text, "syntax = \"proto3\";\nmessage Foo {}\n");

        file.edit(vec![change((1, 13), (1, 14), "\n\n}")]).unwrap();
        assert_eq!(file.text, "syntax = \"proto3\";\nmessage Foo {\n\n}\n");

        file.edit(vec![change(
            (2, 0),
            (2, 0),
            "uint32 i = 1;\nstring s = 2;\nbytes b = 3;",
        )])
        .unwrap();
        assert_eq!(
            file.text,
            [
                "syntax = \"proto3\";",
                "message Foo {",
                "uint32 i = 1;",
                "string s = 2;",
                "bytes b = 3;",
                "}",
                ""
            ]
            .join("\n")
        );

        file.edit(vec![change(
            (2, 0),
            (5, 0),
            "uint32 i = 2;\nstring s = 3;\nbytes b = 4;\n",
        )])
        .unwrap();
        assert_eq!(
            file.text,
            [
                "syntax = \"proto3\";",
                "message Foo {",
                "uint32 i = 2;",
                "string s = 3;",
                "bytes b = 4;",
                "}",
                ""
            ]
            .join("\n")
        );

        file.edit(vec![change((2, 4), (3, 8), "64 u = 2;\nstring str")])
            .unwrap();
        assert_eq!(
            file.text,
            [
                "syntax = \"proto3\";",
                "message Foo {",
                "uint64 u = 2;",
                "string str = 3;",
                "bytes b = 4;",
                "}",
                ""
            ]
            .join("\n")
        );

        file.edit(vec![change((3, 13), (4, 0), "5;\n")]).unwrap();
        assert_eq!(
            file.text,
            [
                "syntax = \"proto3\";",
                "message Foo {",
                "uint64 u = 2;",
                "string str = 5;",
                "bytes b = 4;",
                "}",
                ""
            ]
            .join("\n")
        );
    }

    #[test]
    fn test_edit_unicode() {
        let text = [
            "syntax = \"proto3\";",
            "import \"examp𐐀e.proto\";",
            "import \"other.proto\";",
            "",
        ]
        .join("\n");
        let mut file = File::new(text.clone()).unwrap();
        assert_eq!(file.text, text);

        let change = |(start_line, start_char), (end_line, end_char), text: &str| {
            lsp_types::TextDocumentContentChangeEvent {
                range: Some(lsp_types::Range {
                    start: lsp_types::Position {
                        line: start_line,
                        character: start_char,
                    },
                    end: lsp_types::Position {
                        line: end_line,
                        character: end_char,
                    },
                }),
                range_length: None,
                text: text.into(),
            }
        };

        // 𐐀 (U+10400) is 2 UTF-16 code units, so the 'e' after it is at UTF-16 position 15,
        // and the '.' after that is at UTF-16 position 16.
        file.edit(vec![change((1, 8), (1, 16), "thing")]).unwrap();
        assert_eq!(
            file.text,
            [
                "syntax = \"proto3\";",
                "import \"thing.proto\";",
                "import \"other.proto\";",
                "",
            ]
            .join("\n")
        );
    }
}