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
use codespan::{ByteIndex, Span};
use logos::Logos;
use super::{
raw_lexer::{CommentKind, Token},
text_lexer::Text,
};
use crate::error::LexicalError;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Comment<'input> {
pub span: Span,
pub kind: CommentKind,
pub content: &'input str,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CommentBlock<'a>(pub Vec<Comment<'a>>);
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TokenMetadata<'a> {
pub pre_comment_blocks: Vec<CommentBlock<'a>>,
pub token_begins_paragraph: bool,
pub post_comment: Option<Comment<'a>>,
}
#[derive(Clone, Eq, PartialEq)]
pub struct TokenWithMetadata<'a>(pub Token<'a>, pub TokenMetadata<'a>);
impl<'a> std::fmt::Debug for TokenWithMetadata<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
pub struct Lexer<'input> {
lex: Option<logos::Lexer<'input, Token<'input>>>,
saved_token: Option<Token<'input>>,
end_of_stream_reached: bool,
pre_comment_blocks: Vec<CommentBlock<'input>>,
current_comment_block: CommentBlock<'input>,
}
impl<'input> Lexer<'input> {
pub fn new(s: &'input str) -> Self {
Self {
lex: Some(Token::lexer(s)),
saved_token: None,
end_of_stream_reached: false,
pre_comment_blocks: Vec::new(),
current_comment_block: CommentBlock::default(),
}
}
fn with_text_lexer<F, R>(&mut self, f: F) -> R
where
for<'a> F: FnOnce(&'a mut logos::Lexer<'input, Text>) -> R,
{
let mut lex = self.lex.take().unwrap().morph();
let result = f(&mut lex);
self.lex = Some(lex.morph());
result
}
fn consume_string_token(&mut self) -> Result<(Span, Token<'input>), LexicalError> {
let end_quote_type = self.lex().slice().chars().next().unwrap();
let mut error = None;
let start = self.span().start();
let out = self.with_text_lexer(|lex| Text::run_lexer(lex, end_quote_type, &mut error));
let end = self.span().end();
if let Some(e) = error {
Err(e)
} else {
Ok((Span::new(start, end), Token::StringLiteral(out)))
}
}
fn lex(&mut self) -> &mut logos::Lexer<'input, Token<'input>> {
self.lex.as_mut().unwrap()
}
fn span(&self) -> Span {
let span = self.lex.as_ref().unwrap().span();
Span::new(span.start as u32, span.end as u32)
}
fn next_raw_token(&mut self) -> Option<Token<'input>> {
if let Some(token) = self.saved_token.take() {
Some(token)
} else {
self.lex().next()
}
}
fn next_token(&mut self) -> Option<Result<(Span, bool, Token<'input>), LexicalError>> {
let mut newlines = 0;
loop {
let token_begins_paragraph = newlines >= 2;
let saved_newlines = newlines;
newlines = 0;
return match self.next_raw_token() {
Some(Token::Newline) => {
newlines = saved_newlines + 1;
continue;
}
Some(Token::Comment(c)) => {
if token_begins_paragraph && !self.current_comment_block.0.is_empty() {
self.pre_comment_blocks
.push(std::mem::take(&mut self.current_comment_block));
}
self.current_comment_block.0.push(Comment {
span: self.span(),
kind: c.kind,
content: c.content,
});
continue;
}
Some(Token::UnexpectedToken) => {
let err = format!("Unknown token {}", self.lex().slice());
Some(Err(LexicalError::new(err, self.span())))
}
Some(Token::StringLiteral(_)) => Some(
self.consume_string_token()
.map(|(span, t)| (span, token_begins_paragraph, t)),
),
Some(t) => Some(Ok((self.span(), token_begins_paragraph, t))),
None if !self.end_of_stream_reached => {
self.end_of_stream_reached = true;
Some(Ok((
self.span(),
token_begins_paragraph,
Token::EndOfStream,
)))
}
None => None,
};
}
}
fn next_post_comment(&mut self) -> Option<Comment<'input>> {
match self.next_raw_token()? {
Token::Comment(c) => Some(Comment {
span: self.span(),
kind: c.kind,
content: c.content,
}),
token => {
self.saved_token = Some(token);
None
}
}
}
}
impl<'input> Iterator for Lexer<'input> {
type Item = Result<(ByteIndex, TokenWithMetadata<'input>, ByteIndex), LexicalError>;
fn next(&mut self) -> Option<Self::Item> {
match self.next_token()? {
Ok((span, token_begins_paragraph, token)) => {
let mut pre_comment_blocks = std::mem::take(&mut self.pre_comment_blocks);
if !self.current_comment_block.0.is_empty() {
pre_comment_blocks.push(std::mem::take(&mut self.current_comment_block));
}
let metadata = TokenMetadata {
pre_comment_blocks,
token_begins_paragraph,
post_comment: self.next_post_comment(),
};
Some(Ok((
span.start(),
TokenWithMetadata(token, metadata),
span.end(),
)))
}
Err(e) => Some(Err(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tokenizer() {
let tokenizer = Lexer::new(
r#"
"foo\x41\n\r\t\b\f\"\'\/"
"\k"
"\uffff"
"
""#,
);
let tokens = tokenizer
.map(|v| v.map(|(_start, tok, _end)| tok))
.collect::<Vec<_>>();
for token in tokens {
println!("{:?}", token);
}
}
}