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
|
use std::fmt;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum LexicalError {
}
impl fmt::Display for LexicalError {
// This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("{}")
}
}
pub type Spanned<Token, Loc, LexicalError>
= Result<(Loc, Token, Loc), LexicalError>;
// The type of the parser's input.
//
// The parser iterators over tuples consisting of the token's starting
// position, the token itself, and the token's ending position.
pub(crate) type LexerItem<Token, Loc, LexicalError>
= Spanned<Token, Loc, LexicalError>;
/// The components of an OpenPGP Message.
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
pub enum Token {
PIPE,
STAR,
PLUS,
QUESTION,
LPAREN,
RPAREN,
DOT,
CARET,
DOLLAR,
BACKSLASH,
LBRACKET,
RBRACKET,
DASH,
OTHER(char),
}
assert_send_and_sync!(Token);
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&format!("{:?}", self)[..])
}
}
impl From<Token> for String {
fn from(t: Token) -> String {
use self::Token::*;
match t {
PIPE => '|'.to_string(),
STAR => '*'.to_string(),
PLUS => '+'.to_string(),
QUESTION => '?'.to_string(),
LPAREN => '('.to_string(),
RPAREN => ')'.to_string(),
DOT => '.'.to_string(),
CARET => '^'.to_string(),
DOLLAR => '$'.to_string(),
BACKSLASH => '\\'.to_string(),
LBRACKET => '['.to_string(),
RBRACKET => ']'.to_string(),
DASH => '-'.to_string(),
OTHER(c) => c.to_string(),
}
}
}
impl Token {
pub fn to_char(&self) -> char {
use self::Token::*;
match self {
PIPE => '|',
STAR => '*',
PLUS => '+',
QUESTION => '?',
LPAREN => '(',
RPAREN => ')',
DOT => '.',
CARET => '^',
DOLLAR => '$',
BACKSLASH => '\\',
LBRACKET => '[',
RBRACKET => ']',
DASH => '-',
OTHER(c) => *c,
}
}
}
pub(crate) struct Lexer<'input> {
offset: usize,
input: &'input str,
}
impl<'input> Lexer<'input> {
pub fn new(input: &'input str) -> Self {
Lexer { offset: 0, input }
}
}
impl<'input> Iterator for Lexer<'input> {
type Item = LexerItem<Token, usize, LexicalError>;
fn next(&mut self) -> Option<Self::Item> {
use self::Token::*;
tracer!(super::TRACE, "regex::Lexer::next");
// Returns the length of the first character in s in bytes.
// If s is empty, returns 0.
fn char_bytes(s: &str) -> usize {
if let Some(c) = s.chars().next() {
c.len_utf8()
} else {
0
}
}
let one = |input: &'input str| -> Option<Token> {
let c = input.chars().next()?;
Some(match c {
'|' => PIPE,
'*' => STAR,
'+' => PLUS,
'?' => QUESTION,
'(' => LPAREN,
')' => RPAREN,
'.' => DOT,
'^' => CARET,
'$' => DOLLAR,
'\\' => BACKSLASH,
'[' => LBRACKET,
']' => RBRACKET,
'-' => DASH,
_ => OTHER(c),
})
};
let l = char_bytes(self.input);
let t = match one(self.input) {
Some(t) => t,
None => return None,
};
self.input = &self.input[l..];
let start = self.offset;
let end = start + l;
self.offset += l;
t!("Returning token at offset {}: '{:?}'",
start, t);
Some(Ok((start, t, end)))
}
}
impl<'input> From<&'input str> for Lexer<'input> {
fn from(i: &'input str) -> Lexer<'input> {
Lexer::new(i)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lexer() {
fn lex(s: &str, expected: &[Token]) {
let tokens: Vec<Token> = Lexer::new(s)
.map(|t| t.unwrap().1)
.collect();
assert_eq!(&tokens[..], expected,
"{}", s);
}
use Token::*;
lex("|", &[ PIPE ]);
lex("*", &[ STAR ]);
lex("+", &[ PLUS ]);
lex("?", &[ QUESTION ]);
lex("(", &[ LPAREN ]);
lex(")", &[ RPAREN ]);
lex(".", &[ DOT ]);
lex("^", &[ CARET ]);
lex("$", &[ DOLLAR ]);
lex("\\", &[ BACKSLASH ]);
lex("[", &[ LBRACKET ]);
lex("]", &[ RBRACKET ]);
lex("-", &[ DASH ]);
lex("a", &[ OTHER('a') ]);
lex("aa", &[ OTHER('a'), OTHER('a') ]);
lex("foo", &[ OTHER('f'), OTHER('o'), OTHER('o'
|