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
use std::{iter::Peekable, str::Chars, sync::Arc};
use codemap::{File, Span};
const FORM_FEED: char = '\x0C';
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) struct Token {
pub kind: char,
pos: u32,
}
#[derive(Debug, Clone)]
pub(crate) struct Lexer {
buf: Vec<Token>,
entire_span: Span,
cursor: usize,
/// If the input this lexer is spanned over is larger than the original span.
/// This is possible due to interpolation.
is_expanded: bool,
}
impl Lexer {
pub fn raw_text(&self, start: usize) -> String {
self.buf[start..self.cursor]
.iter()
.map(|t| t.kind)
.collect()
}
/// Whether a newline lies between `start` and the cursor.
///
/// Like [`Self::raw_text`] with a search, but without building the
/// string. The lexer has already turned `\r`, `\r\n` and form feeds into
/// `\n`, so this is the one character to look for.
pub fn contains_newline_since(&self, start: usize) -> bool {
self.buf[start..self.cursor].iter().any(|t| t.kind == '\n')
}
pub fn next_char_is(&self, c: char) -> bool {
matches!(self.peek(), Some(Token { kind, .. }) if kind == c)
}
/// Gets the span of the character at the given index.
///
/// Past the last character it returns an empty span at the end of the
/// input, which is where dart-sass points an error about input that ended
/// too early. If the input is empty, that is an empty span at its start.
fn span_at_index(&self, idx: usize) -> Span {
if self.is_expanded {
return self.entire_span;
}
let (start, len) = match self.buf.get(idx) {
Some(tok) => (tok.pos, tok.kind.len_utf8() as u32),
None => match self.buf.last() {
Some(tok) => (tok.pos + tok.kind.len_utf8() as u32, 0),
None => (0, 0),
},
};
self.entire_span
.subspan(u64::from(start), u64::from(start + len))
}
/// Moves an empty error span back to the line where the problem is.
///
/// If only whitespace separates `span` from the previous non-whitespace
/// character, and that whitespace holds a newline, this returns an empty
/// span at the last such newline; otherwise it returns `span`. So a
/// missing token reported at the start of the next line, or at the end of
/// input after a trailing newline, points at the end of the line that
/// needed it. A port of dart-sass's `Parser._firstNewlineBefore`.
///
/// A non-empty span, or one in a lexer over interpolated text whose
/// offsets do not map to the source, is returned unchanged.
pub fn first_newline_before(&self, span: Span) -> Span {
if self.is_expanded || span.len() != 0 || !self.entire_span.contains(span) {
return span;
}
let offset = (span.low() - self.entire_span.low()) as u32;
let mut last_newline = None;
for tok in self.buf.iter().rev().filter(|tok| tok.pos < offset) {
match tok.kind {
'\n' => last_newline = Some(tok.pos),
' ' | '\t' => {}
_ => {
return match last_newline {
Some(pos) => self.entire_span.subspan(u64::from(pos), u64::from(pos)),
None => span,
};
}
}
}
// Nothing but whitespace precedes the span.
span
}
/// The span of the characters at indices `start..end`.
///
/// In a lexer over interpolated text, whose offsets do not map to the
/// source, this is the whole span the lexer covers, as every other span
/// such a lexer answers is.
pub fn span_between(&self, start: usize, end: usize) -> Span {
if end <= start {
return self.span_at_index(start).subspan(0, 0);
}
self.span_at_index(start).merge(self.span_at_index(end - 1))
}
pub fn span_from(&self, start: usize) -> Span {
let start = self.span_at_index(start);
let end = self.prev_span();
start.merge(end)
}
pub fn prev_span(&self) -> Span {
self.span_at_index(self.cursor.saturating_sub(1))
}
pub fn current_span(&self) -> Span {
self.span_at_index(self.cursor)
}
pub fn peek(&self) -> Option<Token> {
self.buf.get(self.cursor).copied()
}
/// Peeks the previous token without modifying the peek cursor
pub fn peek_previous(&mut self) -> Option<Token> {
self.buf.get(self.cursor.checked_sub(1)?).copied()
}
/// Peeks `n` from current peeked position without modifying cursor
pub fn peek_n(&self, n: usize) -> Option<Token> {
self.buf.get(self.cursor + n).copied()
}
/// Peeks `n` behind current peeked position without modifying cursor
pub fn peek_n_backwards(&self, n: usize) -> Option<Token> {
self.buf.get(self.cursor.checked_sub(n)?).copied()
}
/// Set cursor to position and reset peek
pub fn set_cursor(&mut self, cursor: usize) {
self.cursor = cursor;
}
pub fn cursor(&self) -> usize {
self.cursor
}
}
impl Iterator for Lexer {
type Item = Token;
fn next(&mut self) -> Option<Self::Item> {
self.buf.get(self.cursor).copied().inspect(|_| {
self.cursor += 1;
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.buf.len() - self.cursor;
(remaining, Some(remaining))
}
}
/// Lex a string into a series of tokens
pub(crate) struct TokenLexer<'a> {
buf: Peekable<Chars<'a>>,
cursor: u32,
}
// todo: maybe char indices?
impl<'a> TokenLexer<'a> {
pub fn new(buf: Peekable<Chars<'a>>) -> TokenLexer<'a> {
Self { buf, cursor: 0 }
}
}
impl Iterator for TokenLexer<'_> {
type Item = Token;
fn next(&mut self) -> Option<Self::Item> {
let kind = match self.buf.next()? {
FORM_FEED => '\n',
'\r' => {
if self.buf.peek() == Some(&'\n') {
self.cursor += 1;
self.buf.next();
}
'\n'
}
c => c,
};
let len = kind.len_utf8() as u32;
let pos = self.cursor;
self.cursor += len;
Some(Token { pos, kind })
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.buf.size_hint()
}
}
impl Lexer {
pub fn new_from_file(file: &Arc<File>) -> Self {
let buf = TokenLexer::new(file.source().chars().peekable()).collect();
Self::new(buf, file.span, false)
}
pub fn new_from_string(s: &str, entire_span: Span) -> Self {
let is_expanded = s.len() as u64 > entire_span.len();
let buf = TokenLexer::new(s.chars().peekable()).collect();
Self::new(buf, entire_span, is_expanded)
}
fn new(buf: Vec<Token>, entire_span: Span, is_expanded: bool) -> Self {
Lexer {
buf,
cursor: 0,
entire_span,
is_expanded,
}
}
}