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
use std::iter::Peekable;
use std::str::Chars;
use crate::Result;
#[derive(Debug, PartialEq, Clone)]
pub enum Token {
// Keywords
OpenQasm,
Include,
Qreg,
Creg,
Gate,
Opaque,
If,
Barrier,
Measure,
Reset,
U,
CX,
Pi,
// Logic & Control
Arrow, // ->
EqEq, // ==
// Binary Operators
Plus,
Minus,
Star,
Slash,
Caret,
// Unary Math Functions
Sin,
Cos,
Tan,
Exp,
Ln,
Sqrt,
// Data
Ident(String),
StringLit(String),
Int(usize),
Real(f64),
// Punctuation: (, ), [, ], {, }, ;, ,
Punct(char),
Eof,
}
pub struct Lexer<'a> {
pub chars: Peekable<Chars<'a>>,
pub line: usize,
}
impl<'a> Lexer<'a> {
pub fn new(source: &'a str) -> Self {
Lexer {
chars: source.chars().peekable(),
line: 1,
}
}
/// Advances the iterator and tracks newlines for error reporting.
fn advance(&mut self) -> Option<char> {
let c = self.chars.next();
if c == Some('\n') {
self.line += 1;
}
c
}
fn lex_error(&self, message: impl Into<String>) -> crate::Error {
crate::Error::LanguageError {
message: message.into(),
lineno: self.line,
}
}
fn skip_whitespace(&mut self) {
while self.chars.peek().is_some_and(|&c| c.is_whitespace()) {
self.advance();
}
}
pub fn next_token(&mut self) -> Result<Token> {
// Use a loop so if we consume a comment, we can restart the token search
loop {
self.skip_whitespace();
let c = match self.advance() {
Some(c) => c,
None => return Ok(Token::Eof),
};
match c {
'/' => {
if self.chars.peek().is_some_and(|&nc| nc == '/') {
// Comment: skip to end of line and restart loop
while self.chars.peek().is_some_and(|&nc| nc != '\n') {
self.advance();
}
continue;
} else {
// Division operator
return Ok(Token::Slash);
}
}
';' | ',' | '(' | ')' | '[' | ']' | '{' | '}' => return Ok(Token::Punct(c)),
'+' => return Ok(Token::Plus),
'*' => return Ok(Token::Star),
'^' => return Ok(Token::Caret),
'-' => {
if self.chars.peek().is_some_and(|&nc| nc == '>') {
self.advance();
return Ok(Token::Arrow);
} else {
return Ok(Token::Minus);
}
}
'=' => {
if self.chars.peek().is_some_and(|&nc| nc == '=') {
self.advance();
return Ok(Token::EqEq);
} else {
return Err(self.lex_error("expected '==' but found single '='"));
}
}
'"' => {
let mut s = String::new();
loop {
match self.advance() {
Some('"') => break,
Some(nc) => s.push(nc),
None => return Err(self.lex_error("unterminated string literal")),
}
}
return Ok(Token::StringLit(s));
}
_ if c.is_alphabetic() || c == '_' => {
let mut s = String::new();
s.push(c);
while self
.chars
.peek()
.is_some_and(|&nc| nc.is_alphanumeric() || nc == '_')
{
// peek() confirmed Some, so advance() is infallible here
s.push(self.advance().expect("peek guaranteed Some"));
}
return Ok(match s.as_str() {
"OPENQASM" => Token::OpenQasm,
"include" => Token::Include,
"qreg" => Token::Qreg,
"creg" => Token::Creg,
"gate" => Token::Gate,
"opaque" => Token::Opaque,
"if" => Token::If,
"barrier" => Token::Barrier,
"measure" => Token::Measure,
"reset" => Token::Reset,
"U" => Token::U,
"CX" => Token::CX,
"pi" => Token::Pi,
"sin" => Token::Sin,
"cos" => Token::Cos,
"tan" => Token::Tan,
"exp" => Token::Exp,
"ln" => Token::Ln,
"sqrt" => Token::Sqrt,
_ => Token::Ident(s),
});
}
_ if c.is_ascii_digit() || c == '.' => {
let mut s = String::new();
s.push(c);
let mut is_real = c == '.';
while let Some(&nc) = self.chars.peek() {
if nc.is_ascii_digit()
|| nc == '.'
|| nc == 'e'
|| nc == 'E'
|| ((nc == '+' || nc == '-') && (s.ends_with('e') || s.ends_with('E')))
{
if nc == '.' || nc == 'e' || nc == 'E' {
is_real = true;
}
// peek() confirmed Some, so advance() is infallible here
s.push(self.advance().expect("peek guaranteed Some"));
} else {
break;
}
}
if is_real {
let val = s.parse::<f64>().map_err(|e| {
self.lex_error(format!("invalid float literal '{}': {}", s, e))
})?;
return Ok(Token::Real(val));
} else {
let val = s.parse::<usize>().map_err(|e| {
self.lex_error(format!("invalid integer literal '{}': {}", s, e))
})?;
return Ok(Token::Int(val));
}
}
_ => return Err(self.lex_error(format!("unexpected character '{}'", c))),
}
}
}
}