summaryrefslogtreecommitdiff
path: root/support/texlab/src/syntax/latex/mod.rs
blob: dc24682752985ac7f9b23eb1969b1322f11c3e62 (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
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
mod ast;
mod env;
mod finder;
mod glossary;
mod lexer;
mod math;
mod parser;
mod printer;
mod structure;

pub use self::ast::*;
pub use self::env::*;
pub use self::finder::LatexNode;
pub use self::glossary::*;
pub use self::math::*;
pub use self::printer::LatexPrinter;
pub use self::structure::*;

use self::finder::LatexFinder;
use self::lexer::LatexLexer;
use self::parser::LatexParser;
use super::language::*;
use super::text::SyntaxNode;
use crate::range::RangeExt;
use crate::workspace::Uri;
use lsp_types::{Position, Range};
use path_clean::PathClean;
use std::path::PathBuf;
use std::sync::Arc;

#[derive(Debug, Default)]
struct LatexCommandAnalyzer {
    commands: Vec<Arc<LatexCommand>>,
}

impl LatexCommandAnalyzer {
    fn parse(root: Arc<LatexRoot>) -> Vec<Arc<LatexCommand>> {
        let mut analyzer = Self::default();
        analyzer.visit_root(root);
        analyzer.commands
    }
}

impl LatexVisitor for LatexCommandAnalyzer {
    fn visit_root(&mut self, root: Arc<LatexRoot>) {
        LatexWalker::walk_root(self, root);
    }

    fn visit_group(&mut self, group: Arc<LatexGroup>) {
        LatexWalker::walk_group(self, group);
    }

    fn visit_command(&mut self, command: Arc<LatexCommand>) {
        self.commands.push(Arc::clone(&command));
        LatexWalker::walk_command(self, command);
    }

    fn visit_text(&mut self, text: Arc<LatexText>) {
        LatexWalker::walk_text(self, text);
    }

    fn visit_comma(&mut self, comma: Arc<LatexComma>) {
        LatexWalker::walk_comma(self, comma);
    }

    fn visit_math(&mut self, math: Arc<LatexMath>) {
        LatexWalker::walk_math(self, math);
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexCitation {
    pub command: Arc<LatexCommand>,
    pub index: usize,
}

impl LatexCitation {
    pub fn keys(&self) -> Vec<&LatexToken> {
        self.command.extract_comma_separated_words(0)
    }

    fn parse(commands: &[Arc<LatexCommand>]) -> Vec<Self> {
        let mut citations = Vec::new();
        for command in commands {
            for LatexCitationCommand { name, index } in &LANGUAGE_DATA.citation_commands {
                if command.name.text() == name && command.has_comma_separated_words(*index) {
                    citations.push(Self {
                        command: Arc::clone(command),
                        index: *index,
                    });
                }
            }
        }
        citations
    }
}

impl SyntaxNode for LatexCitation {
    fn range(&self) -> Range {
        self.command.range()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexInclude {
    pub command: Arc<LatexCommand>,
    pub index: usize,
    pub kind: LatexIncludeKind,
    pub all_targets: Vec<Vec<Uri>>,
    pub include_extension: bool,
}

impl LatexInclude {
    pub fn paths(&self) -> Vec<&LatexToken> {
        self.command.extract_comma_separated_words(self.index)
    }

    pub fn components(&self) -> Vec<String> {
        let mut components = Vec::new();
        for path in self.paths() {
            match self.kind {
                LatexIncludeKind::Package => components.push(format!("{}.sty", path.text())),
                LatexIncludeKind::Class => components.push(format!("{}.cls", path.text())),
                LatexIncludeKind::Latex
                | LatexIncludeKind::Bibliography
                | LatexIncludeKind::Image
                | LatexIncludeKind::Svg
                | LatexIncludeKind::Pdf
                | LatexIncludeKind::Everything => (),
            }
        }
        components
    }

    fn parse(uri: &Uri, commands: &[Arc<LatexCommand>]) -> Vec<Self> {
        let mut includes = Vec::new();
        for command in commands {
            for description in &LANGUAGE_DATA.include_commands {
                if let Some(include) = Self::parse_single(uri, &command, &description) {
                    includes.push(include);
                }
            }
        }
        includes
    }

    fn parse_single(
        uri: &Uri,
        command: &Arc<LatexCommand>,
        description: &LatexIncludeCommand,
    ) -> Option<Self> {
        if command.name.text() != description.name {
            return None;
        }

        if command.args.len() <= description.index {
            return None;
        }

        let mut all_targets = Vec::new();
        for relative_path in command.extract_comma_separated_words(description.index) {
            let mut path = uri.to_file_path().ok()?;
            path.pop();
            path.push(relative_path.text());
            path = PathBuf::from(path.to_string_lossy().into_owned().replace('\\', "/"));
            path = path.clean();
            let path = path.to_str()?.to_owned();

            let mut targets = Vec::new();
            targets.push(Uri::from_file_path(&path).ok()?);
            if let Some(extensions) = description.kind.extensions() {
                for extension in extensions {
                    let path = format!("{}.{}", &path, extension);
                    targets.push(Uri::from_file_path(&path).ok()?);
                }
            }
            all_targets.push(targets);
        }

        let include = Self {
            command: Arc::clone(command),
            index: description.index,
            kind: description.kind,
            all_targets,
            include_extension: description.include_extension,
        };
        Some(include)
    }
}

impl SyntaxNode for LatexInclude {
    fn range(&self) -> Range {
        self.command.range()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexCommandDefinition {
    pub command: Arc<LatexCommand>,
    pub definition: Arc<LatexCommand>,
    pub definition_index: usize,
    pub implementation: Arc<LatexGroup>,
    pub implementation_index: usize,
    pub argument_count_index: usize,
}

impl LatexCommandDefinition {
    fn parse(commands: &[Arc<LatexCommand>]) -> Vec<Self> {
        let mut definitions = Vec::new();
        for command in commands {
            for LatexCommandDefinitionCommand {
                name,
                definition_index,
                argument_count_index,
                implementation_index,
            } in &LANGUAGE_DATA.command_definition_commands
            {
                if command.name.text() == name
                    && command.args.len() > *definition_index
                    && command.args.len() > *implementation_index
                {
                    let definition = command.args[0].children.iter().next();
                    if let Some(LatexContent::Command(definition)) = definition {
                        definitions.push(Self {
                            command: Arc::clone(command),
                            definition: Arc::clone(definition),
                            definition_index: *definition_index,
                            implementation: Arc::clone(&command.args[*implementation_index]),
                            implementation_index: *implementation_index,
                            argument_count_index: *argument_count_index,
                        })
                    }
                }
            }
        }
        definitions
    }
}

impl SyntaxNode for LatexCommandDefinition {
    fn range(&self) -> Range {
        self.command.range()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LatexSyntaxTree {
    pub root: Arc<LatexRoot>,
    pub commands: Vec<Arc<LatexCommand>>,
    pub includes: Vec<LatexInclude>,
    pub components: Vec<String>,
    pub env: LatexEnvironmentInfo,
    pub structure: LatexStructureInfo,
    pub citations: Vec<LatexCitation>,
    pub math: LatexMathInfo,
    pub command_definitions: Vec<LatexCommandDefinition>,
    pub glossary: LatexGlossaryInfo,
}

impl LatexSyntaxTree {
    pub fn parse(uri: &Uri, text: &str) -> Self {
        let lexer = LatexLexer::new(text);
        let mut parser = LatexParser::new(lexer);
        let root = Arc::new(parser.root());
        let commands = LatexCommandAnalyzer::parse(Arc::clone(&root));
        let includes = LatexInclude::parse(uri, &commands);
        let components = includes.iter().flat_map(LatexInclude::components).collect();
        let env = LatexEnvironmentInfo::parse(&commands);
        let structure = LatexStructureInfo::parse(&commands);
        let citations = LatexCitation::parse(&commands);
        let math = LatexMathInfo::parse(Arc::clone(&root), &commands);
        let command_definitions = LatexCommandDefinition::parse(&commands);
        let glossary = LatexGlossaryInfo::parse(&commands);
        Self {
            root,
            commands,
            includes,
            components,
            env,
            structure,
            citations,
            math,
            command_definitions,
            glossary,
        }
    }

    pub fn find(&self, position: Position) -> Vec<LatexNode> {
        let mut finder = LatexFinder::new(position);
        finder.visit_root(Arc::clone(&self.root));
        finder.results
    }

    pub fn find_command_by_name(&self, position: Position) -> Option<Arc<LatexCommand>> {
        for result in self.find(position) {
            if let LatexNode::Command(command) = result {
                if command.name.range().contains(position)
                    && command.name.start().character != position.character
                {
                    return Some(command);
                }
            }
        }
        None
    }

    pub fn find_label_by_range(&self, range: Range) -> Option<&LatexLabel> {
        self.structure
            .labels
            .iter()
            .filter(|label| label.kind == LatexLabelKind::Definition)
            .filter(|label| label.names().len() == 1)
            .find(|label| range.contains(label.start()))
    }

    pub fn find_label_by_environment(&self, environment: &LatexEnvironment) -> Option<&LatexLabel> {
        self.structure
            .labels
            .iter()
            .filter(|label| label.kind == LatexLabelKind::Definition)
            .filter(|label| label.names().len() == 1)
            .find(|label| self.is_direct_child(environment, label.start()))
    }

    pub fn is_enumeration_item(&self, enumeration: &LatexEnvironment, item: &LatexItem) -> bool {
        enumeration.range().contains(item.start())
            && !self
                .env
                .environments
                .iter()
                .filter(|env| *env != enumeration)
                .filter(|env| env.left.is_enum() && enumeration.range().contains(env.start()))
                .any(|env| env.range().contains(item.start()))
    }

    pub fn is_direct_child(&self, environment: &LatexEnvironment, position: Position) -> bool {
        environment.range().contains(position)
            && !self
                .env
                .environments
                .iter()
                .filter(|env| *env != environment)
                .filter(|env| environment.range().contains(env.start()))
                .any(|env| env.range().contains(position))
    }
}

pub fn extract_group(content: &LatexGroup) -> String {
    if content.children.is_empty() || content.right.is_none() {
        return String::new();
    }

    let mut printer = LatexPrinter::new(content.children[0].start());
    for child in &content.children {
        child.accept(&mut printer);
    }
    printer.output
}