tinymist_analysis/syntax/
matcher.rs

1//! Convenient utilities to match syntax structures of code.
2//! - Iterators/Finders to traverse nodes.
3//! - Predicates to check nodes' properties.
4//! - Classifiers to check nodes' syntaxes.
5//!
6//! ## Classifiers of syntax structures
7//!
8//! A node can have a quadruple to describe its syntax:
9//!
10//! ```text
11//! (InterpretMode, SurroundingSyntax/SyntaxContext, DefClass/SyntaxClass, SyntaxNode)
12//! ```
13//!
14//! Among them, [`InterpretMode`], [`SurroundingSyntax`], and [`SyntaxContext`]
15//! describes outer syntax. [`DefClass`], [`SyntaxClass`] and
16//! [`typst::syntax::SyntaxNode`] describes inner syntax.
17//!
18//! - [`typst::syntax::SyntaxNode`]: Its contextual version is
19//!   [`typst::syntax::LinkedNode`], containing AST information, like inner text
20//!   and [`SyntaxKind`], on the position.
21//! - [`SyntaxClass`]: Provided by [`classify_syntax`], it describes the
22//!   context-free syntax of the node that are more suitable for IDE operations.
23//!   For example, it identifies users' half-typed syntax like half-completed
24//!   labels and dot accesses.
25//! - [`DefClass`]: Provided by [`classify_def`], it describes the definition
26//!   class of the node at the position. The difference between `SyntaxClass`
27//!   and `DefClass` is that the latter matcher will skip the nodes that do not
28//!   define a definition.
29//! - [`SyntaxContext`]: Provided by [`classify_context`], it describes the
30//!   outer syntax of the node that are more suitable for IDE operations. For
31//!   example, it identifies the context of a cursor on the comma in a function
32//!   call.
33//! - [`SurroundingSyntax`]: Provided by [`surrounding_syntax`], it describes
34//!   the surrounding syntax of the node that are more suitable for IDE
35//!   operations. The difference between `SyntaxContext` and `SurroundingSyntax`
36//!   is that the former is more specific and the latter is more general can be
37//!   used for filtering customized snippets.
38//! - [`InterpretMode`]: Provided by [`interpret_mode_at`], it describes the how
39//!   an interpreter should interpret the code at the position.
40//!
41//! Some examples of the quadruple (the cursor is marked by `|`):
42//!
43//! ```text
44//! #(x|);
45//!    ^ SyntaxContext::Paren, SyntaxClass::Normal(SyntaxKind::Ident)
46//! #(x,|);
47//!     ^ SyntaxContext::Element, SyntaxClass::Normal(SyntaxKind::Array)
48//! #f(x,|);
49//!      ^ SyntaxContext::Arg, SyntaxClass::Normal(SyntaxKind::FuncCall)
50//! ```
51//!
52//! ```text
53//! #show raw|: |it => it|
54//!          ^ SurroundingSyntax::Selector
55//!             ^ SurroundingSyntax::ShowTransform
56//!                      ^ SurroundingSyntax::Regular
57//! ```
58
59use serde::{Deserialize, Serialize};
60use tinymist_world::debug_loc::SourceSpanOffset;
61use typst::syntax::Span;
62
63use crate::prelude::*;
64
65/// Returns the ancestor iterator of the given node.
66pub 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
72/// Finds the first ancestor node that is an expression.
73pub 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                // Since typst matches `field()` by `case_last_match`, when the field access
91                // `x.` (`Ident(x).Error("")`), it will match the `x` as the
92                // field. We need to check dot position to filter out such cases.
93                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
107/// A node that is an ancestor of the given node or the previous sibling
108/// of some ancestor.
109pub enum PreviousItem<'a> {
110    /// When the iterator is crossing an ancesstor node.
111    Parent(&'a LinkedNode<'a>, &'a LinkedNode<'a>),
112    /// When the iterator is on a sibling node of some ancestor.
113    Sibling(&'a LinkedNode<'a>),
114}
115
116impl<'a> PreviousItem<'a> {
117    /// Gets the underlying [`LinkedNode`] of the item.
118    pub fn node(&self) -> &'a LinkedNode<'a> {
119        match self {
120            PreviousItem::Sibling(node) => node,
121            PreviousItem::Parent(node, _) => node,
122        }
123    }
124}
125
126/// Finds the previous items (in the scope) starting from the given position
127/// inclusively. See [`PreviousItem`] for the possible items.
128pub 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
158/// A declaration that is an ancestor of the given node or the previous sibling
159/// of some ancestor.
160pub enum PreviousDecl<'a> {
161    /// An declaration having an identifier.
162    ///
163    /// ## Example
164    ///
165    /// The `x` in the following code:
166    ///
167    /// ```typst
168    /// #let x = 1;
169    /// ```
170    Ident(ast::Ident<'a>),
171    /// An declaration yielding from an import source.
172    ///
173    /// ## Example
174    ///
175    /// The `x` in the following code:
176    ///
177    /// ```typst
178    /// #import "path.typ": x;
179    /// ```
180    ImportSource(ast::Expr<'a>),
181    /// A wildcard import that possibly containing visible declarations.
182    ///
183    /// ## Example
184    ///
185    /// The following import is matched:
186    ///
187    /// ```typst
188    /// #import "path.typ": *;
189    /// ```
190    ImportAll(ast::ModuleImport<'a>),
191}
192
193/// Finds the previous declarations starting from the given position. It checks
194/// [`PreviousItem`] and returns the found declarations.
195pub 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                // import items
210                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                // import itself
227                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
287/// Checks if the node can be recognized as a mark.
288pub 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
300/// Checks if the node can be recognized as an identifier.
301pub 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/// A mode in which a text document is interpreted.
314#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, strum::EnumIter)]
315#[serde(rename_all = "camelCase")]
316pub enum InterpretMode {
317    /// The position is in a comment.
318    Comment,
319    /// The position is in a string.
320    String,
321    /// The position is in a raw.
322    Raw,
323    /// The position is in a markup block.
324    Markup,
325    /// The position is in a code block.
326    Code,
327    /// The position is in a math equation.
328    Math,
329}
330
331/// Determines the interpretation mode at the given position
332/// (context-sensitive).
333pub 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                // Previous leaf is hash
343                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
355/// Determines the interpretation mode at the given kind (context-free).
356pub(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/// Classes of def items that can be operated on by IDE functionality.
388#[derive(Debug, Clone)]
389pub enum DefClass<'a> {
390    /// A let binding item.
391    Let(LinkedNode<'a>),
392    /// A module import item.
393    Import(LinkedNode<'a>),
394}
395
396impl DefClass<'_> {
397    /// Gets the node of the def class.
398    pub fn node(&self) -> &LinkedNode<'_> {
399        match self {
400            DefClass::Let(node) => node,
401            DefClass::Import(node) => node,
402        }
403    }
404
405    /// Gets the name node of the def class.
406    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                // let ident = node.cast::<ast::ImportItem>()?;
422                // Some(ident.span().into())
423                // todo: implement this
424                None
425            }
426        }
427    }
428
429    /// Gets the name's range in code of the def class.
430    pub fn name_range(&self) -> Option<Range<usize>> {
431        self.name().map(|node| node.range())
432    }
433}
434
435// todo: whether we should distinguish between strict and loose def classes
436/// Classifies a definition loosely.
437pub fn classify_def_loosely(node: LinkedNode<'_>) -> Option<DefClass<'_>> {
438    classify_def_(node, false)
439}
440
441/// Classifies a definition strictly.
442pub fn classify_def(node: LinkedNode<'_>) -> Option<DefClass<'_>> {
443    classify_def_(node, true)
444}
445
446/// The internal implementation of classifying a definition.
447fn 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        // todo: label, reference
468        // todo: include
469        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        // todo: parameter
474        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
501/// Adjusts an expression node to a more suitable one for classification.
502/// It is not formal, but the following cases are forbidden:
503/// - Parenthesized expression.
504/// - Identifier on the right side of a dot operator (field access).
505pub 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/// Classes of field syntax that can be operated on by IDE functionality.
519#[derive(Debug, Clone)]
520pub enum FieldClass<'a> {
521    /// A field node.
522    ///
523    /// ## Example
524    ///
525    /// The `x` in the following code:
526    ///
527    /// ```typst
528    /// #a.x
529    /// ```
530    Field(LinkedNode<'a>),
531
532    /// A dot suffix missing a field.
533    ///
534    /// ## Example
535    ///
536    /// The `.` in the following code:
537    ///
538    /// ```typst
539    /// #a.
540    /// ```
541    DotSuffix(SourceSpanOffset),
542}
543
544impl FieldClass<'_> {
545    /// Gets the node of the field class.
546    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/// Classes of variable (access) syntax that can be operated on by IDE
557/// functionality.
558#[derive(Debug, Clone)]
559pub enum VarClass<'a> {
560    /// An identifier expression.
561    Ident(LinkedNode<'a>),
562    /// A field access expression.
563    FieldAccess(LinkedNode<'a>),
564    /// A dot access expression, for example, `#a.|`, `$a.|$`, or `x.|.y`.
565    /// Note the cursor of the last example is on the middle of the spread
566    /// operator.
567    DotAccess(LinkedNode<'a>),
568}
569
570impl<'a> VarClass<'a> {
571    /// Gets the node of the var (access) class.
572    pub fn node(&self) -> &LinkedNode<'a> {
573        match self {
574            Self::Ident(node) | Self::FieldAccess(node) | Self::DotAccess(node) => node,
575        }
576    }
577
578    /// Gets the accessed node of the var (access) class.
579    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    /// Gets the accessing field of the var (access) class.
591    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/// Classes of syntax that can be operated on by IDE functionality.
634#[derive(Debug, Clone)]
635pub enum SyntaxClass<'a> {
636    /// A variable access expression.
637    ///
638    /// It can be either an identifier or a field access.
639    VarAccess(VarClass<'a>),
640    /// A (content) label expression.
641    Label {
642        /// The node of the label.
643        node: LinkedNode<'a>,
644        /// Whether the label is converted from an error node.
645        is_error: bool,
646    },
647    /// A (content) reference expression.
648    Ref {
649        /// The node of the reference.
650        node: LinkedNode<'a>,
651        /// A colon after a reference expression, for example, `@a:|` or
652        /// `@a:b:|`.
653        suffix_colon: bool,
654    },
655    /// A callee expression.
656    Callee(LinkedNode<'a>),
657    /// An import path expression.
658    ImportPath(LinkedNode<'a>),
659    /// An include path expression.
660    IncludePath(LinkedNode<'a>),
661    /// Rest kind of **expressions**.
662    Normal(SyntaxKind, LinkedNode<'a>),
663}
664
665impl<'a> SyntaxClass<'a> {
666    /// Creates a label syntax class.
667    pub fn label(node: LinkedNode<'a>) -> Self {
668        Self::Label {
669            node,
670            is_error: false,
671        }
672    }
673
674    /// Creates an error label syntax class.
675    pub fn error_as_label(node: LinkedNode<'a>) -> Self {
676        Self::Label {
677            node,
678            is_error: true,
679        }
680    }
681
682    /// Gets the node of the syntax class.
683    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    /// Gets the content offset at which the completion should be triggered.
696    pub fn complete_offset(&self) -> Option<usize> {
697        match self {
698            // `<label`
699            //   ^ node.offset() + 1
700            SyntaxClass::Label { node, .. } => Some(node.offset() + 1),
701            _ => None,
702        }
703    }
704}
705
706/// Classifies node's syntax (inner syntax) that can be operated on by IDE
707/// functionality.
708pub 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    /// Skips trivia nodes that are on the same line as the cursor.
714    fn can_skip_trivia(node: &LinkedNode, cursor: usize) -> bool {
715        // A non-trivia node is our target so we stop at it.
716        if !node.kind().is_trivia() || !node.parent_kind().is_some_and(possible_in_code_trivia) {
717            return false;
718        }
719
720        // Gets the trivia text before the cursor.
721        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        // The deref target should be on the same line as the cursor.
729        // Assuming the underlying text is utf-8 encoded, we can check for newlines by
730        // looking for b'\n'.
731        // todo: if we are in markup mode, we should check if we are at start of node
732        !previous_text.contains(&b'\n')
733    }
734
735    // Moves to the first non-trivia node before the cursor.
736    let mut node = node;
737    if can_skip_trivia(&node, cursor) {
738        node = node.prev_sibling()?;
739    }
740
741    /// Matches complete or incomplete dot accesses in code, math, and markup
742    /// mode.
743    ///
744    /// When in markup mode, the dot access is valid if the dot is after a hash
745    /// expression.
746    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        // Don't match `$ .| $`
751        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                // Don't match `$ a.| $` or `$.| $`
762                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            // Check if the cursor is exactly after single dot.
794            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    /// Matches ref parsing broken by a colon.
814    ///
815    /// When in markup mode, the ref is valid if the colon is after a ref
816    /// expression.
817    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            // Check if the cursor is exactly after single dot.
835            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    // todo: check if we can remove Text here
857    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    // Moves to the first ancestor that is an expression.
865    let ancestor = first_ancestor_expr(node)?;
866    crate::log_debug_ct!("first_ancestor_expr: {ancestor:?}");
867
868    // Unwraps all parentheses to get the actual expression.
869    let adjusted = adjust_expr(ancestor)?;
870    crate::log_debug_ct!("adjust_expr: {adjusted:?}");
871
872    // Identifies convenient expression kinds.
873    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
905/// Checks if the node might be in code trivia. This is a bit internal so please
906/// check the caller to understand it.
907fn 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/// Classes of arguments that can be operated on by IDE functionality.
915#[derive(Debug, Clone)]
916pub enum ArgClass<'a> {
917    /// A positional argument.
918    Positional {
919        /// The spread arguments met before the positional argument.
920        spreads: EcoVec<LinkedNode<'a>>,
921        /// The index of the positional argument.
922        positional: usize,
923        /// Whether the positional argument is a spread argument.
924        is_spread: bool,
925    },
926    /// A named argument.
927    Named(LinkedNode<'a>),
928}
929
930impl ArgClass<'_> {
931    /// Creates the class refer to the first positional argument.
932    pub fn first_positional() -> Self {
933        ArgClass::Positional {
934            spreads: EcoVec::new(),
935            positional: 0,
936            is_spread: false,
937        }
938    }
939}
940
941// todo: check if we can merge `SurroundingSyntax` and `SyntaxContext`?
942/// Classes of syntax context (outer syntax) that can be operated on by IDE
943#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, strum::EnumIter)]
944pub enum SurroundingSyntax {
945    /// Regular syntax.
946    Regular,
947    /// Content in a string.
948    StringContent,
949    /// The cursor is directly on the selector of a show rule.
950    Selector,
951    /// The cursor is directly on the transformation of a show rule.
952    ShowTransform,
953    /// The cursor is directly on the import list.
954    ImportList,
955    /// The cursor is directly on the set rule.
956    SetRule,
957    /// The cursor is directly on the parameter list.
958    ParamList,
959}
960
961/// Determines the surrounding syntax of the node at the given position.
962pub 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                    // incomplete show rule
1046                    return Some(Selector);
1047                };
1048
1049                if leaf.offset() >= colon.offset() {
1050                    return Some(ShowTransform);
1051                } else {
1052                    return Some(Selector); // query's first argument
1053                }
1054            }
1055            _ => {}
1056        }
1057
1058        leaf = parent;
1059    }
1060
1061    None
1062}
1063
1064/// Checks the previous syntax of the node.
1065fn 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
1090/// Checks if the node is enclosed by the given span.
1091fn 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/// Classes of syntax context (outer syntax) that can be operated on by IDE
1096/// functionality.
1097///
1098/// A syntax context is either a [`SyntaxClass`] or other things.
1099/// One thing is not necessary to refer to some exact node. For example, a
1100/// cursor moving after some comma in a function call is identified as a
1101/// [`SyntaxContext::Arg`].
1102#[derive(Debug, Clone)]
1103pub enum SyntaxContext<'a> {
1104    /// A cursor on an argument.
1105    Arg {
1106        /// The callee node.
1107        callee: LinkedNode<'a>,
1108        /// The arguments node.
1109        args: LinkedNode<'a>,
1110        /// The argument target pointed by the cursor.
1111        target: ArgClass<'a>,
1112        /// Whether the callee is a set rule.
1113        is_set: bool,
1114    },
1115    /// A cursor on an element in an array or dictionary literal.
1116    Element {
1117        /// The container node.
1118        container: LinkedNode<'a>,
1119        /// The element target pointed by the cursor.
1120        target: ArgClass<'a>,
1121    },
1122    /// A cursor on a parenthesized expression.
1123    Paren {
1124        /// The parenthesized expression node.
1125        container: LinkedNode<'a>,
1126        /// Whether the cursor is on the left side of the parenthesized
1127        /// expression.
1128        is_before: bool,
1129    },
1130    /// A variable access expression.
1131    ///
1132    /// It can be either an identifier or a field access.
1133    VarAccess(VarClass<'a>),
1134    /// A cursor on an import path.
1135    ImportPath(LinkedNode<'a>),
1136    /// A cursor on an include path.
1137    IncludePath(LinkedNode<'a>),
1138    /// A cursor on a label.
1139    Label {
1140        /// The label node.
1141        node: LinkedNode<'a>,
1142        /// Whether the label is converted from an error node.
1143        is_error: bool,
1144    },
1145    /// A (content) reference expression.
1146    Ref {
1147        /// The node of the reference.
1148        node: LinkedNode<'a>,
1149        /// A colon after a reference expression, for example, `@a:|` or
1150        /// `@a:b:|`.
1151        suffix_colon: bool,
1152    },
1153    /// A cursor on a normal [`SyntaxClass`].
1154    Normal(LinkedNode<'a>),
1155}
1156
1157impl<'a> SyntaxContext<'a> {
1158    /// Gets the node of the cursor class.
1159    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    /// Gets the argument container node.
1178    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/// Kind of argument source.
1191#[derive(Debug)]
1192enum ArgSourceKind {
1193    /// An argument in a function call.
1194    Call,
1195    /// An argument (element) in an array literal.
1196    Array,
1197    /// An argument (element) in a dictionary literal.
1198    Dict,
1199}
1200
1201/// Classifies the context (outer syntax) of the node by the outer node that
1202/// can be operated on by IDE functionality.
1203pub 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
1237/// Classifies the context (outer syntax) of the node that can be operated on
1238/// by IDE functionality.
1239pub 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
1341/// Classifies the context of the callee node.
1342fn 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
1377/// Classifies the context of the argument node.
1378fn 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
1463/// The cursor is on an invalid position for completion.
1464pub enum BadCompletionCursor {
1465    /// The cursor is outside of the argument list.
1466    ArgListPos,
1467}
1468
1469/// Checks if the cursor is on an invalid position for completion.
1470pub fn bad_completion_cursor(
1471    syntax: Option<&SyntaxClass>,
1472    syntax_context: Option<&SyntaxContext>,
1473    leaf: &LinkedNode,
1474) -> Option<BadCompletionCursor> {
1475    // The cursor is on `f()|`
1476    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        // The cursor is on `f[]|`
1483    }) || (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}