summaryrefslogtreecommitdiff
path: root/support/texlab/crates/base-db/src/semantics/tex.rs
blob: 1445ae12e7d7f25e587ff2939450db361de43776 (plain)
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
use rowan::{ast::AstNode, TextLen};
use rustc_hash::FxHashSet;
use syntax::latex::{self, HasBrack, HasCurly};
use text_size::TextRange;

use super::Span;

#[derive(Debug, Clone, Default)]
pub struct Semantics {
    pub links: Vec<Link>,
    pub labels: Vec<Label>,
    pub commands: Vec<Span>,
    pub environments: Vec<Span>,
    pub theorem_definitions: Vec<TheoremDefinition>,
    pub graphics_paths: FxHashSet<String>,
    pub can_be_root: bool,
    pub can_be_compiled: bool,
}

impl Semantics {
    pub fn process_root(&mut self, root: &latex::SyntaxNode) {
        for node in root.descendants_with_tokens() {
            match node {
                latex::SyntaxElement::Node(node) => {
                    self.process_node(&node);
                }
                latex::SyntaxElement::Token(token) => {
                    if token.kind() == latex::COMMAND_NAME {
                        let range = token.text_range();
                        let range = TextRange::new(range.start() + "\\".text_len(), range.end());
                        let text = String::from(&token.text()[1..]);
                        self.commands.push(Span { range, text });
                    }
                }
            };
        }

        self.can_be_root = self.can_be_compiled
            && !self
                .links
                .iter()
                .any(|link| link.kind == LinkKind::Cls && link.path.text == "subfiles");
    }

    fn process_node(&mut self, node: &latex::SyntaxNode) {
        if let Some(include) = latex::Include::cast(node.clone()) {
            self.process_include(include);
        } else if let Some(import) = latex::Import::cast(node.clone()) {
            self.process_import(import);
        } else if let Some(label) = latex::LabelDefinition::cast(node.clone()) {
            self.process_label_definition(label);
        } else if let Some(label) = latex::LabelReference::cast(node.clone()) {
            self.process_label_reference(label);
        } else if let Some(label) = latex::LabelReferenceRange::cast(node.clone()) {
            self.process_label_reference_range(label);
        } else if let Some(environment) = latex::Environment::cast(node.clone()) {
            self.process_environment(environment);
        } else if let Some(theorem_def) = latex::TheoremDefinition::cast(node.clone()) {
            self.process_theorem_definition(theorem_def);
        }
    }

    fn process_include(&mut self, include: latex::Include) {
        let Some(list) = include.path_list() else { return };

        for path in list.keys() {
            let kind = match include.syntax().kind() {
                latex::PACKAGE_INCLUDE => LinkKind::Sty,
                latex::CLASS_INCLUDE => LinkKind::Cls,
                latex::LATEX_INCLUDE => LinkKind::Tex,
                latex::BIBLATEX_INCLUDE => LinkKind::Bib,
                latex::BIBTEX_INCLUDE => LinkKind::Bib,
                _ => continue,
            };

            self.links.push(Link {
                kind,
                path: Span::from(&path),
                base_dir: None,
            });
        }
    }

    fn process_import(&mut self, import: latex::Import) {
        let Some(mut base_dir) = import
            .directory()
            .and_then(|dir| dir.key())
            .map(|key| key.to_string()) else { return };

        if !base_dir.ends_with('/') {
            base_dir.push('/');
        }

        let Some(path) = import.file().and_then(|path| path.key()) else { return };
        let text = format!("{base_dir}{}", path.to_string());
        let range = latex::small_range(&path);

        self.links.push(Link {
            kind: LinkKind::Tex,
            path: Span { text, range },
            base_dir: Some(base_dir),
        });
    }

    fn process_label_definition(&mut self, label: latex::LabelDefinition) {
        let Some(name) = label.name().and_then(|group| group.key()) else { return };

        let full_range = latex::small_range(&label);
        let mut objects = Vec::new();
        for node in label.syntax().ancestors() {
            if let Some(section) = latex::Section::cast(node.clone()) {
                let Some(text) = section.name().and_then(|group| group.content_text()) else { continue };
                let range = latex::small_range(&section);
                let prefix = String::from(match section.syntax().kind() {
                    latex::PART => "Part",
                    latex::CHAPTER => "Chapter",
                    latex::SECTION => "Section",
                    latex::SUBSECTION => "Subsection",
                    latex::SUBSUBSECTION => "Subsubsection",
                    latex::PARAGRAPH => "Paragraph",
                    latex::SUBPARAGRAPH => "Subparagraph",
                    _ => unreachable!(),
                });

                let kind = LabelObject::Section { prefix, text };
                objects.push(LabelTarget {
                    object: kind,
                    range,
                });
            } else if let Some(environment) = latex::Environment::cast(node.clone()) {
                let Some(name) = environment.begin()
                    .and_then(|begin| begin.name())
                    .and_then(|group| group.key())
                    .map(|key| key.to_string()) else { continue };

                let caption = environment
                    .syntax()
                    .children()
                    .filter_map(latex::Caption::cast)
                    .find_map(|node| node.long())
                    .and_then(|node| node.content_text());

                let options = environment
                    .begin()
                    .and_then(|begin| begin.options())
                    .and_then(|options| options.content_text());

                let range = latex::small_range(&environment);
                let kind = LabelObject::Environment {
                    name,
                    options,
                    caption,
                };

                objects.push(LabelTarget {
                    object: kind,
                    range,
                });
            } else if let Some(enum_item) = latex::EnumItem::cast(node.clone()) {
                let range = latex::small_range(&enum_item);
                let kind = LabelObject::EnumItem;
                objects.push(LabelTarget {
                    object: kind,
                    range,
                });
            }
        }

        self.labels.push(Label {
            kind: LabelKind::Definition,
            name: Span::from(&name),
            targets: objects,
            full_range,
        });
    }

    fn process_label_reference(&mut self, label: latex::LabelReference) {
        let Some(name_list) = label.name_list() else { return };

        let full_range = latex::small_range(&label);
        for name in name_list.keys() {
            self.labels.push(Label {
                kind: LabelKind::Reference,
                name: Span::from(&name),
                targets: Vec::new(),
                full_range,
            });
        }
    }

    fn process_label_reference_range(&mut self, label: latex::LabelReferenceRange) {
        let full_range = latex::small_range(&label);
        if let Some(from) = label.from().and_then(|group| group.key()) {
            self.labels.push(Label {
                kind: LabelKind::ReferenceRange,
                name: Span::from(&from),
                targets: Vec::new(),
                full_range,
            });
        }

        if let Some(to) = label.to().and_then(|group| group.key()) {
            self.labels.push(Label {
                kind: LabelKind::ReferenceRange,
                name: Span::from(&to),
                targets: Vec::new(),
                full_range,
            });
        }
    }

    fn process_environment(&mut self, environment: latex::Environment) {
        let Some(name) = environment
            .begin()
            .and_then(|begin| begin.name())
            .and_then(|group| group.key()) else { return };

        let name = Span::from(&name);
        self.can_be_compiled = self.can_be_compiled || name.text == "document";
        self.environments.push(name);
    }

    fn process_theorem_definition(&mut self, theorem_def: latex::TheoremDefinition) {
        let Some(name) = theorem_def.name().and_then(|name| name.key()) else { return };

        let Some(heading) = theorem_def.heading() else { return };

        self.theorem_definitions.push(TheoremDefinition {
            name: Span::from(&name),
            heading,
        });
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
pub enum LinkKind {
    Sty,
    Cls,
    Tex,
    Bib,
}

impl LinkKind {
    pub fn extensions(self) -> &'static [&'static str] {
        match self {
            Self::Sty => &["sty"],
            Self::Cls => &["cls"],
            Self::Tex => &["tex"],
            Self::Bib => &["bib"],
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct Link {
    pub kind: LinkKind,
    pub path: Span,
    pub base_dir: Option<String>,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
pub enum LabelKind {
    Definition,
    Reference,
    ReferenceRange,
}

#[derive(Debug, Clone)]
pub struct Label {
    pub kind: LabelKind,
    pub name: Span,
    pub targets: Vec<LabelTarget>,
    pub full_range: TextRange,
}

#[derive(Debug, Clone)]
pub struct LabelTarget {
    pub object: LabelObject,
    pub range: TextRange,
}

#[derive(Debug, Clone)]
pub enum LabelObject {
    Section {
        prefix: String,
        text: String,
    },
    EnumItem,
    Environment {
        name: String,
        options: Option<String>,
        caption: Option<String>,
    },
}

#[derive(Debug, Clone)]
pub struct TheoremDefinition {
    pub name: Span,
    pub heading: String,
}