1use typst::foundations::{Label, Selector, Type};
4use typst::introspection::Introspector;
5use typst_shim::syntax::source_range;
6
7use super::{InsTy, SharedContext, prelude::*};
8use crate::syntax::{Decl, DeclExpr, Expr, ExprInfo, SyntaxClass, VarClass};
9use crate::ty::DocSource;
10
11#[derive(Debug, Clone, Hash, PartialEq, Eq)]
13pub struct Definition {
14 pub decl: DeclExpr,
16 pub term: Option<Ty>,
18}
19
20impl Definition {
21 pub fn new(decl: DeclExpr, term: Option<Ty>) -> Self {
23 Self { decl, term }
24 }
25
26 pub fn new_var(name: Interned<str>, term: Ty) -> Self {
28 let decl = Decl::lit_(name);
29 Self::new(decl.into(), Some(term))
30 }
31
32 pub fn name(&self) -> &Interned<str> {
34 self.decl.name()
35 }
36
37 pub fn file_id(&self) -> Option<TypstFileId> {
39 self.decl.file_id()
40 }
41
42 pub fn name_range(&self, ctx: &SharedContext) -> Option<Range<usize>> {
44 self.decl.name_range(ctx)
45 }
46
47 pub fn full_range(&self) -> Option<Range<usize>> {
49 self.decl.full_range()
50 }
51
52 pub(crate) fn value(&self) -> Option<Value> {
53 self.term.as_ref()?.value()
54 }
55
56 pub(crate) fn from_value(value: Value, name: impl FnOnce() -> Option<StrRef>) -> Option<Self> {
57 value_to_def(value, name)
58 }
59}
60
61trait HasNameRange {
62 fn name_range(&self, ctx: &SharedContext) -> Option<Range<usize>>;
64}
65
66impl HasNameRange for Decl {
67 fn name_range(&self, ctx: &SharedContext) -> Option<Range<usize>> {
68 if let Decl::BibEntry(decl) = self {
69 return Some(decl.at.1.clone());
70 }
71
72 if !self.is_def() {
73 return None;
74 }
75
76 let src = ctx.source_by_id(self.file_id()?).ok()?;
77 source_range(&src, self.span())
78 }
79}
80
81#[typst_macros::time(span = syntax.node().span())]
84pub fn definition(
85 ctx: &Arc<SharedContext>,
86 source: &Source,
87 syntax: SyntaxClass,
88) -> Option<Definition> {
89 match syntax {
90 SyntaxClass::VarAccess(node) => find_ident_definition(ctx, source, node),
92 SyntaxClass::Callee(node) => find_ident_definition(ctx, source, VarClass::Ident(node)),
93 SyntaxClass::ImportPath(path) | SyntaxClass::IncludePath(path) => {
94 DefResolver::new(ctx, source)?.of_span(path.span())
95 }
96 SyntaxClass::Label {
97 node,
98 is_error: false,
99 }
100 | SyntaxClass::Ref {
101 node,
102 suffix_colon: false,
103 } => {
104 let ref_expr: ast::Expr = node.cast()?;
105 let name = match ref_expr {
106 ast::Expr::Ref(r) => r.target(),
107 ast::Expr::Label(r) => r.get(),
108 _ => return None,
109 };
110
111 let introspector = ctx.success_doc()?.introspector();
112 bib_definition(ctx, introspector, name)
113 .or_else(|| ref_definition(introspector, name, ref_expr))
114 }
115 SyntaxClass::Label {
116 node: _,
117 is_error: true,
118 }
119 | SyntaxClass::Ref {
120 node: _,
121 suffix_colon: true,
122 }
123 | SyntaxClass::At { node: _ }
124 | SyntaxClass::Normal(..) => None,
125 }
126}
127
128fn find_ident_definition(
129 ctx: &Arc<SharedContext>,
130 source: &Source,
131 use_site: VarClass,
132) -> Option<Definition> {
133 let ident_store = use_site.clone();
135 let ident_ref = match ident_store.node().cast::<ast::Expr>()? {
136 ast::Expr::Ident(ident) => ident.span(),
137 ast::Expr::MathIdent(ident) => ident.span(),
138 ast::Expr::FieldAccess(field_access) => return field_definition(ctx, field_access),
139 _ => {
140 crate::log_debug_ct!("unsupported kind {kind:?}", kind = use_site.node().kind());
141 Span::detached()
142 }
143 };
144
145 DefResolver::new(ctx, source)?.of_span(ident_ref)
146}
147
148fn field_definition(ctx: &Arc<SharedContext>, node: ast::FieldAccess) -> Option<Definition> {
149 let span = node.span();
150 let ty = ctx.type_of_span(span)?;
151 crate::log_debug_ct!("find_field_definition[{span:?}]: {ty:?}");
152
153 let mut srcs = ty.sources();
155 srcs.sort();
156 crate::log_debug_ct!("check type signature of ty: {ty:?} => {srcs:?}");
157 let type_var = srcs.into_iter().next()?;
158 match type_var {
159 DocSource::Var(v) => {
160 crate::log_debug_ct!("field var: {:?} {:?}", v.def, v.def.span());
161 Some(Definition::new(v.def.clone(), None))
162 }
163 DocSource::Ins(v) if !v.span().is_detached() => {
164 let s = v.span();
165 let source = ctx.source_by_id(s.id()?).ok()?;
166 DefResolver::new(ctx, &source)?.of_span(s)
167 }
168 DocSource::Ins(ins) => value_to_def(ins.val.clone(), || Some(node.field().get().into())),
169 DocSource::Builtin(..) => None,
170 }
171}
172
173fn bib_definition(
174 ctx: &Arc<SharedContext>,
175 introspector: &dyn Introspector,
176 key: &str,
177) -> Option<Definition> {
178 let bib_info = ctx.analyze_bib(introspector)?;
179
180 let entry = bib_info.entries.get(key)?;
181 crate::log_debug_ct!("find_bib_definition: {key} => {entry:?}");
182
183 let decl = Decl::bib_entry(
185 key.into(),
186 entry.file_id,
187 entry.name_range.clone(),
188 Some(entry.range.clone()),
189 );
190 Some(Definition::new(decl.into(), None))
191}
192
193fn ref_definition(
194 introspector: &dyn Introspector,
195 name: &str,
196 ref_expr: ast::Expr,
197) -> Option<Definition> {
198 let (decl, ty) = match ref_expr {
200 ast::Expr::Label(label) => (Decl::label(name, label.span()), None),
201 ast::Expr::Ref(..) => {
202 let sel = Selector::Label(Label::construct(name.into()).ok()?);
203 let elem = introspector.query_first(&sel)?;
204 let span = elem.labelled_at();
205 let decl = if !span.is_detached() {
206 Decl::label(name, span)
207 } else {
208 Decl::content(elem.span())
210 };
211 (decl, Some(Ty::Value(InsTy::new(Value::Content(elem)))))
212 }
213 _ => return None,
214 };
215
216 Some(Definition::new(decl.into(), ty))
217}
218
219#[derive(Debug, Clone)]
221pub enum CallConvention {
222 Static(Func),
224 Method(Value, Func),
226 With(Func),
228 Where(Func),
230}
231
232impl CallConvention {
233 pub fn method_this(&self) -> Option<&Value> {
235 match self {
236 CallConvention::Static(_) => None,
237 CallConvention::Method(this, _) => Some(this),
238 CallConvention::With(_) => None,
239 CallConvention::Where(_) => None,
240 }
241 }
242
243 pub fn callee(self) -> Func {
245 match self {
246 CallConvention::Static(func) => func,
247 CallConvention::Method(_, func) => func,
248 CallConvention::With(func) => func,
249 CallConvention::Where(func) => func,
250 }
251 }
252}
253
254pub fn resolve_call_target(ctx: &Arc<SharedContext>, node: &SyntaxNode) -> Option<CallConvention> {
256 let callee = (|| {
257 let source = ctx.source_by_id(node.span().id()?).ok()?;
258 let def = ctx.def_of_span(&source, node.span())?;
259 let func_ptr = match def.term.and_then(|val| val.value()) {
260 Some(Value::Func(func)) => Some(func),
261 Some(Value::Type(ty)) => ty.constructor().ok(),
262 _ => None,
263 }?;
264
265 Some((None, func_ptr))
266 })();
267 let callee = callee.or_else(|| {
268 let values = ctx.analyze_expr(node);
269
270 if let Some(access) = node.cast::<ast::FieldAccess>() {
271 let target = access.target();
272 let field = access.field().get();
273 let values = ctx.analyze_expr(target.to_untyped());
274 if let Some((this, func_ptr)) = values.into_iter().find_map(|(this, _styles)| {
275 if let Some(Value::Func(func)) = this.ty().scope().get(field).map(|b| b.read()) {
276 return Some((this, func.clone()));
277 }
278
279 None
280 }) {
281 return Some((Some(this), func_ptr));
282 }
283 }
284
285 if let Some(func) = values.into_iter().find_map(|v| v.0.to_func()) {
286 return Some((None, func));
287 };
288
289 None
290 })?;
291
292 let (this, func_ptr) = callee;
293 Some(match this {
294 Some(Value::Func(func)) if is_same_native_func(*WITH_FUNC, &func_ptr) => {
295 CallConvention::With(func)
296 }
297 Some(Value::Func(func)) if is_same_native_func(*WHERE_FUNC, &func_ptr) => {
298 CallConvention::Where(func)
299 }
300 Some(this) => CallConvention::Method(this, func_ptr),
301 None => CallConvention::Static(func_ptr),
302 })
303}
304
305fn is_same_native_func(x: Option<&Func>, y: &Func) -> bool {
306 let Some(x) = x else {
307 return false;
308 };
309
310 use typst::foundations::FuncInner;
311 match (x.inner(), y.inner()) {
312 (FuncInner::Native(x), FuncInner::Native(y)) => x == y,
313 (FuncInner::Element(x), FuncInner::Element(y)) => x == y,
314 _ => false,
315 }
316}
317
318static WITH_FUNC: LazyLock<Option<&'static Func>> = LazyLock::new(|| {
319 let fn_ty = Type::of::<Func>();
320 let bind = fn_ty.scope().get("with")?;
321 let Value::Func(func) = bind.read() else {
322 return None;
323 };
324 Some(func)
325});
326
327static WHERE_FUNC: LazyLock<Option<&'static Func>> = LazyLock::new(|| {
328 let fn_ty = Type::of::<Func>();
329 let bind = fn_ty.scope().get("where")?;
330 let Value::Func(func) = bind.read() else {
331 return None;
332 };
333 Some(func)
334});
335
336fn value_to_def(value: Value, name: impl FnOnce() -> Option<StrRef>) -> Option<Definition> {
337 let val = Ty::Value(InsTy::new(value.clone()));
338 Some(match value {
339 Value::Func(func) => {
340 let name = func.name().map(|name| name.into()).or_else(name)?;
341 let mut s = SyntaxNode::leaf(SyntaxKind::Ident, &name);
342 s.synthesize(func.span());
343
344 let decl = Decl::func(s.cast().unwrap());
345 Definition::new(decl.into(), Some(val))
346 }
347 Value::Module(module) => {
348 Definition::new_var(Interned::new_str(module.name().unwrap()), val)
349 }
350 _v => Definition::new_var(name()?, val),
351 })
352}
353
354struct DefResolver {
355 ei: ExprInfo,
356}
357
358impl DefResolver {
359 fn new(ctx: &Arc<SharedContext>, source: &Source) -> Option<Self> {
360 let ei = ctx.expr_stage(source);
361 Some(Self { ei })
362 }
363
364 fn of_span(&mut self, span: Span) -> Option<Definition> {
365 if span.is_detached() {
366 return None;
367 }
368
369 let resolved = self.ei.resolves.get(&span).cloned()?;
370 match (&resolved.root, &resolved.term) {
371 (Some(expr), term) => self.of_expr(expr, term.as_ref()),
372 (None, Some(term)) => self.of_term(term),
373 (None, None) => None,
374 }
375 }
376
377 fn of_expr(&mut self, expr: &Expr, term: Option<&Ty>) -> Option<Definition> {
378 crate::log_debug_ct!("of_expr: {expr:?}");
379
380 match expr {
381 Expr::Decl(decl) => self.of_decl(decl, term),
382 Expr::Ref(resolved) => {
383 self.of_expr(resolved.root.as_ref()?, resolved.term.as_ref().or(term))
384 }
385 _ => None,
386 }
387 }
388
389 fn of_term(&mut self, term: &Ty) -> Option<Definition> {
390 crate::log_debug_ct!("of_term: {term:?}");
391
392 let better_def = match term {
394 Ty::Value(v) => value_to_def(v.val.clone(), || None),
395 _ => None,
399 };
400
401 better_def.or_else(|| {
402 let constant = Decl::constant(Span::detached());
403 Some(Definition::new(constant.into(), Some(term.clone())))
404 })
405 }
406
407 fn of_decl(&mut self, decl: &Interned<Decl>, term: Option<&Ty>) -> Option<Definition> {
408 crate::log_debug_ct!("of_decl: {decl:?}");
409
410 match decl.as_ref() {
412 Decl::Import(..) | Decl::ImportAlias(..) => {
413 let next = self.of_span(decl.span());
414 Some(next.unwrap_or_else(|| Definition::new(decl.clone(), term.cloned())))
415 }
416 _ => Some(Definition::new(decl.clone(), term.cloned())),
417 }
418 }
419}