tinymist_query/analysis/completion/
field_access.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//! Completion for field access on nodes.

use typst::syntax::ast::MathTextKind;

use crate::analysis::completion::typst_specific::ValueCompletionInfo;

use super::*;
impl CompletionPair<'_, '_, '_> {
    /// Add completions for all dot targets on a node.
    pub fn doc_access_completions(&mut self, target: &LinkedNode) -> Option<()> {
        self.value_dot_access_completions(target)
            .or_else(|| self.type_dot_access_completions(target))
    }

    /// Add completions for all fields on a type.
    fn type_dot_access_completions(&mut self, target: &LinkedNode) -> Option<()> {
        let mode = self.cursor.leaf_mode();

        if matches!(mode, InterpretMode::Math) {
            return None;
        }

        self.type_field_access_completions(target);
        Some(())
    }

    /// Add completions for all fields on a type.
    fn type_field_access_completions(&mut self, target: &LinkedNode) -> Option<()> {
        let ty = self
            .worker
            .ctx
            .post_type_of_node(target.clone())
            .filter(|ty| !matches!(ty, Ty::Any));
        crate::log_debug_ct!("type_field_access_completions_on: {target:?} -> {ty:?}");
        let mut defines = Defines {
            types: self.worker.ctx.type_check(&self.cursor.source),
            defines: Default::default(),
            docs: Default::default(),
        };
        ty?.iface_surface(
            true,
            &mut CompletionScopeChecker {
                check_kind: ScopeCheckKind::FieldAccess,
                defines: &mut defines,
                ctx: self.worker.ctx,
            },
        );

        self.def_completions(defines, true);
        Some(())
    }

    /// Add completions for all fields on a value.
    fn value_dot_access_completions(&mut self, target: &LinkedNode) -> Option<()> {
        let (value, styles) = self.worker.ctx.analyze_expr(target).into_iter().next()?;

        let mode = self.cursor.leaf_mode();
        let valid_field_access_syntax =
            !matches!(mode, InterpretMode::Math) || is_valid_math_field_access(target);
        let valid_postfix_target =
            !matches!(mode, InterpretMode::Math) || is_valid_math_postfix(target);

        if !valid_field_access_syntax && !valid_postfix_target {
            return None;
        }

        if valid_field_access_syntax {
            self.value_field_access_completions(&value, mode);
        }
        if valid_postfix_target {
            self.postfix_completions(target, Ty::Value(InsTy::new(value.clone())));
        }

        match value {
            Value::Symbol(symbol) => {
                self.symbol_var_completions(&symbol, None);

                if valid_postfix_target {
                    self.ufcs_completions(target);
                }
            }
            Value::Content(content) => {
                if valid_field_access_syntax {
                    for (name, value) in content.fields() {
                        self.value_completion(Some(name.into()), &value, false, None);
                    }
                }
                if valid_postfix_target {
                    self.ufcs_completions(target);
                }
            }
            Value::Dict(dict) if valid_field_access_syntax => {
                for (name, value) in dict.iter() {
                    self.value_completion(Some(name.clone().into()), value, false, None);
                }
            }
            Value::Func(func) if valid_field_access_syntax => {
                // Autocomplete get rules.
                if let Some((elem, styles)) = func.element().zip(styles.as_ref()) {
                    for param in elem.params().iter().filter(|param| !param.required) {
                        if let Some(value) = elem
                            .field_id(param.name)
                            .map(|id| elem.field_from_styles(id, StyleChain::new(styles)))
                        {
                            self.value_completion(
                                Some(param.name.into()),
                                &value.unwrap(),
                                false,
                                None,
                            );
                        }
                    }
                }
            }
            _ => {}
        }

        Some(())
    }

    fn value_field_access_completions(&mut self, value: &Value, mode: InterpretMode) {
        let elem_parens = !matches!(mode, InterpretMode::Math);
        for (name, bind) in value.ty().scope().iter() {
            if matches!(mode, InterpretMode::Math) && is_func(bind.read()) {
                continue;
            }

            self.value_completion_(
                bind.read(),
                ValueCompletionInfo {
                    label: Some(name.clone()),
                    parens: elem_parens,
                    docs: None,
                    label_details: None,
                    bound_self: true,
                },
            );
        }

        if let Some(scope) = value.scope() {
            for (name, bind) in scope.iter() {
                if matches!(mode, InterpretMode::Math) && is_func(bind.read()) {
                    continue;
                }

                self.value_completion_(
                    bind.read(),
                    ValueCompletionInfo {
                        label: Some(name.clone()),
                        parens: elem_parens,
                        docs: None,
                        label_details: None,
                        bound_self: false,
                    },
                );
            }
        }

        for &field in fields_on(value.ty()) {
            // Complete the field name along with its value. Notes:
            // 1. No parentheses since function fields cannot currently be called
            // with method syntax;
            // 2. We can unwrap the field's value since it's a field belonging to
            // this value's type, so accessing it should not fail.
            self.value_completion_(
                &value.field(field, ()).unwrap(),
                ValueCompletionInfo {
                    label: Some(field.into()),
                    parens: false,
                    docs: None,
                    label_details: None,
                    bound_self: true,
                },
            );
        }
    }
}

fn is_func(read: &Value) -> bool {
    matches!(read, Value::Func(func) if func.element().is_none())
}

fn is_valid_math_field_access(target: &SyntaxNode) -> bool {
    if let Some(field_access) = target.cast::<ast::FieldAccess>() {
        return is_valid_math_field_access(field_access.target().to_untyped());
    }
    if matches!(target.kind(), SyntaxKind::Ident | SyntaxKind::MathIdent) {
        return true;
    }

    false
}

fn is_valid_math_postfix(target: &SyntaxNode) -> bool {
    fn bad_punc_text(punc: char) -> bool {
        punc.is_ascii_punctuation() || punc.is_ascii_whitespace()
    }

    if let Some(target) = target.cast::<ast::MathText>() {
        return match target.get() {
            MathTextKind::Character(ch) => !bad_punc_text(ch),
            MathTextKind::Number(..) => true,
        };
    }

    if let Some(target) = target.cast::<ast::Text>() {
        let target = target.get();
        return !target.is_empty() && target.chars().all(|ch| !bad_punc_text(ch));
    }

    true
}