tinymist_analysis/syntax/
matcher.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
//! Convenient utilities to match syntax structures of code.
//! - Iterators/Finders to traverse nodes.
//! - Predicates to check nodes' properties.
//! - Classifiers to check nodes' syntax.
//!
//! ## Classifiers of syntax structures
//!
//! A node can have a quadruple to describe its syntax:
//!
//! ```text
//! (InterpretMode, SurroundingSyntax/SyntaxContext, DefClass/SyntaxClass, SyntaxNode)
//! ```
//!
//! Among them, [`InterpretMode`], [`SurroundingSyntax`], and [`SyntaxContext`]
//! describes outer syntax. [`DefClass`], [`SyntaxClass`] and
//! [`typst::syntax::SyntaxNode`] describes inner syntax.
//!
//! - [`typst::syntax::SyntaxNode`]: Its contextual version is
//!   [`typst::syntax::LinkedNode`], containing AST information, like inner text
//!   and [`SyntaxKind`], on the position.
//! - [`SyntaxClass`]: Provided by [`classify_syntax`], it describes the
//!   context-free syntax of the node that are more suitable for IDE operations.
//!   For example, it identifies users' half-typed syntax like half-completed
//!   labels and dot accesses.
//! - [`DefClass`]: Provided by [`classify_def`], it describes the definition
//!   class of the node at the position. The difference between `SyntaxClass`
//!   and `DefClass` is that the latter matcher will skip the nodes that do not
//!   define a definition.
//! - [`SyntaxContext`]: Provided by [`classify_context`], it describes the
//!   outer syntax of the node that are more suitable for IDE operations. For
//!   example, it identifies the context of a cursor on the comma in a function
//!   call.
//! - [`SurroundingSyntax`]: Provided by [`surrounding_syntax`], it describes
//!   the surrounding syntax of the node that are more suitable for IDE
//!   operations. The difference between `SyntaxContext` and `SurroundingSyntax`
//!   is that the former is more specific and the latter is more general can be
//!   used for filtering customized snippets.
//! - [`InterpretMode`]: Provided by [`interpret_mode_at`], it describes the how
//!   an interpreter should interpret the code at the position.
//!
//! Some examples of the quadruple (the cursor is marked by `|`):
//!
//! ```text
//! #(x|);
//!    ^ SyntaxContext::Paren, SyntaxClass::Normal(SyntaxKind::Ident)
//! #(x,|);
//!     ^ SyntaxContext::Element, SyntaxClass::Normal(SyntaxKind::Array)
//! #f(x,|);
//!      ^ SyntaxContext::Arg, SyntaxClass::Normal(SyntaxKind::FuncCall)
//! ```
//!
//! ```text
//! #show raw|: |it => it|
//!          ^ SurroundingSyntax::Selector
//!             ^ SurroundingSyntax::ShowTransform
//!                      ^ SurroundingSyntax::Regular
//! ```

use serde::{Deserialize, Serialize};
use tinymist_world::debug_loc::SourceSpanOffset;
use typst::syntax::Span;

use crate::prelude::*;

/// Returns the ancestor iterator of the given node.
pub fn node_ancestors<'a, 'b>(
    node: &'b LinkedNode<'a>,
) -> impl Iterator<Item = &'b LinkedNode<'a>> {
    std::iter::successors(Some(node), |node| node.parent())
}

/// Finds the first ancestor node that is an expression.
pub fn first_ancestor_expr(node: LinkedNode) -> Option<LinkedNode> {
    node_ancestors(&node)
        .find(|n| n.is::<ast::Expr>())
        .map(|mut node| {
            while matches!(node.kind(), SyntaxKind::Ident | SyntaxKind::MathIdent) {
                let Some(parent) = node.parent() else {
                    return node;
                };

                let Some(field_access) = parent.cast::<ast::FieldAccess>() else {
                    return node;
                };

                let dot = parent
                    .children()
                    .find(|n| matches!(n.kind(), SyntaxKind::Dot));

                // Since typst matches `field()` by `case_last_match`, when the field access
                // `x.` (`Ident(x).Error("")`), it will match the `x` as the
                // field. We need to check dot position to filter out such cases.
                if dot.is_some_and(|dot| {
                    dot.offset() <= node.offset() && field_access.field().span() == node.span()
                }) {
                    node = parent;
                } else {
                    return node;
                }
            }

            node
        })
        .cloned()
}

/// A node that is an ancestor of the given node or the previous sibling
/// of some ancestor.
pub enum PreviousItem<'a> {
    /// When the iterator is crossing an ancesstor node.
    Parent(&'a LinkedNode<'a>, &'a LinkedNode<'a>),
    /// When the iterator is on a sibling node of some ancestor.
    Sibling(&'a LinkedNode<'a>),
}

impl<'a> PreviousItem<'a> {
    /// Gets the underlying [`LinkedNode`] of the item.
    pub fn node(&self) -> &'a LinkedNode<'a> {
        match self {
            PreviousItem::Sibling(node) => node,
            PreviousItem::Parent(node, _) => node,
        }
    }
}

/// Finds the previous items (in the scope) starting from the given position
/// inclusively. See [`PreviousItem`] for the possible items.
pub fn previous_items<T>(
    node: LinkedNode,
    mut recv: impl FnMut(PreviousItem) -> Option<T>,
) -> Option<T> {
    let mut ancestor = Some(node);
    while let Some(node) = &ancestor {
        let mut sibling = Some(node.clone());
        while let Some(node) = &sibling {
            if let Some(v) = recv(PreviousItem::Sibling(node)) {
                return Some(v);
            }

            sibling = node.prev_sibling();
        }

        if let Some(parent) = node.parent() {
            if let Some(v) = recv(PreviousItem::Parent(parent, node)) {
                return Some(v);
            }

            ancestor = Some(parent.clone());
            continue;
        }

        break;
    }

    None
}

/// A declaration that is an ancestor of the given node or the previous sibling
/// of some ancestor.
pub enum PreviousDecl<'a> {
    /// An declaration having an identifier.
    ///
    /// ## Example
    ///
    /// The `x` in the following code:
    ///
    /// ```typst
    /// #let x = 1;
    /// ```
    Ident(ast::Ident<'a>),
    /// An declaration yielding from an import source.
    ///
    /// ## Example
    ///
    /// The `x` in the following code:
    ///
    /// ```typst
    /// #import "path.typ": x;
    /// ```
    ImportSource(ast::Expr<'a>),
    /// A wildcard import that possibly containing visible declarations.
    ///
    /// ## Example
    ///
    /// The following import is matched:
    ///
    /// ```typst
    /// #import "path.typ": *;
    /// ```
    ImportAll(ast::ModuleImport<'a>),
}

/// Finds the previous declarations starting from the given position. It checks
/// [`PreviousItem`] and returns the found declarations.
pub fn previous_decls<T>(
    node: LinkedNode,
    mut recv: impl FnMut(PreviousDecl) -> Option<T>,
) -> Option<T> {
    previous_items(node, |item| {
        match (&item, item.node().cast::<ast::Expr>()?) {
            (PreviousItem::Sibling(..), ast::Expr::Let(lb)) => {
                for ident in lb.kind().bindings() {
                    if let Some(t) = recv(PreviousDecl::Ident(ident)) {
                        return Some(t);
                    }
                }
            }
            (PreviousItem::Sibling(..), ast::Expr::Import(import)) => {
                // import items
                match import.imports() {
                    Some(ast::Imports::Wildcard) => {
                        if let Some(t) = recv(PreviousDecl::ImportAll(import)) {
                            return Some(t);
                        }
                    }
                    Some(ast::Imports::Items(items)) => {
                        for item in items.iter() {
                            if let Some(t) = recv(PreviousDecl::Ident(item.bound_name())) {
                                return Some(t);
                            }
                        }
                    }
                    _ => {}
                }

                // import it self
                if let Some(new_name) = import.new_name() {
                    if let Some(t) = recv(PreviousDecl::Ident(new_name)) {
                        return Some(t);
                    }
                } else if import.imports().is_none() {
                    if let Some(t) = recv(PreviousDecl::ImportSource(import.source())) {
                        return Some(t);
                    }
                }
            }
            (PreviousItem::Parent(parent, child), ast::Expr::For(for_expr)) => {
                let body = parent.find(for_expr.body().span());
                let in_body = body.is_some_and(|n| n.find(child.span()).is_some());
                if !in_body {
                    return None;
                }

                for ident in for_expr.pattern().bindings() {
                    if let Some(t) = recv(PreviousDecl::Ident(ident)) {
                        return Some(t);
                    }
                }
            }
            (PreviousItem::Parent(parent, child), ast::Expr::Closure(closure)) => {
                let body = parent.find(closure.body().span());
                let in_body = body.is_some_and(|n| n.find(child.span()).is_some());
                if !in_body {
                    return None;
                }

                for param in closure.params().children() {
                    match param {
                        ast::Param::Pos(pos) => {
                            for ident in pos.bindings() {
                                if let Some(t) = recv(PreviousDecl::Ident(ident)) {
                                    return Some(t);
                                }
                            }
                        }
                        ast::Param::Named(named) => {
                            if let Some(t) = recv(PreviousDecl::Ident(named.name())) {
                                return Some(t);
                            }
                        }
                        ast::Param::Spread(spread) => {
                            if let Some(sink_ident) = spread.sink_ident() {
                                if let Some(t) = recv(PreviousDecl::Ident(sink_ident)) {
                                    return Some(t);
                                }
                            }
                        }
                    }
                }
            }
            _ => {}
        };
        None
    })
}

/// Whether the node can be recognized as a mark.
pub fn is_mark(sk: SyntaxKind) -> bool {
    use SyntaxKind::*;
    #[allow(clippy::match_like_matches_macro)]
    match sk {
        MathAlignPoint | Plus | Minus | Dot | Dots | Arrow | Not | And | Or => true,
        Eq | EqEq | ExclEq | Lt | LtEq | Gt | GtEq | PlusEq | HyphEq | StarEq | SlashEq => true,
        LeftBrace | RightBrace | LeftBracket | RightBracket | LeftParen | RightParen => true,
        Slash | Hat | Comma | Semicolon | Colon | Hash => true,
        _ => false,
    }
}

/// Whether the node can be recognized as an identifier.
pub fn is_ident_like(node: &SyntaxNode) -> bool {
    fn can_be_ident(node: &SyntaxNode) -> bool {
        typst::syntax::is_ident(node.text())
    }

    use SyntaxKind::*;
    let kind = node.kind();
    matches!(kind, Ident | MathIdent | Underscore)
        || (matches!(kind, Error) && can_be_ident(node))
        || kind.is_keyword()
}

/// A mode in which a text document is interpreted.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, strum::EnumIter)]
#[serde(rename_all = "camelCase")]
pub enum InterpretMode {
    /// The position is in a comment.
    Comment,
    /// The position is in a string.
    String,
    /// The position is in a raw.
    Raw,
    /// The position is in a markup block.
    Markup,
    /// The position is in a code block.
    Code,
    /// The position is in a math equation.
    Math,
}

/// Determine the interpretation mode at the given position (context-sensitive).
pub fn interpret_mode_at(mut leaf: Option<&LinkedNode>) -> InterpretMode {
    loop {
        crate::log_debug_ct!("leaf for mode: {leaf:?}");
        if let Some(t) = leaf {
            if let Some(mode) = interpret_mode_at_kind(t.kind()) {
                break mode;
            }

            if !t.kind().is_trivia() && {
                // Previous leaf is hash
                t.prev_leaf().is_some_and(|n| n.kind() == SyntaxKind::Hash)
            } {
                return InterpretMode::Code;
            }

            leaf = t.parent();
        } else {
            break InterpretMode::Markup;
        }
    }
}

/// Determine the interpretation mode at the given kind (context-free).
pub(crate) fn interpret_mode_at_kind(kind: SyntaxKind) -> Option<InterpretMode> {
    use SyntaxKind::*;
    Some(match kind {
        LineComment | BlockComment | Shebang => InterpretMode::Comment,
        Raw => InterpretMode::Raw,
        Str => InterpretMode::String,
        CodeBlock | Code => InterpretMode::Code,
        ContentBlock | Markup => InterpretMode::Markup,
        Equation | Math => InterpretMode::Math,
        Hash => InterpretMode::Code,
        Label | Text | Ident | Args | FuncCall | FieldAccess | Bool | Int | Float | Numeric
        | Space | Linebreak | Parbreak | Escape | Shorthand | SmartQuote | RawLang | RawDelim
        | RawTrimmed | LeftBrace | RightBrace | LeftBracket | RightBracket | LeftParen
        | RightParen | Comma | Semicolon | Colon | Star | Underscore | Dollar | Plus | Minus
        | Slash | Hat | Prime | Dot | Eq | EqEq | ExclEq | Lt | LtEq | Gt | GtEq | PlusEq
        | HyphEq | StarEq | SlashEq | Dots | Arrow | Root | Not | And | Or | None | Auto | As
        | Named | Keyed | Spread | Error | End => return Option::None,
        Strong | Emph | Link | Ref | RefMarker | Heading | HeadingMarker | ListItem
        | ListMarker | EnumItem | EnumMarker | TermItem | TermMarker => InterpretMode::Markup,
        MathIdent | MathAlignPoint | MathDelimited | MathAttach | MathPrimes | MathFrac
        | MathRoot | MathShorthand | MathText => InterpretMode::Math,
        Let | Set | Show | Context | If | Else | For | In | While | Break | Continue | Return
        | Import | Include | Closure | Params | LetBinding | SetRule | ShowRule | Contextual
        | Conditional | WhileLoop | ForLoop | LoopBreak | ModuleImport | ImportItems
        | ImportItemPath | RenamedImportItem | ModuleInclude | LoopContinue | FuncReturn
        | Unary | Binary | Parenthesized | Dict | Array | Destructuring | DestructAssignment => {
            InterpretMode::Code
        }
    })
}

/// Classes of def items that can be operated on by IDE functionality.
#[derive(Debug, Clone)]
pub enum DefClass<'a> {
    /// A let binding item.
    Let(LinkedNode<'a>),
    /// A module import item.
    Import(LinkedNode<'a>),
}

impl DefClass<'_> {
    /// Gets the node of the def class.
    pub fn node(&self) -> &LinkedNode {
        match self {
            DefClass::Let(node) => node,
            DefClass::Import(node) => node,
        }
    }

    /// Gets the name node of the def class.
    pub fn name(&self) -> Option<LinkedNode> {
        match self {
            DefClass::Let(node) => {
                let lb: ast::LetBinding<'_> = node.cast()?;
                let names = match lb.kind() {
                    ast::LetBindingKind::Closure(name) => node.find(name.span())?,
                    ast::LetBindingKind::Normal(ast::Pattern::Normal(name)) => {
                        node.find(name.span())?
                    }
                    _ => return None,
                };

                Some(names)
            }
            DefClass::Import(_node) => {
                // let ident = node.cast::<ast::ImportItem>()?;
                // Some(ident.span().into())
                // todo: implement this
                None
            }
        }
    }

    /// Gets the name's range in code of the def class.
    pub fn name_range(&self) -> Option<Range<usize>> {
        self.name().map(|node| node.range())
    }
}

// todo: whether we should distinguish between strict and loose def classes
/// Classifies a definition loosely.
pub fn classify_def_loosely(node: LinkedNode) -> Option<DefClass<'_>> {
    classify_def_(node, false)
}

/// Classifies a definition strictly.
pub fn classify_def(node: LinkedNode) -> Option<DefClass<'_>> {
    classify_def_(node, true)
}

/// The internal implementation of classifying a definition.
fn classify_def_(node: LinkedNode, strict: bool) -> Option<DefClass<'_>> {
    let mut ancestor = node;
    if ancestor.kind().is_trivia() || is_mark(ancestor.kind()) {
        ancestor = ancestor.prev_sibling()?;
    }

    while !ancestor.is::<ast::Expr>() {
        ancestor = ancestor.parent()?.clone();
    }
    crate::log_debug_ct!("ancestor: {ancestor:?}");
    let adjusted = adjust_expr(ancestor)?;
    crate::log_debug_ct!("adjust_expr: {adjusted:?}");

    let may_ident = adjusted.cast::<ast::Expr>()?;
    if strict && !may_ident.hash() && !matches!(may_ident, ast::Expr::MathIdent(_)) {
        return None;
    }

    let expr = may_ident;
    Some(match expr {
        // todo: label, reference
        // todo: include
        ast::Expr::FuncCall(..) => return None,
        ast::Expr::Set(..) => return None,
        ast::Expr::Let(..) => DefClass::Let(adjusted),
        ast::Expr::Import(..) => DefClass::Import(adjusted),
        // todo: parameter
        ast::Expr::Ident(..)
        | ast::Expr::MathIdent(..)
        | ast::Expr::FieldAccess(..)
        | ast::Expr::Closure(..) => {
            let mut ancestor = adjusted;
            while !ancestor.is::<ast::LetBinding>() {
                ancestor = ancestor.parent()?.clone();
            }

            DefClass::Let(ancestor)
        }
        ast::Expr::Str(..) => {
            let parent = adjusted.parent()?;
            if parent.kind() != SyntaxKind::ModuleImport {
                return None;
            }

            DefClass::Import(parent.clone())
        }
        _ if expr.hash() => return None,
        _ => {
            crate::log_debug_ct!("unsupported kind {:?}", adjusted.kind());
            return None;
        }
    })
}

/// Adjusts an expression node to a more suitable one for classification.
/// It is not formal, but the following cases are forbidden:
/// - Parenthesized expression.
/// - Identifier on the right side of a dot operator (field access).
fn adjust_expr(mut node: LinkedNode) -> Option<LinkedNode> {
    while let Some(paren_expr) = node.cast::<ast::Parenthesized>() {
        node = node.find(paren_expr.expr().span())?;
    }
    if let Some(parent) = node.parent() {
        if let Some(field_access) = parent.cast::<ast::FieldAccess>() {
            if node.span() == field_access.field().span() {
                return Some(parent.clone());
            }
        }
    }
    Some(node)
}

/// Classes of field syntax that can be operated on by IDE functionality.
#[derive(Debug, Clone)]
pub enum FieldClass<'a> {
    /// A field node.
    ///
    /// ## Example
    ///
    /// The `x` in the following code:
    ///
    /// ```typst
    /// #a.x
    /// ```
    Field(LinkedNode<'a>),

    /// A dot suffix missing a field.
    ///
    /// ## Example
    ///
    /// The `.` in the following code:
    ///
    /// ```typst
    /// #a.
    /// ```
    DotSuffix(SourceSpanOffset),
}

impl FieldClass<'_> {
    /// Gets the node of the field class.
    pub fn offset(&self, source: &Source) -> Option<usize> {
        Some(match self {
            Self::Field(node) => node.offset(),
            Self::DotSuffix(span_offset) => {
                source.find(span_offset.span)?.offset() + span_offset.offset
            }
        })
    }
}

/// Classes of variable (access) syntax that can be operated on by IDE
/// functionality.
#[derive(Debug, Clone)]
pub enum VarClass<'a> {
    /// An identifier expression.
    Ident(LinkedNode<'a>),
    /// A field access expression.
    FieldAccess(LinkedNode<'a>),
    /// A dot access expression, for example, `#a.|`, `$a.|$`, or `x.|.y`.
    /// Note the cursor of the last example is on the middle of the spread
    /// operator.
    DotAccess(LinkedNode<'a>),
}

impl<'a> VarClass<'a> {
    /// Gets the node of the var (access) class.
    pub fn node(&self) -> &LinkedNode<'a> {
        match self {
            Self::Ident(node) | Self::FieldAccess(node) | Self::DotAccess(node) => node,
        }
    }

    /// Gets the accessed node of the var (access) class.
    pub fn accessed_node(&self) -> Option<LinkedNode<'a>> {
        Some(match self {
            Self::Ident(node) => node.clone(),
            Self::FieldAccess(node) => {
                let field_access = node.cast::<ast::FieldAccess>()?;
                node.find(field_access.target().span())?
            }
            Self::DotAccess(node) => node.clone(),
        })
    }

    /// Gets the accessing field of the var (access) class.
    pub fn accessing_field(&self) -> Option<FieldClass<'a>> {
        match self {
            Self::FieldAccess(node) => {
                let dot = node
                    .children()
                    .find(|n| matches!(n.kind(), SyntaxKind::Dot))?;
                let mut iter_after_dot =
                    node.children().skip_while(|n| n.kind() != SyntaxKind::Dot);
                let ident = iter_after_dot.find(|n| {
                    matches!(
                        n.kind(),
                        SyntaxKind::Ident | SyntaxKind::MathIdent | SyntaxKind::Error
                    )
                });

                let ident_case = ident.map(|ident| {
                    if ident.text().is_empty() {
                        FieldClass::DotSuffix(SourceSpanOffset {
                            span: ident.span(),
                            offset: 0,
                        })
                    } else {
                        FieldClass::Field(ident)
                    }
                });

                ident_case.or_else(|| {
                    Some(FieldClass::DotSuffix(SourceSpanOffset {
                        span: dot.span(),
                        offset: 1,
                    }))
                })
            }
            Self::DotAccess(node) => Some(FieldClass::DotSuffix(SourceSpanOffset {
                span: node.span(),
                offset: node.range().len() + 1,
            })),
            Self::Ident(_) => None,
        }
    }
}

/// Classes of syntax that can be operated on by IDE functionality.
#[derive(Debug, Clone)]
pub enum SyntaxClass<'a> {
    /// A variable access expression.
    ///
    /// It can be either an identifier or a field access.
    VarAccess(VarClass<'a>),
    /// A (content) label expression.
    Label {
        /// The node of the label.
        node: LinkedNode<'a>,
        /// Whether the label is converted from an error node.
        is_error: bool,
    },
    /// A (content) reference expression.
    Ref(LinkedNode<'a>),
    /// A callee expression.
    Callee(LinkedNode<'a>),
    /// An import path expression.
    ImportPath(LinkedNode<'a>),
    /// An include path expression.
    IncludePath(LinkedNode<'a>),
    /// Rest kind of **expressions**.
    Normal(SyntaxKind, LinkedNode<'a>),
}

impl<'a> SyntaxClass<'a> {
    /// Creates a label syntax class.
    pub fn label(node: LinkedNode<'a>) -> Self {
        Self::Label {
            node,
            is_error: false,
        }
    }

    /// Creates an error label syntax class.
    pub fn error_as_label(node: LinkedNode<'a>) -> Self {
        Self::Label {
            node,
            is_error: true,
        }
    }

    /// Gets the node of the syntax class.
    pub fn node(&self) -> &LinkedNode<'a> {
        match self {
            SyntaxClass::VarAccess(cls) => cls.node(),
            SyntaxClass::Label { node, .. }
            | SyntaxClass::Ref(node)
            | SyntaxClass::Callee(node)
            | SyntaxClass::ImportPath(node)
            | SyntaxClass::IncludePath(node)
            | SyntaxClass::Normal(_, node) => node,
        }
    }

    /// Gets the content offset at which the completion should be triggered.
    pub fn complete_offset(&self) -> Option<usize> {
        match self {
            // `<label`
            //   ^ node.offset() + 1
            SyntaxClass::Label { node, .. } => Some(node.offset() + 1),
            _ => None,
        }
    }
}

/// Classifies node's syntax (inner syntax) that can be operated on by IDE
/// functionality.
pub fn classify_syntax(node: LinkedNode, cursor: usize) -> Option<SyntaxClass<'_>> {
    if matches!(node.kind(), SyntaxKind::Error) && node.text().starts_with('<') {
        return Some(SyntaxClass::error_as_label(node));
    }

    /// Skips trivia nodes that are on the same line as the cursor.
    fn can_skip_trivia(node: &LinkedNode, cursor: usize) -> bool {
        // A non-trivia node is our target so we stop at it.
        if !node.kind().is_trivia() || !node.parent_kind().is_some_and(possible_in_code_trivia) {
            return false;
        }

        // Gets the trivia text before the cursor.
        let previous_text = node.text().as_bytes();
        let previous_text = if node.range().contains(&cursor) {
            &previous_text[..cursor - node.offset()]
        } else {
            previous_text
        };

        // The deref target should be on the same line as the cursor.
        // Assuming the underlying text is utf-8 encoded, we can check for newlines by
        // looking for b'\n'.
        // todo: if we are in markup mode, we should check if we are at start of node
        !previous_text.contains(&b'\n')
    }

    // Moves to the first non-trivia node before the cursor.
    let mut node = node;
    if can_skip_trivia(&node, cursor) {
        node = node.prev_sibling()?;
    }

    /// Matches complete or incomplete dot accesses in code, math, and markup
    /// mode.
    ///
    /// When in markup mode, the dot access is valid if the dot is after a hash
    /// expression.
    fn classify_dot_access<'a>(node: &LinkedNode<'a>) -> Option<SyntaxClass<'a>> {
        let prev_leaf = node.prev_leaf();
        let mode = interpret_mode_at(Some(node));

        // Don't match `$ .| $`
        if matches!(mode, InterpretMode::Markup | InterpretMode::Math)
            && prev_leaf
                .as_ref()
                .is_some_and(|leaf| leaf.range().end < node.offset())
        {
            return None;
        }

        if matches!(mode, InterpretMode::Math)
            && prev_leaf.as_ref().is_some_and(|leaf| {
                // Don't match `$ a.| $` or `$.| $`
                node_ancestors(leaf)
                    .find(|t| matches!(t.kind(), SyntaxKind::Equation))
                    .is_some_and(|parent| parent.offset() == leaf.offset())
            })
        {
            return None;
        }

        let dot_target = prev_leaf.and_then(first_ancestor_expr)?;

        if matches!(mode, InterpretMode::Math | InterpretMode::Code) || {
            matches!(mode, InterpretMode::Markup)
                && (matches!(
                    dot_target.kind(),
                    SyntaxKind::Ident
                        | SyntaxKind::MathIdent
                        | SyntaxKind::FieldAccess
                        | SyntaxKind::FuncCall
                ) || (matches!(
                    dot_target.prev_leaf().as_deref().map(SyntaxNode::kind),
                    Some(SyntaxKind::Hash)
                )))
        } {
            return Some(SyntaxClass::VarAccess(VarClass::DotAccess(dot_target)));
        }

        None
    }

    if node.offset() + 1 == cursor && {
        // Check if the cursor is exactly after single dot.
        matches!(node.kind(), SyntaxKind::Dot)
            || (matches!(
                node.kind(),
                SyntaxKind::Text | SyntaxKind::MathText | SyntaxKind::Error
            ) && node.text().starts_with("."))
    } {
        if let Some(dot_access) = classify_dot_access(&node) {
            return Some(dot_access);
        }
    }

    if node.offset() + 1 == cursor
        && matches!(node.kind(), SyntaxKind::Dots)
        && matches!(node.parent_kind(), Some(SyntaxKind::Spread))
    {
        if let Some(dot_access) = classify_dot_access(&node) {
            return Some(dot_access);
        }
    }

    // todo: check if we can remove Text here
    if matches!(node.kind(), SyntaxKind::Text | SyntaxKind::MathText) {
        let mode = interpret_mode_at(Some(&node));
        if matches!(mode, InterpretMode::Math) && is_ident_like(&node) {
            return Some(SyntaxClass::VarAccess(VarClass::Ident(node)));
        }
    }

    // Move to the first ancestor that is an expression.
    let ancestor = first_ancestor_expr(node)?;
    crate::log_debug_ct!("first_ancestor_expr: {ancestor:?}");

    // Unwrap all parentheses to get the actual expression.
    let adjusted = adjust_expr(ancestor)?;
    crate::log_debug_ct!("adjust_expr: {adjusted:?}");

    // Identify convenient expression kinds.
    let expr = adjusted.cast::<ast::Expr>()?;
    Some(match expr {
        ast::Expr::Label(..) => SyntaxClass::label(adjusted),
        ast::Expr::Ref(..) => SyntaxClass::Ref(adjusted),
        ast::Expr::FuncCall(call) => SyntaxClass::Callee(adjusted.find(call.callee().span())?),
        ast::Expr::Set(set) => SyntaxClass::Callee(adjusted.find(set.target().span())?),
        ast::Expr::Ident(..) | ast::Expr::MathIdent(..) => {
            SyntaxClass::VarAccess(VarClass::Ident(adjusted))
        }
        ast::Expr::FieldAccess(..) => SyntaxClass::VarAccess(VarClass::FieldAccess(adjusted)),
        ast::Expr::Str(..) => {
            let parent = adjusted.parent()?;
            if parent.kind() == SyntaxKind::ModuleImport {
                SyntaxClass::ImportPath(adjusted)
            } else if parent.kind() == SyntaxKind::ModuleInclude {
                SyntaxClass::IncludePath(adjusted)
            } else {
                SyntaxClass::Normal(adjusted.kind(), adjusted)
            }
        }
        _ if expr.hash()
            || matches!(adjusted.kind(), SyntaxKind::MathIdent | SyntaxKind::Error) =>
        {
            SyntaxClass::Normal(adjusted.kind(), adjusted)
        }
        _ => return None,
    })
}

/// Whether the node might be in code trivia. This is a bit internal so please
/// check the caller to understand it.
fn possible_in_code_trivia(kind: SyntaxKind) -> bool {
    !matches!(
        interpret_mode_at_kind(kind),
        Some(InterpretMode::Markup | InterpretMode::Math | InterpretMode::Comment)
    )
}

/// Classes of arguments that can be operated on by IDE functionality.
#[derive(Debug, Clone)]
pub enum ArgClass<'a> {
    /// A positional argument.
    Positional {
        /// The spread arguments met before the positional argument.
        spreads: EcoVec<LinkedNode<'a>>,
        /// The index of the positional argument.
        positional: usize,
        /// Whether the positional argument is a spread argument.
        is_spread: bool,
    },
    /// A named argument.
    Named(LinkedNode<'a>),
}

impl ArgClass<'_> {
    /// Creates the class refer to the first positional argument.
    pub fn first_positional() -> Self {
        ArgClass::Positional {
            spreads: EcoVec::new(),
            positional: 0,
            is_spread: false,
        }
    }
}

// todo: whether we can merge `SurroundingSyntax` and `SyntaxContext`?
/// Classes of syntax context (outer syntax) that can be operated on by IDE
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, strum::EnumIter)]
pub enum SurroundingSyntax {
    /// Regular syntax.
    Regular,
    /// Content in a string.
    StringContent,
    /// The cursor is directly on the selector of a show rule.
    Selector,
    /// The cursor is directly on the transformation of a show rule.
    ShowTransform,
    /// The cursor is directly on the import list.
    ImportList,
    /// The cursor is directly on the set rule.
    SetRule,
    /// The cursor is directly on the parameter list.
    ParamList,
}

/// Determines the surrounding syntax of the node at the position.
pub fn surrounding_syntax(node: &LinkedNode) -> SurroundingSyntax {
    check_previous_syntax(node)
        .or_else(|| check_surrounding_syntax(node))
        .unwrap_or(SurroundingSyntax::Regular)
}

fn check_surrounding_syntax(mut leaf: &LinkedNode) -> Option<SurroundingSyntax> {
    use SurroundingSyntax::*;
    let mut met_args = false;

    if matches!(leaf.kind(), SyntaxKind::Str) {
        return Some(StringContent);
    }

    while let Some(parent) = leaf.parent() {
        crate::log_debug_ct!(
            "check_surrounding_syntax: {:?}::{:?}",
            parent.kind(),
            leaf.kind()
        );
        match parent.kind() {
            SyntaxKind::CodeBlock
            | SyntaxKind::ContentBlock
            | SyntaxKind::Equation
            | SyntaxKind::Closure => {
                return Some(Regular);
            }
            SyntaxKind::ImportItemPath
            | SyntaxKind::ImportItems
            | SyntaxKind::RenamedImportItem => {
                return Some(ImportList);
            }
            SyntaxKind::ModuleImport => {
                let colon = parent.children().find(|s| s.kind() == SyntaxKind::Colon);
                let Some(colon) = colon else {
                    return Some(Regular);
                };

                if leaf.offset() >= colon.offset() {
                    return Some(ImportList);
                } else {
                    return Some(Regular);
                }
            }
            SyntaxKind::Named => {
                let colon = parent.children().find(|s| s.kind() == SyntaxKind::Colon);
                let Some(colon) = colon else {
                    return Some(Regular);
                };

                return if leaf.offset() >= colon.offset() {
                    Some(Regular)
                } else if node_ancestors(leaf).any(|n| n.kind() == SyntaxKind::Params) {
                    Some(ParamList)
                } else {
                    Some(Regular)
                };
            }
            SyntaxKind::Params => {
                return Some(ParamList);
            }
            SyntaxKind::Args => {
                met_args = true;
            }
            SyntaxKind::SetRule => {
                let rule = parent.get().cast::<ast::SetRule>()?;
                if met_args || enclosed_by(parent, rule.condition().map(|s| s.span()), leaf) {
                    return Some(Regular);
                } else {
                    return Some(SetRule);
                }
            }
            SyntaxKind::ShowRule => {
                if met_args {
                    return Some(Regular);
                }

                let rule = parent.get().cast::<ast::ShowRule>()?;
                let colon = rule
                    .to_untyped()
                    .children()
                    .find(|s| s.kind() == SyntaxKind::Colon);
                let Some(colon) = colon.and_then(|colon| parent.find(colon.span())) else {
                    // incomplete show rule
                    return Some(Selector);
                };

                if leaf.offset() >= colon.offset() {
                    return Some(ShowTransform);
                } else {
                    return Some(Selector); // query's first argument
                }
            }
            _ => {}
        }

        leaf = parent;
    }

    None
}

fn check_previous_syntax(leaf: &LinkedNode) -> Option<SurroundingSyntax> {
    let mut leaf = leaf.clone();
    if leaf.kind().is_trivia() {
        leaf = leaf.prev_sibling()?;
    }
    if matches!(
        leaf.kind(),
        SyntaxKind::ShowRule
            | SyntaxKind::SetRule
            | SyntaxKind::ModuleImport
            | SyntaxKind::ModuleInclude
    ) {
        return check_surrounding_syntax(&leaf.rightmost_leaf()?);
    }

    if matches!(leaf.kind(), SyntaxKind::Show) {
        return Some(SurroundingSyntax::Selector);
    }
    if matches!(leaf.kind(), SyntaxKind::Set) {
        return Some(SurroundingSyntax::SetRule);
    }

    None
}

fn enclosed_by(parent: &LinkedNode, s: Option<Span>, leaf: &LinkedNode) -> bool {
    s.and_then(|s| parent.find(s)?.find(leaf.span())).is_some()
}

/// Classes of syntax context (outer syntax) that can be operated on by IDE
/// functionality.
///
/// A syntax context is either a [`SyntaxClass`] or other things.
/// One thing is not necessary to refer to some exact node. For example, a
/// cursor moving after some comma in a function call is identified as a
/// [`SyntaxContext::Arg`].
#[derive(Debug, Clone)]
pub enum SyntaxContext<'a> {
    /// A cursor on an argument.
    Arg {
        /// The callee node.
        callee: LinkedNode<'a>,
        /// The arguments node.
        args: LinkedNode<'a>,
        /// The argument target pointed by the cursor.
        target: ArgClass<'a>,
        /// Whether the callee is a set rule.
        is_set: bool,
    },
    /// A cursor on an element in an array or dictionary literal.
    Element {
        /// The container node.
        container: LinkedNode<'a>,
        /// The element target pointed by the cursor.
        target: ArgClass<'a>,
    },
    /// A cursor on a parenthesized expression.
    Paren {
        /// The parenthesized expression node.
        container: LinkedNode<'a>,
        /// Whether the cursor is on the left side of the parenthesized
        /// expression.
        is_before: bool,
    },
    /// A variable access expression.
    ///
    /// It can be either an identifier or a field access.
    VarAccess(VarClass<'a>),
    /// A cursor on an import path.
    ImportPath(LinkedNode<'a>),
    /// A cursor on an include path.
    IncludePath(LinkedNode<'a>),
    /// A cursor on a label.
    Label {
        /// The label node.
        node: LinkedNode<'a>,
        /// Whether the label is converted from an error node.
        is_error: bool,
    },
    /// A cursor on a normal [`SyntaxClass`].
    Normal(LinkedNode<'a>),
}

impl<'a> SyntaxContext<'a> {
    /// Gets the node of the cursor class.
    pub fn node(&self) -> Option<LinkedNode<'a>> {
        Some(match self {
            SyntaxContext::Arg { target, .. } | SyntaxContext::Element { target, .. } => {
                match target {
                    ArgClass::Positional { .. } => return None,
                    ArgClass::Named(node) => node.clone(),
                }
            }
            SyntaxContext::VarAccess(cls) => cls.node().clone(),
            SyntaxContext::Paren { container, .. } => container.clone(),
            SyntaxContext::Label { node, .. }
            | SyntaxContext::ImportPath(node)
            | SyntaxContext::IncludePath(node)
            | SyntaxContext::Normal(node) => node.clone(),
        })
    }

    /// Gets the argument container node.
    pub fn arg_container(&self) -> Option<&LinkedNode<'a>> {
        match self {
            Self::Arg { args, .. }
            | Self::Element {
                container: args, ..
            } => Some(args),
            Self::Paren { container, .. } => Some(container),
            _ => None,
        }
    }
}

/// Kind of argument source.
#[derive(Debug)]
enum ArgSourceKind {
    /// An argument in a function call.
    Call,
    /// An argument (element) in an array literal.
    Array,
    /// An argument (element) in a dictionary literal.
    Dict,
}

/// Classifies node's context (outer syntax) by outer node that can be operated
/// on by IDE functionality.
pub fn classify_context_outer<'a>(
    outer: LinkedNode<'a>,
    node: LinkedNode<'a>,
) -> Option<SyntaxContext<'a>> {
    use SyntaxClass::*;
    let context_syntax = classify_syntax(outer.clone(), node.offset())?;
    let node_syntax = classify_syntax(node.clone(), node.offset())?;

    match context_syntax {
        Callee(callee)
            if matches!(node_syntax, Normal(..) | Label { .. } | Ref(..))
                && !matches!(node_syntax, Callee(..)) =>
        {
            let parent = callee.parent()?;
            let args = match parent.cast::<ast::Expr>() {
                Some(ast::Expr::FuncCall(call)) => call.args(),
                Some(ast::Expr::Set(set)) => set.args(),
                _ => return None,
            };
            let args = parent.find(args.span())?;

            let is_set = parent.kind() == SyntaxKind::SetRule;
            let arg_target = arg_context(args.clone(), node, ArgSourceKind::Call)?;
            Some(SyntaxContext::Arg {
                callee,
                args,
                target: arg_target,
                is_set,
            })
        }
        _ => None,
    }
}

/// Classifies node's context (outer syntax) that can be operated on by IDE
/// functionality.
pub fn classify_context(node: LinkedNode, cursor: Option<usize>) -> Option<SyntaxContext<'_>> {
    let mut node = node;
    if node.kind().is_trivia() && node.parent_kind().is_some_and(possible_in_code_trivia) {
        loop {
            node = node.prev_sibling()?;

            if !node.kind().is_trivia() {
                break;
            }
        }
    }

    let cursor = cursor.unwrap_or_else(|| node.offset());
    let syntax = classify_syntax(node.clone(), cursor)?;

    let normal_syntax = match syntax {
        SyntaxClass::Callee(callee) => {
            return callee_context(callee, node);
        }
        SyntaxClass::Label { node, is_error } => {
            return Some(SyntaxContext::Label { node, is_error });
        }
        SyntaxClass::ImportPath(node) => {
            return Some(SyntaxContext::ImportPath(node));
        }
        SyntaxClass::IncludePath(node) => {
            return Some(SyntaxContext::IncludePath(node));
        }
        syntax => syntax,
    };

    let Some(mut node_parent) = node.parent().cloned() else {
        return Some(SyntaxContext::Normal(node));
    };

    while let SyntaxKind::Named | SyntaxKind::Colon = node_parent.kind() {
        let Some(parent) = node_parent.parent() else {
            return Some(SyntaxContext::Normal(node));
        };
        node_parent = parent.clone();
    }

    match node_parent.kind() {
        SyntaxKind::Args => {
            let callee = node_ancestors(&node_parent).find_map(|ancestor| {
                let span = match ancestor.cast::<ast::Expr>()? {
                    ast::Expr::FuncCall(call) => call.callee().span(),
                    ast::Expr::Set(set) => set.target().span(),
                    _ => return None,
                };
                ancestor.find(span)
            })?;

            let param_node = match node.kind() {
                SyntaxKind::Ident
                    if matches!(
                        node.parent_kind().zip(node.next_sibling_kind()),
                        Some((SyntaxKind::Named, SyntaxKind::Colon))
                    ) =>
                {
                    node
                }
                _ if matches!(node.parent_kind(), Some(SyntaxKind::Named)) => {
                    node.parent().cloned()?
                }
                _ => node,
            };

            callee_context(callee, param_node)
        }
        SyntaxKind::Array | SyntaxKind::Dict => {
            let element_target = arg_context(
                node_parent.clone(),
                node.clone(),
                match node_parent.kind() {
                    SyntaxKind::Array => ArgSourceKind::Array,
                    SyntaxKind::Dict => ArgSourceKind::Dict,
                    _ => unreachable!(),
                },
            )?;
            Some(SyntaxContext::Element {
                container: node_parent.clone(),
                target: element_target,
            })
        }
        SyntaxKind::Parenthesized => {
            let is_before = node.offset() <= node_parent.offset() + 1;
            Some(SyntaxContext::Paren {
                container: node_parent.clone(),
                is_before,
            })
        }
        _ => Some(match normal_syntax {
            SyntaxClass::VarAccess(v) => SyntaxContext::VarAccess(v),
            normal_syntax => SyntaxContext::Normal(normal_syntax.node().clone()),
        }),
    }
}

fn callee_context<'a>(callee: LinkedNode<'a>, node: LinkedNode<'a>) -> Option<SyntaxContext<'a>> {
    let parent = callee.parent()?;
    let args = match parent.cast::<ast::Expr>() {
        Some(ast::Expr::FuncCall(call)) => call.args(),
        Some(ast::Expr::Set(set)) => set.args(),
        _ => return None,
    };
    let args = parent.find(args.span())?;

    let is_set = parent.kind() == SyntaxKind::SetRule;
    let target = arg_context(args.clone(), node, ArgSourceKind::Call)?;
    Some(SyntaxContext::Arg {
        callee,
        args,
        target,
        is_set,
    })
}

fn arg_context<'a>(
    args_node: LinkedNode<'a>,
    mut node: LinkedNode<'a>,
    param_kind: ArgSourceKind,
) -> Option<ArgClass<'a>> {
    if node.kind() == SyntaxKind::RightParen {
        node = node.prev_sibling()?;
    }
    match node.kind() {
        SyntaxKind::Named => {
            let param_ident = node.cast::<ast::Named>()?.name();
            Some(ArgClass::Named(args_node.find(param_ident.span())?))
        }
        SyntaxKind::Colon => {
            let prev = node.prev_leaf()?;
            let param_ident = prev.cast::<ast::Ident>()?;
            Some(ArgClass::Named(args_node.find(param_ident.span())?))
        }
        _ => {
            let parent = node.parent();
            if let Some(parent) = parent {
                if parent.kind() == SyntaxKind::Named {
                    let param_ident = parent.cast::<ast::Named>()?;
                    let name = param_ident.name();
                    let init = param_ident.expr();
                    let init = parent.find(init.span())?;
                    if init.range().contains(&node.offset()) {
                        let name = args_node.find(name.span())?;
                        return Some(ArgClass::Named(name));
                    }
                }
            }

            let mut spreads = EcoVec::new();
            let mut positional = 0;
            let is_spread = node.kind() == SyntaxKind::Spread;

            let args_before = args_node
                .children()
                .take_while(|arg| arg.range().end <= node.offset());
            match param_kind {
                ArgSourceKind::Call => {
                    for ch in args_before {
                        match ch.cast::<ast::Arg>() {
                            Some(ast::Arg::Pos(..)) => {
                                positional += 1;
                            }
                            Some(ast::Arg::Spread(..)) => {
                                spreads.push(ch);
                            }
                            Some(ast::Arg::Named(..)) | None => {}
                        }
                    }
                }
                ArgSourceKind::Array => {
                    for ch in args_before {
                        match ch.cast::<ast::ArrayItem>() {
                            Some(ast::ArrayItem::Pos(..)) => {
                                positional += 1;
                            }
                            Some(ast::ArrayItem::Spread(..)) => {
                                spreads.push(ch);
                            }
                            _ => {}
                        }
                    }
                }
                ArgSourceKind::Dict => {
                    for ch in args_before {
                        if let Some(ast::DictItem::Spread(..)) = ch.cast::<ast::DictItem>() {
                            spreads.push(ch);
                        }
                    }
                }
            }

            Some(ArgClass::Positional {
                spreads,
                positional,
                is_spread,
            })
        }
    }
}

/// The cursor is on an invalid position.
pub enum BadCompletionCursor {
    /// The cursor is outside of the argument list.
    ArgListPos,
}

/// Checks if the cursor is on an invalid position for completion.
pub fn bad_completion_cursor(
    syntax: Option<&SyntaxClass>,
    syntax_context: Option<&SyntaxContext>,
    leaf: &LinkedNode,
) -> Option<BadCompletionCursor> {
    // The cursor is on `f()|`
    if (matches!(syntax, Some(SyntaxClass::Callee(..))) && {
        syntax_context
            .and_then(SyntaxContext::arg_container)
            .is_some_and(|container| {
                container.rightmost_leaf().map(|s| s.offset()) == Some(leaf.offset())
            })
        // The cursor is on `f[]|`
    }) || (matches!(
        syntax,
        Some(SyntaxClass::Normal(SyntaxKind::ContentBlock, _))
    ) && matches!(leaf.kind(), SyntaxKind::RightBracket))
    {
        return Some(BadCompletionCursor::ArgListPos);
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use insta::assert_snapshot;
    use typst::syntax::{is_newline, Side, Source};

    fn map_node(source: &str, mapper: impl Fn(&LinkedNode, usize) -> char) -> String {
        let source = Source::detached(source.to_owned());
        let root = LinkedNode::new(source.root());
        let mut output_mapping = String::new();

        let mut cursor = 0;
        for ch in source.text().chars() {
            cursor += ch.len_utf8();
            if is_newline(ch) {
                output_mapping.push(ch);
                continue;
            }

            output_mapping.push(mapper(&root, cursor));
        }

        source
            .text()
            .lines()
            .zip(output_mapping.lines())
            .flat_map(|(a, b)| [a, "\n", b, "\n"])
            .collect::<String>()
    }

    fn map_syntax(source: &str) -> String {
        map_node(source, |root, cursor| {
            let node = root.leaf_at(cursor, Side::Before);
            let kind = node.and_then(|node| classify_syntax(node, cursor));
            match kind {
                Some(SyntaxClass::VarAccess(..)) => 'v',
                Some(SyntaxClass::Normal(..)) => 'n',
                Some(SyntaxClass::Label { .. }) => 'l',
                Some(SyntaxClass::Ref(..)) => 'r',
                Some(SyntaxClass::Callee(..)) => 'c',
                Some(SyntaxClass::ImportPath(..)) => 'i',
                Some(SyntaxClass::IncludePath(..)) => 'I',
                None => ' ',
            }
        })
    }

    fn map_context(source: &str) -> String {
        map_node(source, |root, cursor| {
            let node = root.leaf_at(cursor, Side::Before);
            let kind = node.and_then(|node| classify_context(node, Some(cursor)));
            match kind {
                Some(SyntaxContext::Arg { .. }) => 'p',
                Some(SyntaxContext::Element { .. }) => 'e',
                Some(SyntaxContext::Paren { .. }) => 'P',
                Some(SyntaxContext::VarAccess { .. }) => 'v',
                Some(SyntaxContext::ImportPath(..)) => 'i',
                Some(SyntaxContext::IncludePath(..)) => 'I',
                Some(SyntaxContext::Label { .. }) => 'l',
                Some(SyntaxContext::Normal(..)) => 'n',
                None => ' ',
            }
        })
    }

    #[test]
    fn test_get_syntax() {
        assert_snapshot!(map_syntax(r#"#let x = 1  
Text
= Heading #let y = 2;  
== Heading"#).trim(), @r"
        #let x = 1  
         nnnnvvnnn  
        Text
            
        = Heading #let y = 2;  
                   nnnnvvnnn   
        == Heading
        ");
        assert_snapshot!(map_syntax(r#"#let f(x);"#).trim(), @r"
        #let f(x);
         nnnnv v
        ");
        assert_snapshot!(map_syntax(r#"#{
  calc.  
}"#).trim(), @r"
        #{
         n
          calc.  
        nnvvvvvnn
        }
        n
        ");
    }

    #[test]
    fn test_get_context() {
        assert_snapshot!(map_context(r#"#let x = 1  
Text
= Heading #let y = 2;  
== Heading"#).trim(), @r"
        #let x = 1  
         nnnnvvnnn  
        Text
            
        = Heading #let y = 2;  
                   nnnnvvnnn   
        == Heading
        ");
        assert_snapshot!(map_context(r#"#let f(x);"#).trim(), @r"
        #let f(x);
         nnnnv v
        ");
        assert_snapshot!(map_context(r#"#f(1, 2)   Test"#).trim(), @r"
        #f(1, 2)   Test
         vpppppp
        ");
        assert_snapshot!(map_context(r#"#()   Test"#).trim(), @r"
        #()   Test
         ee
        ");
        assert_snapshot!(map_context(r#"#(1)   Test"#).trim(), @r"
        #(1)   Test
         PPP
        ");
        assert_snapshot!(map_context(r#"#(a: 1)   Test"#).trim(), @r"
        #(a: 1)   Test
         eeeeee
        ");
        assert_snapshot!(map_context(r#"#(1, 2)   Test"#).trim(), @r"
        #(1, 2)   Test
         eeeeee
        ");
        assert_snapshot!(map_context(r#"#(1, 2)  
  Test"#).trim(), @r"
        #(1, 2)  
         eeeeee  
          Test
        ");
    }

    fn access_node(s: &str, cursor: i32) -> String {
        access_node_(s, cursor).unwrap_or_default()
    }

    fn access_node_(s: &str, cursor: i32) -> Option<String> {
        access_var(s, cursor, |_source, var| {
            Some(var.accessed_node()?.get().clone().into_text().into())
        })
    }

    fn access_field(s: &str, cursor: i32) -> String {
        access_field_(s, cursor).unwrap_or_default()
    }

    fn access_field_(s: &str, cursor: i32) -> Option<String> {
        access_var(s, cursor, |source, var| {
            let field = var.accessing_field()?;
            Some(match field {
                FieldClass::Field(ident) => format!("Field: {}", ident.text()),
                FieldClass::DotSuffix(span_offset) => {
                    let offset = source.find(span_offset.span)?.offset() + span_offset.offset;
                    format!("DotSuffix: {offset:?}")
                }
            })
        })
    }

    fn access_var(
        s: &str,
        cursor: i32,
        f: impl FnOnce(&Source, VarClass) -> Option<String>,
    ) -> Option<String> {
        let cursor = if cursor < 0 {
            s.len() as i32 + cursor
        } else {
            cursor
        };
        let source = Source::detached(s.to_owned());
        let root = LinkedNode::new(source.root());
        let node = root.leaf_at(cursor as usize, Side::Before)?;
        let syntax = classify_syntax(node, cursor as usize)?;
        let SyntaxClass::VarAccess(var) = syntax else {
            return None;
        };
        f(&source, var)
    }

    #[test]
    fn test_access_field() {
        assert_snapshot!(access_field("#(a.b)", 5), @r"Field: b");
        assert_snapshot!(access_field("#a.", 3), @"DotSuffix: 3");
        assert_snapshot!(access_field("$a.$", 3), @"DotSuffix: 3");
        assert_snapshot!(access_field("#(a.)", 4), @"DotSuffix: 4");
        assert_snapshot!(access_node("#(a..b)", 4), @"a");
        assert_snapshot!(access_field("#(a..b)", 4), @"DotSuffix: 4");
        assert_snapshot!(access_node("#(a..b())", 4), @"a");
        assert_snapshot!(access_field("#(a..b())", 4), @"DotSuffix: 4");
    }

    #[test]
    fn test_code_access() {
        assert_snapshot!(access_node("#{`a`.}", 6), @"`a`");
        assert_snapshot!(access_field("#{`a`.}", 6), @"DotSuffix: 6");
        assert_snapshot!(access_node("#{$a$.}", 6), @"$a$");
        assert_snapshot!(access_field("#{$a$.}", 6), @"DotSuffix: 6");
        assert_snapshot!(access_node("#{\"a\".}", 6), @"\"a\"");
        assert_snapshot!(access_field("#{\"a\".}", 6), @"DotSuffix: 6");
        assert_snapshot!(access_node("#{<a>.}", 6), @"<a>");
        assert_snapshot!(access_field("#{<a>.}", 6), @"DotSuffix: 6");
    }

    #[test]
    fn test_markup_access() {
        assert_snapshot!(access_field("_a_.", 4), @"");
        assert_snapshot!(access_field("*a*.", 4), @"");
        assert_snapshot!(access_field("`a`.", 4), @"");
        assert_snapshot!(access_field("$a$.", 4), @"");
        assert_snapshot!(access_field("\"a\".", 4), @"");
        assert_snapshot!(access_field("@a.", 3), @"");
        assert_snapshot!(access_field("<a>.", 4), @"");
    }

    #[test]
    fn test_markup_chain_access() {
        assert_snapshot!(access_node("#a.b.", 5), @"a.b");
        assert_snapshot!(access_field("#a.b.", 5), @"DotSuffix: 5");
        assert_snapshot!(access_node("#a.b.c.", 7), @"a.b.c");
        assert_snapshot!(access_field("#a.b.c.", 7), @"DotSuffix: 7");
        assert_snapshot!(access_node("#context a.", 11), @"a");
        assert_snapshot!(access_field("#context a.", 11), @"DotSuffix: 11");
        assert_snapshot!(access_node("#context a.b.", 13), @"a.b");
        assert_snapshot!(access_field("#context a.b.", 13), @"DotSuffix: 13");

        assert_snapshot!(access_node("#a.at(1).", 9), @"a.at(1)");
        assert_snapshot!(access_field("#a.at(1).", 9), @"DotSuffix: 9");
        assert_snapshot!(access_node("#context a.at(1).", 17), @"a.at(1)");
        assert_snapshot!(access_field("#context a.at(1).", 17), @"DotSuffix: 17");

        assert_snapshot!(access_node("#a.at(1).c.", 11), @"a.at(1).c");
        assert_snapshot!(access_field("#a.at(1).c.", 11), @"DotSuffix: 11");
        assert_snapshot!(access_node("#context a.at(1).c.", 19), @"a.at(1).c");
        assert_snapshot!(access_field("#context a.at(1).c.", 19), @"DotSuffix: 19");
    }

    #[test]
    fn test_hash_access() {
        assert_snapshot!(access_node("#a.", 3), @"a");
        assert_snapshot!(access_field("#a.", 3), @"DotSuffix: 3");
        assert_snapshot!(access_node("#(a).", 5), @"(a)");
        assert_snapshot!(access_field("#(a).", 5), @"DotSuffix: 5");
        assert_snapshot!(access_node("#`a`.", 5), @"`a`");
        assert_snapshot!(access_field("#`a`.", 5), @"DotSuffix: 5");
        assert_snapshot!(access_node("#$a$.", 5), @"$a$");
        assert_snapshot!(access_field("#$a$.", 5), @"DotSuffix: 5");
        assert_snapshot!(access_node("#(a,).", 6), @"(a,)");
        assert_snapshot!(access_field("#(a,).", 6), @"DotSuffix: 6");
    }
}