summaryrefslogtreecommitdiff
path: root/support/texlab/src/syntax/latex/parser.rs
blob: 4ace4fbcd65a81d0d87b8193a5314fd16be9cc85 (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
use super::ast::*;
use crate::{
    protocol::{Range, RangeExt},
    syntax::{
        generic_ast::{Ast, AstNodeIndex},
        text::SyntaxNode,
    },
};
use std::iter::Peekable;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Scope {
    Root,
    Group,
    Options,
}

#[derive(Debug)]
pub struct Parser<I: Iterator<Item = Token>> {
    tree: Ast<Node>,
    tokens: Peekable<I>,
}

impl<I: Iterator<Item = Token>> Parser<I> {
    pub fn new(tokens: I) -> Self {
        Self {
            tree: Ast::new(),
            tokens: tokens.peekable(),
        }
    }

    pub fn parse(mut self) -> Tree {
        let children = self.content(Scope::Root);

        let range = if children.is_empty() {
            Range::new_simple(0, 0, 0, 0)
        } else {
            let start = self.tree[children[0]].start();
            let end = self.tree[children[children.len() - 1]].end();
            Range::new(start, end)
        };

        let root = self.tree.add_node(Node::Root(Root { range }));
        self.connect(root, &children);
        Tree {
            inner: self.tree,
            root,
        }
    }

    fn content(&mut self, scope: Scope) -> Vec<AstNodeIndex> {
        let mut children = Vec::new();
        while let Some(ref token) = self.tokens.peek() {
            match token.kind {
                TokenKind::Word | TokenKind::BeginOptions => {
                    children.push(self.text(scope));
                }
                TokenKind::Command => {
                    children.push(self.command());
                }
                TokenKind::Comma => {
                    children.push(self.comma());
                }
                TokenKind::Math => {
                    children.push(self.math());
                }
                TokenKind::BeginGroup => {
                    children.push(self.group(GroupKind::Group));
                }
                TokenKind::EndGroup => {
                    if scope == Scope::Root {
                        self.tokens.next();
                    } else {
                        return children;
                    }
                }
                TokenKind::EndOptions => {
                    if scope == Scope::Options {
                        return children;
                    } else {
                        children.push(self.text(scope));
                    }
                }
            }
        }
        children
    }

    fn group(&mut self, kind: GroupKind) -> AstNodeIndex {
        let left = self.tokens.next().unwrap();
        let scope = match kind {
            GroupKind::Group => Scope::Group,
            GroupKind::Options => Scope::Options,
        };

        let children = self.content(scope);
        let right_kind = match kind {
            GroupKind::Group => TokenKind::EndGroup,
            GroupKind::Options => TokenKind::EndOptions,
        };

        let right = if self.next_of_kind(right_kind) {
            self.tokens.next()
        } else {
            None
        };

        let end = right
            .as_ref()
            .map(SyntaxNode::end)
            .or_else(|| children.last().map(|child| self.tree[*child].end()))
            .unwrap_or_else(|| left.end());
        let range = Range::new(left.start(), end);

        let node = self.tree.add_node(Node::Group(Group {
            range,
            left,
            kind,
            right,
        }));
        self.connect(node, &children);
        node
    }

    fn command(&mut self) -> AstNodeIndex {
        let name = self.tokens.next().unwrap();
        let mut children = Vec::new();
        while let Some(token) = self.tokens.peek() {
            match token.kind {
                TokenKind::BeginGroup => children.push(self.group(GroupKind::Group)),
                TokenKind::BeginOptions => children.push(self.group(GroupKind::Options)),
                _ => break,
            }
        }

        let end = children
            .last()
            .map(|child| self.tree[*child].end())
            .unwrap_or_else(|| name.end());
        let range = Range::new(name.start(), end);

        let node = self.tree.add_node(Node::Command(Command { range, name }));
        self.connect(node, &children);
        node
    }

    fn text(&mut self, scope: Scope) -> AstNodeIndex {
        let mut words = Vec::new();
        while let Some(ref token) = self.tokens.peek() {
            let kind = token.kind;
            let opts = kind == TokenKind::EndOptions && scope != Scope::Options;
            if kind == TokenKind::Word || kind == TokenKind::BeginOptions || opts {
                words.push(self.tokens.next().unwrap());
            } else {
                break;
            }
        }
        let range = Range::new(words[0].start(), words[words.len() - 1].end());
        self.tree.add_node(Node::Text(Text { range, words }))
    }

    fn comma(&mut self) -> AstNodeIndex {
        let token = self.tokens.next().unwrap();
        let range = token.range();
        self.tree.add_node(Node::Comma(Comma { range, token }))
    }

    fn math(&mut self) -> AstNodeIndex {
        let token = self.tokens.next().unwrap();
        let range = token.range();
        self.tree.add_node(Node::Math(Math { range, token }))
    }

    fn connect(&mut self, parent: AstNodeIndex, children: &[AstNodeIndex]) {
        for child in children {
            self.tree.add_edge(parent, *child);
        }
    }

    fn next_of_kind(&mut self, kind: TokenKind) -> bool {
        self.tokens
            .peek()
            .filter(|token| token.kind == kind)
            .is_some()
    }
}