summaryrefslogtreecommitdiff
path: root/crates/typst-ide/src/definition.rs
blob: 4c2b80cd4ad09d984a786b18457cf687599cfcbb (plain) (blame)
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
use typst::foundations::{Label, Selector, Value};
use typst::layout::PagedDocument;
use typst::syntax::{ast, LinkedNode, Side, Source, Span};
use typst::utils::PicoStr;

use crate::utils::globals;
use crate::{
    analyze_expr, analyze_import, deref_target, named_items, DerefTarget, IdeWorld,
    NamedItem,
};

/// A definition of some item.
#[derive(Debug, Clone)]
pub enum Definition {
    /// The item is defined at the given span.
    Span(Span),
    /// The item is defined in the standard library.
    Std(Value),
}

/// Find the definition of the item under the cursor.
///
/// Passing a `document` (from a previous compilation) is optional, but enhances
/// the definition search. Label definitions, for instance, are only generated
/// when the document is available.
pub fn definition(
    world: &dyn IdeWorld,
    document: Option<&PagedDocument>,
    source: &Source,
    cursor: usize,
    side: Side,
) -> Option<Definition> {
    let root = LinkedNode::new(source.root());
    let leaf = root.leaf_at(cursor, side)?;

    match deref_target(leaf.clone())? {
        // Try to find a named item (defined in this file or an imported file)
        // or fall back to a standard library item.
        DerefTarget::VarAccess(node) | DerefTarget::Callee(node) => {
            let name = node.cast::<ast::Ident>()?.get().clone();
            if let Some(src) = named_items(world, node.clone(), |item: NamedItem| {
                (*item.name() == name).then(|| Definition::Span(item.span()))
            }) {
                return Some(src);
            };

            if let Some((value, _)) = analyze_expr(world, &node).first() {
                let span = match value {
                    Value::Content(content) => content.span(),
                    Value::Func(func) => func.span(),
                    _ => Span::detached(),
                };
                if !span.is_detached() && span != node.span() {
                    return Some(Definition::Span(span));
                }
            }

            if let Some(binding) = globals(world, &leaf).get(&name) {
                return Some(Definition::Std(binding.read().clone()));
            }
        }

        // Try to jump to the an imported file or package.
        DerefTarget::ImportPath(node) | DerefTarget::IncludePath(node) => {
            let Some(Value::Module(module)) = analyze_import(world, &node) else {
                return None;
            };
            let id = module.file_id()?;
            let span = Span::from_range(id, 0..0);
            return Some(Definition::Span(span));
        }

        // Try to jump to the referenced content.
        DerefTarget::Ref(node) => {
            let label = Label::new(PicoStr::intern(node.cast::<ast::Ref>()?.target()))
                .expect("unexpected empty reference");
            let selector = Selector::Label(label);
            let elem = document?.introspector.query_first(&selector)?;
            return Some(Definition::Span(elem.span()));
        }

        _ => {}
    }

    None
}

#[cfg(test)]
mod tests {
    use std::borrow::Borrow;
    use std::ops::Range;

    use typst::foundations::{IntoValue, NativeElement};
    use typst::syntax::Side;
    use typst::WorldExt;

    use super::{definition, Definition};
    use crate::tests::{FilePos, TestWorld, WorldLike};

    type Response = (TestWorld, Option<Definition>);

    trait ResponseExt {
        fn must_be_at(&self, path: &str, range: Range<usize>) -> &Self;
        fn must_be_value(&self, value: impl IntoValue) -> &Self;
    }

    impl ResponseExt for Response {
        #[track_caller]
        fn must_be_at(&self, path: &str, expected: Range<usize>) -> &Self {
            match self.1 {
                Some(Definition::Span(span)) => {
                    let range = self.0.range(span);
                    assert_eq!(
                        span.id().unwrap().vpath().as_rootless_path().to_string_lossy(),
                        path
                    );
                    assert_eq!(range, Some(expected));
                }
                _ => panic!("expected span definition"),
            }
            self
        }

        #[track_caller]
        fn must_be_value(&self, expected: impl IntoValue) -> &Self {
            match &self.1 {
                Some(Definition::Std(value)) => {
                    assert_eq!(*value, expected.into_value())
                }
                _ => panic!("expected std definition"),
            }
            self
        }
    }

    #[track_caller]
    fn test(world: impl WorldLike, pos: impl FilePos, side: Side) -> Response {
        let world = world.acquire();
        let world = world.borrow();
        let doc = typst::compile(world).output.ok();
        let (source, cursor) = pos.resolve(world);
        let def = definition(world, doc.as_ref(), &source, cursor, side);
        (world.clone(), def)
    }

    #[test]
    fn test_definition_let() {
        test("#let x; #x", -2, Side::After).must_be_at("main.typ", 5..6);
        test("#let x() = {}; #x", -2, Side::After).must_be_at("main.typ", 5..6);
    }

    #[test]
    fn test_definition_field_access_function() {
        let world = TestWorld::new("#import \"other.typ\"; #other.foo")
            .with_source("other.typ", "#let foo(x) = x + 1");

        // The span is at the args here because that's what the function value's
        // span is. Not ideal, but also not too big of a big deal.
        test(&world, -2, Side::Before).must_be_at("other.typ", 8..11);
    }

    #[test]
    fn test_definition_cross_file() {
        let world = TestWorld::new("#import \"other.typ\": x; #x")
            .with_source("other.typ", "#let x = 1");
        test(&world, -2, Side::After).must_be_at("other.typ", 5..6);
    }

    #[test]
    fn test_definition_import() {
        let world = TestWorld::new("#import \"other.typ\" as o: x")
            .with_source("other.typ", "#let x = 1");
        test(&world, 14, Side::Before).must_be_at("other.typ", 0..0);
    }

    #[test]
    fn test_definition_include() {
        let world = TestWorld::new("#include \"other.typ\"")
            .with_source("other.typ", "Hello there");
        test(&world, 14, Side::Before).must_be_at("other.typ", 0..0);
    }

    #[test]
    fn test_definition_ref() {
        test("#figure[] <hi> See @hi", -2, Side::After).must_be_at("main.typ", 1..9);
    }

    #[test]
    fn test_definition_std() {
        test("#table", 1, Side::After).must_be_value(typst::model::TableElem::ELEM);
    }
}