tinymist-query 0.15.4-rc1

Language queries for tinymist.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Analysis of function signatures.

use std::cell::RefCell;

use itertools::Either;
use tinymist_analysis::{ArgInfo, ArgsInfo, PartialSignature, func_signature};
use tinymist_derive::BindTyCtx;
use tinymist_std::hash::FxHashSet;

use super::{Definition, SharedContext, prelude::*};
use crate::analysis::PostTypeChecker;
use crate::docs::{DocText, UntypedDefDocs, UntypedSignatureDocs, UntypedVarDocs};
use crate::syntax::{DeclExpr, classify_def_loosely};
use crate::ty::{
    BoundCheckContext, BoundChecker, DocSource, DynTypeBounds, ParamAttrs, ParamTy, SigTy,
    SigWithTy, TyCtx, TyCtxMut, TypeInfo, TypeVar,
};

pub use tinymist_analysis::{PrimarySignature, Signature};

/// The language object that the signature is being analyzed for.
#[derive(Debug, Clone)]
pub enum SignatureTarget {
    /// A static node without knowing the function at runtime.
    Def(Option<Source>, Definition),
    /// A static node without knowing the function at runtime.
    SyntaxFast(Source, Span),
    /// A static node without knowing the function at runtime.
    Syntax(Source, Span),
    /// A function that is known at runtime.
    Runtime(Func),
    /// A function that is known at runtime.
    Convert(Func),
}

impl SignatureTarget {
    /// Returns the span of the callee node.
    pub fn span(&self) -> Span {
        match self {
            SignatureTarget::Def(_, def) => def.decl.span(),
            SignatureTarget::SyntaxFast(_, span) | SignatureTarget::Syntax(_, span) => *span,
            SignatureTarget::Runtime(func) | SignatureTarget::Convert(func) => func.span(),
        }
    }
}

#[typst_macros::time(span = callee_node.span())]
pub(crate) fn analyze_signature(
    ctx: &Arc<SharedContext>,
    callee_node: SignatureTarget,
) -> Option<Signature> {
    ctx.compute_signature(callee_node.clone(), move |ctx| {
        crate::log_debug_ct!("analyzing signature for {callee_node:?}");
        analyze_type_signature(ctx, &callee_node)
            .or_else(|| analyze_dyn_signature(ctx, &callee_node))
    })
}

#[typst_macros::time(span = callee_node.span())]
fn analyze_type_signature(
    ctx: &Arc<SharedContext>,
    callee_node: &SignatureTarget,
) -> Option<Signature> {
    let (type_info, ty) = match callee_node {
        SignatureTarget::Convert(..) => return None,
        SignatureTarget::SyntaxFast(source, span) | SignatureTarget::Syntax(source, span) => {
            let type_info = ctx.type_check(source);
            let ty = type_info.type_of_span(*span)?;
            Some((type_info, ty))
        }
        SignatureTarget::Def(source, def) => {
            let span = def.decl.span();
            let type_info = ctx.type_check(source.as_ref()?);
            let ty = type_info.type_of_span(span)?;
            Some((type_info, ty))
        }
        SignatureTarget::Runtime(func) => {
            let source = ctx.source_by_id(func.span().id()?).ok()?;
            let node = source.find(func.span())?;
            let def = classify_def_loosely(node.parent()?.clone())?;
            let type_info = ctx.type_check(&source);
            let ty = type_info.type_of_span(def.name()?.span())?;
            Some((type_info, ty))
        }
    }?;

    sig_of_type(ctx, &type_info, ty)
}

pub(crate) fn sig_of_type(
    ctx: &Arc<SharedContext>,
    type_info: &TypeInfo,
    ty: Ty,
) -> Option<Signature> {
    // todo multiple sources
    let mut srcs = ty.sources();
    srcs.sort();
    crate::log_debug_ct!("check type signature of ty: {ty:?} => {srcs:?}");
    let type_var = srcs.into_iter().next()?;
    match type_var {
        DocSource::Var(v) => {
            let mut ty_ctx =
                SignatureTypeContext::new(PostTypeChecker::new(ctx.clone(), type_info));
            let sig_ty = Ty::Func(ty.sig_repr(true, &mut ty_ctx)?);
            let sig_ty = type_info.simplify(sig_ty, false);
            let Ty::Func(sig_ty) = sig_ty else {
                static WARN_ONCE: std::sync::Once = std::sync::Once::new();
                WARN_ONCE.call_once(|| {
                    // todo: seems like a bug
                    log::warn!("expected function type, got {sig_ty:?}");
                });
                return None;
            };

            // todo: this will affect inlay hint: _var_with
            ty_ctx.reset_cycle_guard();
            let (var_with, docstring) = match type_info.var_docs.get(&v.def).map(|x| x.as_ref()) {
                Some(UntypedDefDocs::Function(sig)) => (vec![], Either::Left(sig.as_ref())),
                Some(UntypedDefDocs::Variable(docs)) => find_alias_stack(&mut ty_ctx, &v, docs)?,
                _ => return None,
            };

            let docstring = match docstring {
                Either::Left(docstring) => docstring,
                Either::Right(func) => return Some(wind_stack(var_with, ctx.type_of_func(func))),
            };

            let mut param_specs = Vec::new();
            let mut has_fill_or_size_or_stroke = false;
            let mut _broken = false;

            if docstring.pos.len() != sig_ty.positional_params().len() {
                static WARN_ONCE: std::sync::Once = std::sync::Once::new();
                WARN_ONCE.call_once(|| {
                    // todo: seems like a bug
                    log::warn!("positional params mismatch: {docstring:#?} != {sig_ty:#?}");
                });
                return None;
            }

            for (doc, ty) in docstring.pos.iter().zip(sig_ty.positional_params()) {
                let default = doc.default.clone();
                let ty = ty.clone();

                let name = doc.name.clone();
                if matches!(name.as_ref(), "fill" | "stroke" | "size") {
                    has_fill_or_size_or_stroke = true;
                }

                param_specs.push(Interned::new(ParamTy {
                    name,
                    docs: Some(DocText::plain(doc.docs.clone())),
                    default,
                    ty,
                    attrs: ParamAttrs::positional(),
                }));
            }

            for (name, ty) in sig_ty.named_params() {
                let docstring = docstring.named.get(name);
                let default = Some(
                    docstring
                        .and_then(|doc| doc.default.clone())
                        .unwrap_or_else(|| "unknown".into()),
                );
                let ty = ty.clone();

                if matches!(name.as_ref(), "fill" | "stroke" | "size") {
                    has_fill_or_size_or_stroke = true;
                }

                param_specs.push(Interned::new(ParamTy {
                    name: name.clone(),
                    docs: docstring.map(|doc| DocText::plain(doc.docs.clone())),
                    default,
                    ty,
                    attrs: ParamAttrs::named(),
                }));
            }

            if let Some(doc) = docstring.rest.as_ref() {
                let default = doc.default.clone();

                param_specs.push(Interned::new(ParamTy {
                    name: doc.name.clone(),
                    docs: Some(DocText::plain(doc.docs.clone())),
                    default,
                    ty: sig_ty.rest_param().cloned().unwrap_or(Ty::Any),
                    attrs: ParamAttrs::variadic(),
                }));
            }

            let sig = Signature::Primary(Arc::new(PrimarySignature {
                docs: Some(DocText::plain(docstring.docs.clone())),
                param_specs,
                has_fill_or_size_or_stroke,
                sig_ty,
                _broken,
            }));
            Some(wind_stack(var_with, sig))
        }
        src @ (DocSource::Builtin(..) | DocSource::Ins(..)) => {
            Some(ctx.type_of_func(src.as_func()?))
        }
    }
}

/// A type context for signature rendering that memoizes `(TypeVar, polarity)`
/// visits within a single traversal so recursive bounds are only expanded once.
struct SignatureTypeContext<'a> {
    inner: PostTypeChecker<'a>,
    visited: RefCell<FxHashSet<(DeclExpr, bool)>>,
}

impl<'a> SignatureTypeContext<'a> {
    fn new(inner: PostTypeChecker<'a>) -> Self {
        Self {
            inner,
            visited: RefCell::new(FxHashSet::default()),
        }
    }

    fn reset_cycle_guard(&self) {
        self.visited.borrow_mut().clear();
    }
}

impl TyCtx for SignatureTypeContext<'_> {
    fn global_bounds(&self, var: &Interned<TypeVar>, pol: bool) -> Option<DynTypeBounds> {
        if !self.visited.borrow_mut().insert((var.def.clone(), pol)) {
            return None;
        }

        self.inner.global_bounds(var, pol)
    }

    fn local_bind_of(&self, var: &Interned<TypeVar>) -> Option<Ty> {
        self.inner.local_bind_of(var)
    }
}

impl TyCtxMut for SignatureTypeContext<'_> {
    type Snap = <TypeInfo as TyCtxMut>::Snap;

    fn start_scope(&mut self) -> Self::Snap {
        self.inner.start_scope()
    }

    fn end_scope(&mut self, snap: Self::Snap) {
        self.inner.end_scope(snap)
    }

    fn bind_local(&mut self, var: &Interned<TypeVar>, ty: Ty) {
        self.inner.bind_local(var, ty);
    }

    fn type_of_func(&mut self, func: &Func) -> Option<Interned<SigTy>> {
        self.inner.type_of_func(func)
    }

    fn type_of_value(&mut self, val: &Value) -> Ty {
        self.inner.type_of_value(val)
    }

    fn check_module_item(&mut self, module: TypstFileId, key: &StrRef) -> Option<Ty> {
        self.inner.check_module_item(module, key)
    }
}

fn wind_stack(var_with: Vec<WithElem>, sig: Signature) -> Signature {
    if var_with.is_empty() {
        return sig;
    }

    let (primary, mut base_args) = match sig {
        Signature::Primary(primary) => (primary, eco_vec![]),
        Signature::Partial(partial) => (partial.signature.clone(), partial.with_stack.clone()),
    };

    let mut accepting = primary.pos().iter().skip(base_args.len());

    // Ignoring docs at the moment
    for (_d, w) in var_with {
        if let Some(w) = w {
            let mut items = eco_vec![];
            for pos in w.with.positional_params() {
                let Some(arg) = accepting.next() else {
                    break;
                };
                items.push(ArgInfo {
                    name: Some(arg.name.clone()),
                    term: Some(pos.clone()),
                });
            }
            // todo: ignored spread arguments
            if !items.is_empty() {
                base_args.push(ArgsInfo { items });
            }
        }
    }

    Signature::Partial(Arc::new(PartialSignature {
        signature: primary,
        with_stack: base_args,
    }))
}

type WithElem<'a> = (&'a UntypedVarDocs, Option<Interned<SigWithTy>>);

fn find_alias_stack<'a>(
    ctx: &'a mut SignatureTypeContext,
    var: &Interned<TypeVar>,
    docs: &'a UntypedVarDocs,
) -> Option<(Vec<WithElem<'a>>, Either<&'a UntypedSignatureDocs, Func>)> {
    let mut checker = AliasStackChecker {
        ctx,
        stack: vec![(docs, None)],
        res: None,
        checking_with: true,
    };
    Ty::Var(var.clone()).bounds(true, &mut checker);

    checker.res.map(|res| (checker.stack, res))
}

#[derive(BindTyCtx)]
#[bind(ctx)]
struct AliasStackChecker<'a, 'b> {
    ctx: &'a mut SignatureTypeContext<'b>,
    stack: Vec<WithElem<'a>>,
    res: Option<Either<&'a UntypedSignatureDocs, Func>>,
    checking_with: bool,
}

impl BoundChecker for AliasStackChecker<'_, '_> {
    fn check_var(&mut self, u: &Interned<TypeVar>, pol: bool, ctx: &mut BoundCheckContext) {
        crate::log_debug_ct!("collecting var {u:?} {pol:?}");
        if self.res.is_some() {
            return;
        }

        if self.checking_with {
            ctx.check_var_rec(u, pol, self);
            return;
        }

        let docs = self.ctx.inner.info.var_docs.get(&u.def).map(|x| x.as_ref());

        crate::log_debug_ct!("collecting var {u:?} {pol:?} => {docs:?}");
        // todo: bind builtin functions
        match docs {
            Some(UntypedDefDocs::Function(sig)) => {
                self.res = Some(Either::Left(sig));
            }
            Some(UntypedDefDocs::Variable(docs)) => {
                self.checking_with = true;
                self.stack.push((docs, None));
                ctx.check_var_rec(u, pol, self);
                self.stack.pop();
                self.checking_with = false;
            }
            _ => {}
        }
    }

    fn collect(&mut self, ty: &Ty, pol: bool) {
        if self.res.is_some() {
            return;
        }

        match (self.checking_with, ty) {
            (true, Ty::With(w)) => {
                crate::log_debug_ct!("collecting with {ty:?} {pol:?}");
                self.stack.last_mut().unwrap().1 = Some(w.clone());
                self.checking_with = false;
                w.sig.bounds(pol, self);
                self.checking_with = true;
            }
            (false, ty) => {
                if let Some(src) = ty.as_source() {
                    match src {
                        DocSource::Var(u) => {
                            let mut ctx = BoundCheckContext::default();
                            self.check_var(&u, pol, &mut ctx);
                        }
                        src @ (DocSource::Builtin(..) | DocSource::Ins(..)) => {
                            if let Some(func) = src.as_func() {
                                self.res = Some(Either::Right(func));
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

#[typst_macros::time(span = callee_node.span())]
fn analyze_dyn_signature(
    ctx: &Arc<SharedContext>,
    callee_node: &SignatureTarget,
) -> Option<Signature> {
    let func = match callee_node {
        SignatureTarget::Def(_source, def) => def.value()?.to_func()?,
        SignatureTarget::SyntaxFast(..) => return None,
        SignatureTarget::Syntax(source, span) => {
            let def = ctx.def_of_span(source, *span)?;
            def.value()?.to_func()?
        }
        SignatureTarget::Convert(func) | SignatureTarget::Runtime(func) => func.clone(),
    };

    Some(func_signature(func))
}