1use serde::{Deserialize, Serialize};
60use tinymist_world::debug_loc::SourceSpanOffset;
61use typst::syntax::Span;
62
63use crate::prelude::*;
64
65pub fn node_ancestors<'a, 'b>(
67 node: &'b LinkedNode<'a>,
68) -> impl Iterator<Item = &'b LinkedNode<'a>> {
69 std::iter::successors(Some(node), |node| node.parent())
70}
71
72pub fn first_ancestor_expr(node: LinkedNode) -> Option<LinkedNode> {
74 node_ancestors(&node)
75 .find(|n| n.is::<ast::Expr>())
76 .map(|mut node| {
77 while matches!(node.kind(), SyntaxKind::Ident | SyntaxKind::MathIdent) {
78 let Some(parent) = node.parent() else {
79 return node;
80 };
81
82 let Some(field_access) = parent.cast::<ast::FieldAccess>() else {
83 return node;
84 };
85
86 let dot = parent
87 .children()
88 .find(|n| matches!(n.kind(), SyntaxKind::Dot));
89
90 if dot.is_some_and(|dot| {
94 dot.offset() <= node.offset() && field_access.field().span() == node.span()
95 }) {
96 node = parent;
97 } else {
98 return node;
99 }
100 }
101
102 node
103 })
104 .cloned()
105}
106
107pub enum PreviousItem<'a> {
110 Parent(&'a LinkedNode<'a>, &'a LinkedNode<'a>),
112 Sibling(&'a LinkedNode<'a>),
114}
115
116impl<'a> PreviousItem<'a> {
117 pub fn node(&self) -> &'a LinkedNode<'a> {
119 match self {
120 PreviousItem::Sibling(node) => node,
121 PreviousItem::Parent(node, _) => node,
122 }
123 }
124}
125
126pub fn previous_items<T>(
129 node: LinkedNode,
130 mut recv: impl FnMut(PreviousItem) -> Option<T>,
131) -> Option<T> {
132 let mut ancestor = Some(node);
133 while let Some(node) = &ancestor {
134 let mut sibling = Some(node.clone());
135 while let Some(node) = &sibling {
136 if let Some(v) = recv(PreviousItem::Sibling(node)) {
137 return Some(v);
138 }
139
140 sibling = node.prev_sibling();
141 }
142
143 if let Some(parent) = node.parent() {
144 if let Some(v) = recv(PreviousItem::Parent(parent, node)) {
145 return Some(v);
146 }
147
148 ancestor = Some(parent.clone());
149 continue;
150 }
151
152 break;
153 }
154
155 None
156}
157
158pub enum PreviousDecl<'a> {
161 Ident(ast::Ident<'a>),
171 ImportSource(ast::Expr<'a>),
181 ImportAll(ast::ModuleImport<'a>),
191}
192
193pub fn previous_decls<T>(
196 node: LinkedNode,
197 mut recv: impl FnMut(PreviousDecl) -> Option<T>,
198) -> Option<T> {
199 previous_items(node, |item| {
200 match (&item, item.node().cast::<ast::Expr>()?) {
201 (PreviousItem::Sibling(..), ast::Expr::LetBinding(lb)) => {
202 for ident in lb.kind().bindings() {
203 if let Some(t) = recv(PreviousDecl::Ident(ident)) {
204 return Some(t);
205 }
206 }
207 }
208 (PreviousItem::Sibling(..), ast::Expr::ModuleImport(import)) => {
209 match import.imports() {
211 Some(ast::Imports::Wildcard) => {
212 if let Some(t) = recv(PreviousDecl::ImportAll(import)) {
213 return Some(t);
214 }
215 }
216 Some(ast::Imports::Items(items)) => {
217 for item in items.iter() {
218 if let Some(t) = recv(PreviousDecl::Ident(item.bound_name())) {
219 return Some(t);
220 }
221 }
222 }
223 _ => {}
224 }
225
226 if let Some(new_name) = import.new_name() {
228 if let Some(t) = recv(PreviousDecl::Ident(new_name)) {
229 return Some(t);
230 }
231 } else if import.imports().is_none()
232 && let Some(t) = recv(PreviousDecl::ImportSource(import.source()))
233 {
234 return Some(t);
235 }
236 }
237 (PreviousItem::Parent(parent, child), ast::Expr::ForLoop(for_expr)) => {
238 let body = parent.find(for_expr.body().span());
239 let in_body = body.is_some_and(|n| n.find(child.span()).is_some());
240 if !in_body {
241 return None;
242 }
243
244 for ident in for_expr.pattern().bindings() {
245 if let Some(t) = recv(PreviousDecl::Ident(ident)) {
246 return Some(t);
247 }
248 }
249 }
250 (PreviousItem::Parent(parent, child), ast::Expr::Closure(closure)) => {
251 let body = parent.find(closure.body().span());
252 let in_body = body.is_some_and(|n| n.find(child.span()).is_some());
253 if !in_body {
254 return None;
255 }
256
257 for param in closure.params().children() {
258 match param {
259 ast::Param::Pos(pos) => {
260 for ident in pos.bindings() {
261 if let Some(t) = recv(PreviousDecl::Ident(ident)) {
262 return Some(t);
263 }
264 }
265 }
266 ast::Param::Named(named) => {
267 if let Some(t) = recv(PreviousDecl::Ident(named.name())) {
268 return Some(t);
269 }
270 }
271 ast::Param::Spread(spread) => {
272 if let Some(sink_ident) = spread.sink_ident()
273 && let Some(t) = recv(PreviousDecl::Ident(sink_ident))
274 {
275 return Some(t);
276 }
277 }
278 }
279 }
280 }
281 _ => {}
282 };
283 None
284 })
285}
286
287pub fn is_mark(sk: SyntaxKind) -> bool {
289 use SyntaxKind::*;
290 #[allow(clippy::match_like_matches_macro)]
291 match sk {
292 MathAlignPoint | Plus | Minus | Dot | Dots | Arrow | Not | And | Or => true,
293 Eq | EqEq | ExclEq | Lt | LtEq | Gt | GtEq | PlusEq | HyphEq | StarEq | SlashEq => true,
294 LeftBrace | RightBrace | LeftBracket | RightBracket | LeftParen | RightParen => true,
295 Slash | Hat | Comma | Semicolon | Colon | Hash => true,
296 _ => false,
297 }
298}
299
300pub fn is_ident_like(node: &SyntaxNode) -> bool {
302 fn can_be_ident(node: &SyntaxNode) -> bool {
303 typst::syntax::is_ident(node.text())
304 }
305
306 use SyntaxKind::*;
307 let kind = node.kind();
308 matches!(kind, Ident | MathIdent | Underscore)
309 || (matches!(kind, Error) && can_be_ident(node))
310 || kind.is_keyword()
311}
312
313#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, strum::EnumIter)]
315#[serde(rename_all = "camelCase")]
316pub enum InterpretMode {
317 Comment,
319 String,
321 Raw,
323 Markup,
325 Code,
327 Math,
329}
330
331pub fn interpret_mode_at(mut leaf: Option<&LinkedNode>) -> InterpretMode {
334 loop {
335 crate::log_debug_ct!("leaf for mode: {leaf:?}");
336 if let Some(t) = leaf {
337 if let Some(mode) = interpret_mode_at_kind(t.kind()) {
338 break mode;
339 }
340
341 if !t.kind().is_trivia() && {
342 t.prev_leaf().is_some_and(|n| n.kind() == SyntaxKind::Hash)
344 } {
345 return InterpretMode::Code;
346 }
347
348 leaf = t.parent();
349 } else {
350 break InterpretMode::Markup;
351 }
352 }
353}
354
355pub(crate) fn interpret_mode_at_kind(kind: SyntaxKind) -> Option<InterpretMode> {
357 use SyntaxKind::*;
358 Some(match kind {
359 LineComment | BlockComment | Shebang => InterpretMode::Comment,
360 Raw => InterpretMode::Raw,
361 Str => InterpretMode::String,
362 CodeBlock | Code => InterpretMode::Code,
363 ContentBlock | Markup => InterpretMode::Markup,
364 Equation | Math => InterpretMode::Math,
365 Hash => InterpretMode::Code,
366 Label | Text | Ident | Args | FuncCall | FieldAccess | Bool | Int | Float | Numeric
367 | Space | Linebreak | Parbreak | Escape | Shorthand | SmartQuote | RawLang | RawDelim
368 | RawTrimmed | LeftBrace | RightBrace | LeftBracket | RightBracket | LeftParen
369 | RightParen | Comma | Semicolon | Colon | Star | Underscore | Dollar | Plus | Minus
370 | Slash | Hat | Prime | Dot | Eq | EqEq | ExclEq | Lt | LtEq | Gt | GtEq | PlusEq
371 | HyphEq | StarEq | SlashEq | Dots | Arrow | Root | Not | And | Or | None | Auto | As
372 | Named | Keyed | Spread | Error | End => return Option::None,
373 Strong | Emph | Link | Ref | RefMarker | Heading | HeadingMarker | ListItem
374 | ListMarker | EnumItem | EnumMarker | TermItem | TermMarker => InterpretMode::Markup,
375 MathIdent | MathAlignPoint | MathDelimited | MathAttach | MathPrimes | MathFrac
376 | MathRoot | MathShorthand | MathText => InterpretMode::Math,
377 Let | Set | Show | Context | If | Else | For | In | While | Break | Continue | Return
378 | Import | Include | Closure | Params | LetBinding | SetRule | ShowRule | Contextual
379 | Conditional | WhileLoop | ForLoop | LoopBreak | ModuleImport | ImportItems
380 | ImportItemPath | RenamedImportItem | ModuleInclude | LoopContinue | FuncReturn
381 | Unary | Binary | Parenthesized | Dict | Array | Destructuring | DestructAssignment => {
382 InterpretMode::Code
383 }
384 })
385}
386
387#[derive(Debug, Clone)]
389pub enum DefClass<'a> {
390 Let(LinkedNode<'a>),
392 Import(LinkedNode<'a>),
394}
395
396impl DefClass<'_> {
397 pub fn node(&self) -> &LinkedNode<'_> {
399 match self {
400 DefClass::Let(node) => node,
401 DefClass::Import(node) => node,
402 }
403 }
404
405 pub fn name(&self) -> Option<LinkedNode<'_>> {
407 match self {
408 DefClass::Let(node) => {
409 let lb: ast::LetBinding<'_> = node.cast()?;
410 let names = match lb.kind() {
411 ast::LetBindingKind::Closure(name) => node.find(name.span())?,
412 ast::LetBindingKind::Normal(ast::Pattern::Normal(name)) => {
413 node.find(name.span())?
414 }
415 _ => return None,
416 };
417
418 Some(names)
419 }
420 DefClass::Import(_node) => {
421 None
425 }
426 }
427 }
428
429 pub fn name_range(&self) -> Option<Range<usize>> {
431 self.name().map(|node| node.range())
432 }
433}
434
435pub fn classify_def_loosely(node: LinkedNode<'_>) -> Option<DefClass<'_>> {
438 classify_def_(node, false)
439}
440
441pub fn classify_def(node: LinkedNode<'_>) -> Option<DefClass<'_>> {
443 classify_def_(node, true)
444}
445
446fn classify_def_(node: LinkedNode<'_>, strict: bool) -> Option<DefClass<'_>> {
448 let mut ancestor = node;
449 if ancestor.kind().is_trivia() || is_mark(ancestor.kind()) {
450 ancestor = ancestor.prev_sibling()?;
451 }
452
453 while !ancestor.is::<ast::Expr>() {
454 ancestor = ancestor.parent()?.clone();
455 }
456 crate::log_debug_ct!("ancestor: {ancestor:?}");
457 let adjusted = adjust_expr(ancestor)?;
458 crate::log_debug_ct!("adjust_expr: {adjusted:?}");
459
460 let may_ident = adjusted.cast::<ast::Expr>()?;
461 if strict && !may_ident.hash() && !matches!(may_ident, ast::Expr::MathIdent(_)) {
462 return None;
463 }
464
465 let expr = may_ident;
466 Some(match expr {
467 ast::Expr::FuncCall(..) => return None,
470 ast::Expr::SetRule(..) => return None,
471 ast::Expr::LetBinding(..) => DefClass::Let(adjusted),
472 ast::Expr::ModuleImport(..) => DefClass::Import(adjusted),
473 ast::Expr::Ident(..)
475 | ast::Expr::MathIdent(..)
476 | ast::Expr::FieldAccess(..)
477 | ast::Expr::Closure(..) => {
478 let mut ancestor = adjusted;
479 while !ancestor.is::<ast::LetBinding>() {
480 ancestor = ancestor.parent()?.clone();
481 }
482
483 DefClass::Let(ancestor)
484 }
485 ast::Expr::Str(..) => {
486 let parent = adjusted.parent()?;
487 if parent.kind() != SyntaxKind::ModuleImport {
488 return None;
489 }
490
491 DefClass::Import(parent.clone())
492 }
493 _ if expr.hash() => return None,
494 _ => {
495 crate::log_debug_ct!("unsupported kind {:?}", adjusted.kind());
496 return None;
497 }
498 })
499}
500
501pub fn adjust_expr(mut node: LinkedNode) -> Option<LinkedNode> {
506 while let Some(paren_expr) = node.cast::<ast::Parenthesized>() {
507 node = node.find(paren_expr.expr().span())?;
508 }
509 if let Some(parent) = node.parent()
510 && let Some(field_access) = parent.cast::<ast::FieldAccess>()
511 && node.span() == field_access.field().span()
512 {
513 return Some(parent.clone());
514 }
515 Some(node)
516}
517
518#[derive(Debug, Clone)]
520pub enum FieldClass<'a> {
521 Field(LinkedNode<'a>),
531
532 DotSuffix(SourceSpanOffset),
542}
543
544impl FieldClass<'_> {
545 pub fn offset(&self, source: &Source) -> Option<usize> {
547 Some(match self {
548 Self::Field(node) => node.offset(),
549 Self::DotSuffix(span_offset) => {
550 source.find(span_offset.span)?.offset() + span_offset.offset
551 }
552 })
553 }
554}
555
556#[derive(Debug, Clone)]
559pub enum VarClass<'a> {
560 Ident(LinkedNode<'a>),
562 FieldAccess(LinkedNode<'a>),
564 DotAccess(LinkedNode<'a>),
568}
569
570impl<'a> VarClass<'a> {
571 pub fn node(&self) -> &LinkedNode<'a> {
573 match self {
574 Self::Ident(node) | Self::FieldAccess(node) | Self::DotAccess(node) => node,
575 }
576 }
577
578 pub fn accessed_node(&self) -> Option<LinkedNode<'a>> {
580 Some(match self {
581 Self::Ident(node) => node.clone(),
582 Self::FieldAccess(node) => {
583 let field_access = node.cast::<ast::FieldAccess>()?;
584 node.find(field_access.target().span())?
585 }
586 Self::DotAccess(node) => node.clone(),
587 })
588 }
589
590 pub fn accessing_field(&self) -> Option<FieldClass<'a>> {
592 match self {
593 Self::FieldAccess(node) => {
594 let dot = node
595 .children()
596 .find(|n| matches!(n.kind(), SyntaxKind::Dot))?;
597 let mut iter_after_dot =
598 node.children().skip_while(|n| n.kind() != SyntaxKind::Dot);
599 let ident = iter_after_dot.find(|n| {
600 matches!(
601 n.kind(),
602 SyntaxKind::Ident | SyntaxKind::MathIdent | SyntaxKind::Error
603 )
604 });
605
606 let ident_case = ident.map(|ident| {
607 if ident.text().is_empty() {
608 FieldClass::DotSuffix(SourceSpanOffset {
609 span: ident.span(),
610 offset: 0,
611 })
612 } else {
613 FieldClass::Field(ident)
614 }
615 });
616
617 ident_case.or_else(|| {
618 Some(FieldClass::DotSuffix(SourceSpanOffset {
619 span: dot.span(),
620 offset: 1,
621 }))
622 })
623 }
624 Self::DotAccess(node) => Some(FieldClass::DotSuffix(SourceSpanOffset {
625 span: node.span(),
626 offset: node.range().len() + 1,
627 })),
628 Self::Ident(..) => None,
629 }
630 }
631}
632
633#[derive(Debug, Clone)]
635pub enum SyntaxClass<'a> {
636 VarAccess(VarClass<'a>),
640 Label {
642 node: LinkedNode<'a>,
644 is_error: bool,
646 },
647 Ref {
649 node: LinkedNode<'a>,
651 suffix_colon: bool,
654 },
655 Callee(LinkedNode<'a>),
657 ImportPath(LinkedNode<'a>),
659 IncludePath(LinkedNode<'a>),
661 Normal(SyntaxKind, LinkedNode<'a>),
663}
664
665impl<'a> SyntaxClass<'a> {
666 pub fn label(node: LinkedNode<'a>) -> Self {
668 Self::Label {
669 node,
670 is_error: false,
671 }
672 }
673
674 pub fn error_as_label(node: LinkedNode<'a>) -> Self {
676 Self::Label {
677 node,
678 is_error: true,
679 }
680 }
681
682 pub fn node(&self) -> &LinkedNode<'a> {
684 match self {
685 SyntaxClass::VarAccess(cls) => cls.node(),
686 SyntaxClass::Label { node, .. }
687 | SyntaxClass::Ref { node, .. }
688 | SyntaxClass::Callee(node)
689 | SyntaxClass::ImportPath(node)
690 | SyntaxClass::IncludePath(node)
691 | SyntaxClass::Normal(_, node) => node,
692 }
693 }
694
695 pub fn complete_offset(&self) -> Option<usize> {
697 match self {
698 SyntaxClass::Label { node, .. } => Some(node.offset() + 1),
701 _ => None,
702 }
703 }
704}
705
706pub fn classify_syntax(node: LinkedNode<'_>, cursor: usize) -> Option<SyntaxClass<'_>> {
709 if matches!(node.kind(), SyntaxKind::Error) && node.text().starts_with('<') {
710 return Some(SyntaxClass::error_as_label(node));
711 }
712
713 fn can_skip_trivia(node: &LinkedNode, cursor: usize) -> bool {
715 if !node.kind().is_trivia() || !node.parent_kind().is_some_and(possible_in_code_trivia) {
717 return false;
718 }
719
720 let previous_text = node.text().as_bytes();
722 let previous_text = if node.range().contains(&cursor) {
723 &previous_text[..cursor - node.offset()]
724 } else {
725 previous_text
726 };
727
728 !previous_text.contains(&b'\n')
733 }
734
735 let mut node = node;
737 if can_skip_trivia(&node, cursor) {
738 node = node.prev_sibling()?;
739 }
740
741 fn classify_dot_access<'a>(node: &LinkedNode<'a>) -> Option<SyntaxClass<'a>> {
747 let prev_leaf = node.prev_leaf();
748 let mode = interpret_mode_at(Some(node));
749
750 if matches!(mode, InterpretMode::Markup | InterpretMode::Math)
752 && prev_leaf
753 .as_ref()
754 .is_some_and(|leaf| leaf.range().end < node.offset())
755 {
756 return None;
757 }
758
759 if matches!(mode, InterpretMode::Math)
760 && prev_leaf.as_ref().is_some_and(|leaf| {
761 node_ancestors(leaf)
763 .find(|t| matches!(t.kind(), SyntaxKind::Equation))
764 .is_some_and(|parent| parent.offset() == leaf.offset())
765 })
766 {
767 return None;
768 }
769
770 let dot_target = prev_leaf.and_then(first_ancestor_expr)?;
771
772 if matches!(mode, InterpretMode::Math | InterpretMode::Code) || {
773 matches!(mode, InterpretMode::Markup)
774 && (matches!(
775 dot_target.kind(),
776 SyntaxKind::Ident
777 | SyntaxKind::MathIdent
778 | SyntaxKind::FieldAccess
779 | SyntaxKind::FuncCall
780 ) || (matches!(
781 dot_target.prev_leaf().as_deref().map(SyntaxNode::kind),
782 Some(SyntaxKind::Hash)
783 )))
784 } {
785 return Some(SyntaxClass::VarAccess(VarClass::DotAccess(dot_target)));
786 }
787
788 None
789 }
790
791 if node.offset() + 1 == cursor
792 && {
793 matches!(node.kind(), SyntaxKind::Dot)
795 || (matches!(
796 node.kind(),
797 SyntaxKind::Text | SyntaxKind::MathText | SyntaxKind::Error
798 ) && node.text().starts_with("."))
799 }
800 && let Some(dot_access) = classify_dot_access(&node)
801 {
802 return Some(dot_access);
803 }
804
805 if node.offset() + 1 == cursor
806 && matches!(node.kind(), SyntaxKind::Dots)
807 && matches!(node.parent_kind(), Some(SyntaxKind::Spread))
808 && let Some(dot_access) = classify_dot_access(&node)
809 {
810 return Some(dot_access);
811 }
812
813 fn classify_ref<'a>(node: &LinkedNode<'a>) -> Option<SyntaxClass<'a>> {
818 let prev_leaf = node.prev_leaf()?;
819
820 if matches!(prev_leaf.kind(), SyntaxKind::RefMarker)
821 && prev_leaf.range().end == node.offset()
822 {
823 return Some(SyntaxClass::Ref {
824 node: prev_leaf,
825 suffix_colon: true,
826 });
827 }
828
829 None
830 }
831
832 if node.offset() + 1 == cursor
833 && {
834 matches!(node.kind(), SyntaxKind::Colon)
836 || (matches!(
837 node.kind(),
838 SyntaxKind::Text | SyntaxKind::MathText | SyntaxKind::Error
839 ) && node.text().starts_with(":"))
840 }
841 && let Some(ref_syntax) = classify_ref(&node)
842 {
843 return Some(ref_syntax);
844 }
845
846 if node.kind() == SyntaxKind::Text
847 && node.offset() + 1 == cursor
848 && node.text().starts_with('@')
849 {
850 return Some(SyntaxClass::Ref {
851 node,
852 suffix_colon: false,
853 });
854 }
855
856 if matches!(node.kind(), SyntaxKind::Text | SyntaxKind::MathText) {
858 let mode = interpret_mode_at(Some(&node));
859 if matches!(mode, InterpretMode::Math) && is_ident_like(&node) {
860 return Some(SyntaxClass::VarAccess(VarClass::Ident(node)));
861 }
862 }
863
864 let ancestor = first_ancestor_expr(node)?;
866 crate::log_debug_ct!("first_ancestor_expr: {ancestor:?}");
867
868 let adjusted = adjust_expr(ancestor)?;
870 crate::log_debug_ct!("adjust_expr: {adjusted:?}");
871
872 let expr = adjusted.cast::<ast::Expr>()?;
874 Some(match expr {
875 ast::Expr::Label(..) => SyntaxClass::label(adjusted),
876 ast::Expr::Ref(..) => SyntaxClass::Ref {
877 node: adjusted,
878 suffix_colon: false,
879 },
880 ast::Expr::FuncCall(call) => SyntaxClass::Callee(adjusted.find(call.callee().span())?),
881 ast::Expr::SetRule(set) => SyntaxClass::Callee(adjusted.find(set.target().span())?),
882 ast::Expr::Ident(..) | ast::Expr::MathIdent(..) => {
883 SyntaxClass::VarAccess(VarClass::Ident(adjusted))
884 }
885 ast::Expr::FieldAccess(..) => SyntaxClass::VarAccess(VarClass::FieldAccess(adjusted)),
886 ast::Expr::Str(..) => {
887 let parent = adjusted.parent()?;
888 if parent.kind() == SyntaxKind::ModuleImport {
889 SyntaxClass::ImportPath(adjusted)
890 } else if parent.kind() == SyntaxKind::ModuleInclude {
891 SyntaxClass::IncludePath(adjusted)
892 } else {
893 SyntaxClass::Normal(adjusted.kind(), adjusted)
894 }
895 }
896 _ if expr.hash()
897 || matches!(adjusted.kind(), SyntaxKind::MathIdent | SyntaxKind::Error) =>
898 {
899 SyntaxClass::Normal(adjusted.kind(), adjusted)
900 }
901 _ => return None,
902 })
903}
904
905fn possible_in_code_trivia(kind: SyntaxKind) -> bool {
908 !matches!(
909 interpret_mode_at_kind(kind),
910 Some(InterpretMode::Markup | InterpretMode::Math | InterpretMode::Comment)
911 )
912}
913
914#[derive(Debug, Clone)]
916pub enum ArgClass<'a> {
917 Positional {
919 spreads: EcoVec<LinkedNode<'a>>,
921 positional: usize,
923 is_spread: bool,
925 },
926 Named(LinkedNode<'a>),
928}
929
930impl ArgClass<'_> {
931 pub fn first_positional() -> Self {
933 ArgClass::Positional {
934 spreads: EcoVec::new(),
935 positional: 0,
936 is_spread: false,
937 }
938 }
939}
940
941#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, strum::EnumIter)]
944pub enum SurroundingSyntax {
945 Regular,
947 StringContent,
949 Selector,
951 ShowTransform,
953 ImportList,
955 SetRule,
957 ParamList,
959}
960
961pub fn surrounding_syntax(node: &LinkedNode) -> SurroundingSyntax {
963 check_previous_syntax(node)
964 .or_else(|| check_surrounding_syntax(node))
965 .unwrap_or(SurroundingSyntax::Regular)
966}
967
968fn check_surrounding_syntax(mut leaf: &LinkedNode) -> Option<SurroundingSyntax> {
969 use SurroundingSyntax::*;
970 let mut met_args = false;
971
972 if matches!(leaf.kind(), SyntaxKind::Str) {
973 return Some(StringContent);
974 }
975
976 while let Some(parent) = leaf.parent() {
977 crate::log_debug_ct!(
978 "check_surrounding_syntax: {:?}::{:?}",
979 parent.kind(),
980 leaf.kind()
981 );
982 match parent.kind() {
983 SyntaxKind::CodeBlock
984 | SyntaxKind::ContentBlock
985 | SyntaxKind::Equation
986 | SyntaxKind::Closure => {
987 return Some(Regular);
988 }
989 SyntaxKind::ImportItemPath
990 | SyntaxKind::ImportItems
991 | SyntaxKind::RenamedImportItem => {
992 return Some(ImportList);
993 }
994 SyntaxKind::ModuleImport => {
995 let colon = parent.children().find(|s| s.kind() == SyntaxKind::Colon);
996 let Some(colon) = colon else {
997 return Some(Regular);
998 };
999
1000 if leaf.offset() >= colon.offset() {
1001 return Some(ImportList);
1002 } else {
1003 return Some(Regular);
1004 }
1005 }
1006 SyntaxKind::Named => {
1007 let colon = parent.children().find(|s| s.kind() == SyntaxKind::Colon);
1008 let Some(colon) = colon else {
1009 return Some(Regular);
1010 };
1011
1012 return if leaf.offset() >= colon.offset() {
1013 Some(Regular)
1014 } else if node_ancestors(leaf).any(|n| n.kind() == SyntaxKind::Params) {
1015 Some(ParamList)
1016 } else {
1017 Some(Regular)
1018 };
1019 }
1020 SyntaxKind::Params => {
1021 return Some(ParamList);
1022 }
1023 SyntaxKind::Args => {
1024 met_args = true;
1025 }
1026 SyntaxKind::SetRule => {
1027 let rule = parent.get().cast::<ast::SetRule>()?;
1028 if met_args || enclosed_by(parent, rule.condition().map(|s| s.span()), leaf) {
1029 return Some(Regular);
1030 } else {
1031 return Some(SetRule);
1032 }
1033 }
1034 SyntaxKind::ShowRule => {
1035 if met_args {
1036 return Some(Regular);
1037 }
1038
1039 let rule = parent.get().cast::<ast::ShowRule>()?;
1040 let colon = rule
1041 .to_untyped()
1042 .children()
1043 .find(|s| s.kind() == SyntaxKind::Colon);
1044 let Some(colon) = colon.and_then(|colon| parent.find(colon.span())) else {
1045 return Some(Selector);
1047 };
1048
1049 if leaf.offset() >= colon.offset() {
1050 return Some(ShowTransform);
1051 } else {
1052 return Some(Selector); }
1054 }
1055 _ => {}
1056 }
1057
1058 leaf = parent;
1059 }
1060
1061 None
1062}
1063
1064fn check_previous_syntax(leaf: &LinkedNode) -> Option<SurroundingSyntax> {
1066 let mut leaf = leaf.clone();
1067 if leaf.kind().is_trivia() {
1068 leaf = leaf.prev_sibling()?;
1069 }
1070 if matches!(
1071 leaf.kind(),
1072 SyntaxKind::ShowRule
1073 | SyntaxKind::SetRule
1074 | SyntaxKind::ModuleImport
1075 | SyntaxKind::ModuleInclude
1076 ) {
1077 return check_surrounding_syntax(&leaf.rightmost_leaf()?);
1078 }
1079
1080 if matches!(leaf.kind(), SyntaxKind::Show) {
1081 return Some(SurroundingSyntax::Selector);
1082 }
1083 if matches!(leaf.kind(), SyntaxKind::Set) {
1084 return Some(SurroundingSyntax::SetRule);
1085 }
1086
1087 None
1088}
1089
1090fn enclosed_by(parent: &LinkedNode, s: Option<Span>, leaf: &LinkedNode) -> bool {
1092 s.and_then(|s| parent.find(s)?.find(leaf.span())).is_some()
1093}
1094
1095#[derive(Debug, Clone)]
1103pub enum SyntaxContext<'a> {
1104 Arg {
1106 callee: LinkedNode<'a>,
1108 args: LinkedNode<'a>,
1110 target: ArgClass<'a>,
1112 is_set: bool,
1114 },
1115 Element {
1117 container: LinkedNode<'a>,
1119 target: ArgClass<'a>,
1121 },
1122 Paren {
1124 container: LinkedNode<'a>,
1126 is_before: bool,
1129 },
1130 VarAccess(VarClass<'a>),
1134 ImportPath(LinkedNode<'a>),
1136 IncludePath(LinkedNode<'a>),
1138 Label {
1140 node: LinkedNode<'a>,
1142 is_error: bool,
1144 },
1145 Ref {
1147 node: LinkedNode<'a>,
1149 suffix_colon: bool,
1152 },
1153 Normal(LinkedNode<'a>),
1155}
1156
1157impl<'a> SyntaxContext<'a> {
1158 pub fn node(&self) -> Option<LinkedNode<'a>> {
1160 Some(match self {
1161 SyntaxContext::Arg { target, .. } | SyntaxContext::Element { target, .. } => {
1162 match target {
1163 ArgClass::Positional { .. } => return None,
1164 ArgClass::Named(node) => node.clone(),
1165 }
1166 }
1167 SyntaxContext::VarAccess(cls) => cls.node().clone(),
1168 SyntaxContext::Paren { container, .. } => container.clone(),
1169 SyntaxContext::Label { node, .. }
1170 | SyntaxContext::Ref { node, .. }
1171 | SyntaxContext::ImportPath(node)
1172 | SyntaxContext::IncludePath(node)
1173 | SyntaxContext::Normal(node) => node.clone(),
1174 })
1175 }
1176
1177 pub fn arg_container(&self) -> Option<&LinkedNode<'a>> {
1179 match self {
1180 Self::Arg { args, .. }
1181 | Self::Element {
1182 container: args, ..
1183 } => Some(args),
1184 Self::Paren { container, .. } => Some(container),
1185 _ => None,
1186 }
1187 }
1188}
1189
1190#[derive(Debug)]
1192enum ArgSourceKind {
1193 Call,
1195 Array,
1197 Dict,
1199}
1200
1201pub fn classify_context_outer<'a>(
1204 outer: LinkedNode<'a>,
1205 node: LinkedNode<'a>,
1206) -> Option<SyntaxContext<'a>> {
1207 use SyntaxClass::*;
1208 let context_syntax = classify_syntax(outer.clone(), node.offset())?;
1209 let node_syntax = classify_syntax(node.clone(), node.offset())?;
1210
1211 match context_syntax {
1212 Callee(callee)
1213 if matches!(node_syntax, Normal(..) | Label { .. } | Ref { .. })
1214 && !matches!(node_syntax, Callee(..)) =>
1215 {
1216 let parent = callee.parent()?;
1217 let args = match parent.cast::<ast::Expr>() {
1218 Some(ast::Expr::FuncCall(call)) => call.args(),
1219 Some(ast::Expr::SetRule(set)) => set.args(),
1220 _ => return None,
1221 };
1222 let args = parent.find(args.span())?;
1223
1224 let is_set = parent.kind() == SyntaxKind::SetRule;
1225 let arg_target = arg_context(args.clone(), node, ArgSourceKind::Call)?;
1226 Some(SyntaxContext::Arg {
1227 callee,
1228 args,
1229 target: arg_target,
1230 is_set,
1231 })
1232 }
1233 _ => None,
1234 }
1235}
1236
1237pub fn classify_context(node: LinkedNode<'_>, cursor: Option<usize>) -> Option<SyntaxContext<'_>> {
1240 let mut node = node;
1241 if node.kind().is_trivia() && node.parent_kind().is_some_and(possible_in_code_trivia) {
1242 loop {
1243 node = node.prev_sibling()?;
1244
1245 if !node.kind().is_trivia() {
1246 break;
1247 }
1248 }
1249 }
1250
1251 let cursor = cursor.unwrap_or_else(|| node.offset());
1252 let syntax = classify_syntax(node.clone(), cursor)?;
1253
1254 let normal_syntax = match syntax {
1255 SyntaxClass::Callee(callee) => {
1256 return callee_context(callee, node);
1257 }
1258 SyntaxClass::Label { node, is_error } => {
1259 return Some(SyntaxContext::Label { node, is_error });
1260 }
1261 SyntaxClass::Ref { node, suffix_colon } => {
1262 return Some(SyntaxContext::Ref { node, suffix_colon });
1263 }
1264 SyntaxClass::ImportPath(node) => {
1265 return Some(SyntaxContext::ImportPath(node));
1266 }
1267 SyntaxClass::IncludePath(node) => {
1268 return Some(SyntaxContext::IncludePath(node));
1269 }
1270 syntax => syntax,
1271 };
1272
1273 let Some(mut node_parent) = node.parent().cloned() else {
1274 return Some(SyntaxContext::Normal(node));
1275 };
1276
1277 while let SyntaxKind::Named | SyntaxKind::Colon = node_parent.kind() {
1278 let Some(parent) = node_parent.parent() else {
1279 return Some(SyntaxContext::Normal(node));
1280 };
1281 node_parent = parent.clone();
1282 }
1283
1284 match node_parent.kind() {
1285 SyntaxKind::Args => {
1286 let callee = node_ancestors(&node_parent).find_map(|ancestor| {
1287 let span = match ancestor.cast::<ast::Expr>()? {
1288 ast::Expr::FuncCall(call) => call.callee().span(),
1289 ast::Expr::SetRule(set) => set.target().span(),
1290 _ => return None,
1291 };
1292 ancestor.find(span)
1293 })?;
1294
1295 let param_node = match node.kind() {
1296 SyntaxKind::Ident
1297 if matches!(
1298 node.parent_kind().zip(node.next_sibling_kind()),
1299 Some((SyntaxKind::Named, SyntaxKind::Colon))
1300 ) =>
1301 {
1302 node
1303 }
1304 _ if matches!(node.parent_kind(), Some(SyntaxKind::Named)) => {
1305 node.parent().cloned()?
1306 }
1307 _ => node,
1308 };
1309
1310 callee_context(callee, param_node)
1311 }
1312 SyntaxKind::Array | SyntaxKind::Dict => {
1313 let element_target = arg_context(
1314 node_parent.clone(),
1315 node.clone(),
1316 match node_parent.kind() {
1317 SyntaxKind::Array => ArgSourceKind::Array,
1318 SyntaxKind::Dict => ArgSourceKind::Dict,
1319 _ => unreachable!(),
1320 },
1321 )?;
1322 Some(SyntaxContext::Element {
1323 container: node_parent.clone(),
1324 target: element_target,
1325 })
1326 }
1327 SyntaxKind::Parenthesized => {
1328 let is_before = node.offset() <= node_parent.offset() + 1;
1329 Some(SyntaxContext::Paren {
1330 container: node_parent.clone(),
1331 is_before,
1332 })
1333 }
1334 _ => Some(match normal_syntax {
1335 SyntaxClass::VarAccess(v) => SyntaxContext::VarAccess(v),
1336 normal_syntax => SyntaxContext::Normal(normal_syntax.node().clone()),
1337 }),
1338 }
1339}
1340
1341fn callee_context<'a>(callee: LinkedNode<'a>, node: LinkedNode<'a>) -> Option<SyntaxContext<'a>> {
1343 let parent = callee.parent()?;
1344 let args = match parent.cast::<ast::Expr>() {
1345 Some(ast::Expr::FuncCall(call)) => call.args(),
1346 Some(ast::Expr::SetRule(set)) => set.args(),
1347 _ => return None,
1348 };
1349 let args = parent.find(args.span())?;
1350
1351 let mut parent = &node;
1352 loop {
1353 use SyntaxKind::*;
1354 match parent.kind() {
1355 ContentBlock | CodeBlock | Str | Raw | LineComment | BlockComment => {
1356 return Option::None;
1357 }
1358 Args if parent.range() == args.range() => {
1359 break;
1360 }
1361 _ => {}
1362 }
1363
1364 parent = parent.parent()?;
1365 }
1366
1367 let is_set = parent.kind() == SyntaxKind::SetRule;
1368 let target = arg_context(args.clone(), node, ArgSourceKind::Call)?;
1369 Some(SyntaxContext::Arg {
1370 callee,
1371 args,
1372 target,
1373 is_set,
1374 })
1375}
1376
1377fn arg_context<'a>(
1379 args_node: LinkedNode<'a>,
1380 mut node: LinkedNode<'a>,
1381 param_kind: ArgSourceKind,
1382) -> Option<ArgClass<'a>> {
1383 if node.kind() == SyntaxKind::RightParen {
1384 node = node.prev_sibling()?;
1385 }
1386 match node.kind() {
1387 SyntaxKind::Named => {
1388 let param_ident = node.cast::<ast::Named>()?.name();
1389 Some(ArgClass::Named(args_node.find(param_ident.span())?))
1390 }
1391 SyntaxKind::Colon => {
1392 let prev = node.prev_leaf()?;
1393 let param_ident = prev.cast::<ast::Ident>()?;
1394 Some(ArgClass::Named(args_node.find(param_ident.span())?))
1395 }
1396 _ => {
1397 let parent = node.parent();
1398 if let Some(parent) = parent
1399 && parent.kind() == SyntaxKind::Named
1400 {
1401 let param_ident = parent.cast::<ast::Named>()?;
1402 let name = param_ident.name();
1403 let init = param_ident.expr();
1404 let init = parent.find(init.span())?;
1405 if init.range().contains(&node.offset()) {
1406 let name = args_node.find(name.span())?;
1407 return Some(ArgClass::Named(name));
1408 }
1409 }
1410
1411 let mut spreads = EcoVec::new();
1412 let mut positional = 0;
1413 let is_spread = node.kind() == SyntaxKind::Spread;
1414
1415 let args_before = args_node
1416 .children()
1417 .take_while(|arg| arg.range().end <= node.offset());
1418 match param_kind {
1419 ArgSourceKind::Call => {
1420 for ch in args_before {
1421 match ch.cast::<ast::Arg>() {
1422 Some(ast::Arg::Pos(..)) => {
1423 positional += 1;
1424 }
1425 Some(ast::Arg::Spread(..)) => {
1426 spreads.push(ch);
1427 }
1428 Some(ast::Arg::Named(..)) | None => {}
1429 }
1430 }
1431 }
1432 ArgSourceKind::Array => {
1433 for ch in args_before {
1434 match ch.cast::<ast::ArrayItem>() {
1435 Some(ast::ArrayItem::Pos(..)) => {
1436 positional += 1;
1437 }
1438 Some(ast::ArrayItem::Spread(..)) => {
1439 spreads.push(ch);
1440 }
1441 _ => {}
1442 }
1443 }
1444 }
1445 ArgSourceKind::Dict => {
1446 for ch in args_before {
1447 if let Some(ast::DictItem::Spread(..)) = ch.cast::<ast::DictItem>() {
1448 spreads.push(ch);
1449 }
1450 }
1451 }
1452 }
1453
1454 Some(ArgClass::Positional {
1455 spreads,
1456 positional,
1457 is_spread,
1458 })
1459 }
1460 }
1461}
1462
1463pub enum BadCompletionCursor {
1465 ArgListPos,
1467}
1468
1469pub fn bad_completion_cursor(
1471 syntax: Option<&SyntaxClass>,
1472 syntax_context: Option<&SyntaxContext>,
1473 leaf: &LinkedNode,
1474) -> Option<BadCompletionCursor> {
1475 if (matches!(syntax, Some(SyntaxClass::Callee(..))) && {
1477 syntax_context
1478 .and_then(SyntaxContext::arg_container)
1479 .is_some_and(|container| {
1480 container.rightmost_leaf().map(|s| s.offset()) == Some(leaf.offset())
1481 })
1482 }) || (matches!(
1484 syntax,
1485 Some(SyntaxClass::Normal(SyntaxKind::ContentBlock, _))
1486 ) && matches!(leaf.kind(), SyntaxKind::RightBracket))
1487 {
1488 return Some(BadCompletionCursor::ArgListPos);
1489 }
1490
1491 None
1492}
1493
1494#[cfg(test)]
1495mod tests {
1496 use super::*;
1497 use insta::assert_snapshot;
1498 use typst::syntax::{Side, Source, is_newline};
1499
1500 fn map_node(source: &str, mapper: impl Fn(&LinkedNode, usize) -> char) -> String {
1501 let source = Source::detached(source.to_owned());
1502 let root = LinkedNode::new(source.root());
1503 let mut output_mapping = String::new();
1504
1505 let mut cursor = 0;
1506 for ch in source.text().chars() {
1507 cursor += ch.len_utf8();
1508 if is_newline(ch) {
1509 output_mapping.push(ch);
1510 continue;
1511 }
1512
1513 output_mapping.push(mapper(&root, cursor));
1514 }
1515
1516 source
1517 .text()
1518 .lines()
1519 .zip(output_mapping.lines())
1520 .flat_map(|(a, b)| [a, "\n", b, "\n"])
1521 .collect::<String>()
1522 }
1523
1524 fn map_syntax(source: &str) -> String {
1525 map_node(source, |root, cursor| {
1526 let node = root.leaf_at(cursor, Side::Before);
1527 let kind = node.and_then(|node| classify_syntax(node, cursor));
1528 match kind {
1529 Some(SyntaxClass::VarAccess(..)) => 'v',
1530 Some(SyntaxClass::Normal(..)) => 'n',
1531 Some(SyntaxClass::Label { .. }) => 'l',
1532 Some(SyntaxClass::Ref { .. }) => 'r',
1533 Some(SyntaxClass::Callee(..)) => 'c',
1534 Some(SyntaxClass::ImportPath(..)) => 'i',
1535 Some(SyntaxClass::IncludePath(..)) => 'I',
1536 None => ' ',
1537 }
1538 })
1539 }
1540
1541 fn map_context(source: &str) -> String {
1542 map_node(source, |root, cursor| {
1543 let node = root.leaf_at(cursor, Side::Before);
1544 let kind = node.and_then(|node| classify_context(node, Some(cursor)));
1545 match kind {
1546 Some(SyntaxContext::Arg { .. }) => 'p',
1547 Some(SyntaxContext::Element { .. }) => 'e',
1548 Some(SyntaxContext::Paren { .. }) => 'P',
1549 Some(SyntaxContext::VarAccess { .. }) => 'v',
1550 Some(SyntaxContext::ImportPath(..)) => 'i',
1551 Some(SyntaxContext::IncludePath(..)) => 'I',
1552 Some(SyntaxContext::Label { .. }) => 'l',
1553 Some(SyntaxContext::Ref { .. }) => 'r',
1554 Some(SyntaxContext::Normal(..)) => 'n',
1555 None => ' ',
1556 }
1557 })
1558 }
1559
1560 #[test]
1561 fn test_get_syntax() {
1562 assert_snapshot!(map_syntax(r#"#let x = 1
1563Text
1564= Heading #let y = 2;
1565== Heading"#).trim(), @r"
1566 #let x = 1
1567 nnnnvvnnn
1568 Text
1569
1570 = Heading #let y = 2;
1571 nnnnvvnnn
1572 == Heading
1573 ");
1574 assert_snapshot!(map_syntax(r#"#let f(x);"#).trim(), @r"
1575 #let f(x);
1576 nnnnv v
1577 ");
1578 assert_snapshot!(map_syntax(r#"#{
1579 calc.
1580}"#).trim(), @r"
1581 #{
1582 n
1583 calc.
1584 nnvvvvvnn
1585 }
1586 n
1587 ");
1588 }
1589
1590 #[test]
1591 fn test_get_context() {
1592 assert_snapshot!(map_context(r#"#let x = 1
1593Text
1594= Heading #let y = 2;
1595== Heading"#).trim(), @r"
1596 #let x = 1
1597 nnnnvvnnn
1598 Text
1599
1600 = Heading #let y = 2;
1601 nnnnvvnnn
1602 == Heading
1603 ");
1604 assert_snapshot!(map_context(r#"#let f(x);"#).trim(), @r"
1605 #let f(x);
1606 nnnnv v
1607 ");
1608 assert_snapshot!(map_context(r#"#f(1, 2) Test"#).trim(), @r"
1609 #f(1, 2) Test
1610 vpppppp
1611 ");
1612 assert_snapshot!(map_context(r#"#() Test"#).trim(), @r"
1613 #() Test
1614 ee
1615 ");
1616 assert_snapshot!(map_context(r#"#(1) Test"#).trim(), @r"
1617 #(1) Test
1618 PPP
1619 ");
1620 assert_snapshot!(map_context(r#"#(a: 1) Test"#).trim(), @r"
1621 #(a: 1) Test
1622 eeeeee
1623 ");
1624 assert_snapshot!(map_context(r#"#(1, 2) Test"#).trim(), @r"
1625 #(1, 2) Test
1626 eeeeee
1627 ");
1628 assert_snapshot!(map_context(r#"#(1, 2)
1629 Test"#).trim(), @r"
1630 #(1, 2)
1631 eeeeee
1632 Test
1633 ");
1634 }
1635
1636 #[test]
1637 fn ref_syntxax() {
1638 assert_snapshot!(map_syntax("@ab:"), @r###"
1639 @ab:
1640 rrrr
1641 "###);
1642 }
1643
1644 #[test]
1645 fn ref_syntax() {
1646 assert_snapshot!(map_syntax("@"), @r"
1647 @
1648 r
1649 ");
1650 assert_snapshot!(map_syntax("@;"), @r"
1651 @;
1652 r
1653 ");
1654 assert_snapshot!(map_syntax("@ab"), @r###"
1655 @ab
1656 rrr
1657 "###);
1658 assert_snapshot!(map_syntax("@ab:"), @r###"
1659 @ab:
1660 rrrr
1661 "###);
1662 assert_snapshot!(map_syntax("@ab:ab"), @r###"
1663 @ab:ab
1664 rrrrrr
1665 "###);
1666 assert_snapshot!(map_syntax("@ab:ab:"), @r###"
1667 @ab:ab:
1668 rrrrrrr
1669 "###);
1670 assert_snapshot!(map_syntax("@ab:ab:ab"), @r###"
1671 @ab:ab:ab
1672 rrrrrrrrr
1673 "###);
1674 assert_snapshot!(map_syntax("@ab[]:"), @r###"
1675 @ab[]:
1676 rrrnn
1677 "###);
1678 assert_snapshot!(map_syntax("@ab[ab]:"), @r###"
1679 @ab[ab]:
1680 rrrn n
1681 "###);
1682 assert_snapshot!(map_syntax("@ab :ab: ab"), @r###"
1683 @ab :ab: ab
1684 rrr
1685 "###);
1686 assert_snapshot!(map_syntax("@ab :ab:ab"), @r###"
1687 @ab :ab:ab
1688 rrr
1689 "###);
1690 }
1691
1692 fn access_node(s: &str, cursor: i32) -> String {
1693 access_node_(s, cursor).unwrap_or_default()
1694 }
1695
1696 fn access_node_(s: &str, cursor: i32) -> Option<String> {
1697 access_var(s, cursor, |_source, var| {
1698 Some(var.accessed_node()?.get().clone().into_text().into())
1699 })
1700 }
1701
1702 fn access_field(s: &str, cursor: i32) -> String {
1703 access_field_(s, cursor).unwrap_or_default()
1704 }
1705
1706 fn access_field_(s: &str, cursor: i32) -> Option<String> {
1707 access_var(s, cursor, |source, var| {
1708 let field = var.accessing_field()?;
1709 Some(match field {
1710 FieldClass::Field(ident) => format!("Field: {}", ident.text()),
1711 FieldClass::DotSuffix(span_offset) => {
1712 let offset = source.find(span_offset.span)?.offset() + span_offset.offset;
1713 format!("DotSuffix: {offset:?}")
1714 }
1715 })
1716 })
1717 }
1718
1719 fn access_var(
1720 s: &str,
1721 cursor: i32,
1722 f: impl FnOnce(&Source, VarClass) -> Option<String>,
1723 ) -> Option<String> {
1724 let cursor = if cursor < 0 {
1725 s.len() as i32 + cursor
1726 } else {
1727 cursor
1728 };
1729 let source = Source::detached(s.to_owned());
1730 let root = LinkedNode::new(source.root());
1731 let node = root.leaf_at(cursor as usize, Side::Before)?;
1732 let syntax = classify_syntax(node, cursor as usize)?;
1733 let SyntaxClass::VarAccess(var) = syntax else {
1734 return None;
1735 };
1736 f(&source, var)
1737 }
1738
1739 #[test]
1740 fn test_access_field() {
1741 assert_snapshot!(access_field("#(a.b)", 5), @r"Field: b");
1742 assert_snapshot!(access_field("#a.", 3), @"DotSuffix: 3");
1743 assert_snapshot!(access_field("$a.$", 3), @"DotSuffix: 3");
1744 assert_snapshot!(access_field("#(a.)", 4), @"DotSuffix: 4");
1745 assert_snapshot!(access_node("#(a..b)", 4), @"a");
1746 assert_snapshot!(access_field("#(a..b)", 4), @"DotSuffix: 4");
1747 assert_snapshot!(access_node("#(a..b())", 4), @"a");
1748 assert_snapshot!(access_field("#(a..b())", 4), @"DotSuffix: 4");
1749 }
1750
1751 #[test]
1752 fn test_code_access() {
1753 assert_snapshot!(access_node("#{`a`.}", 6), @"`a`");
1754 assert_snapshot!(access_field("#{`a`.}", 6), @"DotSuffix: 6");
1755 assert_snapshot!(access_node("#{$a$.}", 6), @"$a$");
1756 assert_snapshot!(access_field("#{$a$.}", 6), @"DotSuffix: 6");
1757 assert_snapshot!(access_node("#{\"a\".}", 6), @"\"a\"");
1758 assert_snapshot!(access_field("#{\"a\".}", 6), @"DotSuffix: 6");
1759 assert_snapshot!(access_node("#{<a>.}", 6), @"<a>");
1760 assert_snapshot!(access_field("#{<a>.}", 6), @"DotSuffix: 6");
1761 }
1762
1763 #[test]
1764 fn test_markup_access() {
1765 assert_snapshot!(access_field("_a_.", 4), @"");
1766 assert_snapshot!(access_field("*a*.", 4), @"");
1767 assert_snapshot!(access_field("`a`.", 4), @"");
1768 assert_snapshot!(access_field("$a$.", 4), @"");
1769 assert_snapshot!(access_field("\"a\".", 4), @"");
1770 assert_snapshot!(access_field("@a.", 3), @"");
1771 assert_snapshot!(access_field("<a>.", 4), @"");
1772 }
1773
1774 #[test]
1775 fn test_markup_chain_access() {
1776 assert_snapshot!(access_node("#a.b.", 5), @"a.b");
1777 assert_snapshot!(access_field("#a.b.", 5), @"DotSuffix: 5");
1778 assert_snapshot!(access_node("#a.b.c.", 7), @"a.b.c");
1779 assert_snapshot!(access_field("#a.b.c.", 7), @"DotSuffix: 7");
1780 assert_snapshot!(access_node("#context a.", 11), @"a");
1781 assert_snapshot!(access_field("#context a.", 11), @"DotSuffix: 11");
1782 assert_snapshot!(access_node("#context a.b.", 13), @"a.b");
1783 assert_snapshot!(access_field("#context a.b.", 13), @"DotSuffix: 13");
1784
1785 assert_snapshot!(access_node("#a.at(1).", 9), @"a.at(1)");
1786 assert_snapshot!(access_field("#a.at(1).", 9), @"DotSuffix: 9");
1787 assert_snapshot!(access_node("#context a.at(1).", 17), @"a.at(1)");
1788 assert_snapshot!(access_field("#context a.at(1).", 17), @"DotSuffix: 17");
1789
1790 assert_snapshot!(access_node("#a.at(1).c.", 11), @"a.at(1).c");
1791 assert_snapshot!(access_field("#a.at(1).c.", 11), @"DotSuffix: 11");
1792 assert_snapshot!(access_node("#context a.at(1).c.", 19), @"a.at(1).c");
1793 assert_snapshot!(access_field("#context a.at(1).c.", 19), @"DotSuffix: 19");
1794 }
1795
1796 #[test]
1797 fn test_hash_access() {
1798 assert_snapshot!(access_node("#a.", 3), @"a");
1799 assert_snapshot!(access_field("#a.", 3), @"DotSuffix: 3");
1800 assert_snapshot!(access_node("#(a).", 5), @"(a)");
1801 assert_snapshot!(access_field("#(a).", 5), @"DotSuffix: 5");
1802 assert_snapshot!(access_node("#`a`.", 5), @"`a`");
1803 assert_snapshot!(access_field("#`a`.", 5), @"DotSuffix: 5");
1804 assert_snapshot!(access_node("#$a$.", 5), @"$a$");
1805 assert_snapshot!(access_field("#$a$.", 5), @"DotSuffix: 5");
1806 assert_snapshot!(access_node("#(a,).", 6), @"(a,)");
1807 assert_snapshot!(access_field("#(a,).", 6), @"DotSuffix: 6");
1808 }
1809}