cranelift_isle/lexer.rs
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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
//! Lexer for the ISLE language.
use std::borrow::Cow;
use crate::error::{Error, Span};
use crate::files::Files;
type Result<T> = std::result::Result<T, Error>;
/// The lexer.
///
/// Breaks source text up into a sequence of tokens (with source positions).
#[derive(Clone, Debug)]
pub struct Lexer<'src> {
src: &'src str,
pos: Pos,
lookahead: Option<(Pos, Token)>,
}
/// A source position.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Hash, PartialOrd, Ord)]
pub struct Pos {
/// This source position's file.
///
/// Indexes into `Lexer::filenames` early in the compiler pipeline, and
/// later into `TypeEnv::filenames` once we get into semantic analysis.
pub file: usize,
/// This source position's byte offset in the file.
pub offset: usize,
}
impl Pos {
/// Create a new `Pos`.
pub fn new(file: usize, offset: usize) -> Self {
Self { file, offset }
}
/// Print this source position as `file.isle line 12`.
pub fn pretty_print_line(&self, files: &Files) -> String {
format!(
"{} line {}",
files.file_name(self.file).unwrap(),
files.file_line_map(self.file).unwrap().line(self.offset)
)
}
}
/// A token of ISLE source.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Token {
/// Left paren.
LParen,
/// Right paren.
RParen,
/// A symbol, e.g. `Foo`.
Symbol(String),
/// An integer.
Int(i128),
/// `@`
At,
}
impl<'src> Lexer<'src> {
/// Create a new lexer for the given source contents
pub fn new(file: usize, src: &'src str) -> Result<Lexer<'src>> {
let mut l = Lexer {
src,
pos: Pos::new(file, 0),
lookahead: None,
};
l.reload()?;
Ok(l)
}
/// Get the lexer's current source position.
pub fn pos(&self) -> Pos {
self.pos
}
fn advance_pos(&mut self) {
self.pos.offset += 1;
}
fn error(&self, pos: Pos, msg: impl Into<String>) -> Error {
Error::ParseError {
msg: msg.into(),
span: Span::new_single(pos),
}
}
fn next_token(&mut self) -> Result<Option<(Pos, Token)>> {
fn is_sym_first_char(c: u8) -> bool {
match c {
b'-' | b'0'..=b'9' | b'(' | b')' | b';' | b'<' | b'>' => false,
c if c.is_ascii_whitespace() => false,
_ => true,
}
}
fn is_sym_other_char(c: u8) -> bool {
match c {
b'(' | b')' | b';' | b'@' | b'<' => false,
c if c.is_ascii_whitespace() => false,
_ => true,
}
}
// Skip any whitespace and any comments.
while let Some(c) = self.peek_byte() {
match c {
c if c.is_ascii_whitespace() => self.advance_pos(),
b';' => {
while let Some(c) = self.peek_byte() {
match c {
b'\n' => break,
_ => self.advance_pos(),
}
}
}
_ => break,
}
}
let Some(c) = self.peek_byte() else {
return Ok(None);
};
let char_pos = self.pos();
match c {
b'(' => {
self.advance_pos();
Ok(Some((char_pos, Token::LParen)))
}
b')' => {
self.advance_pos();
Ok(Some((char_pos, Token::RParen)))
}
b'@' => {
self.advance_pos();
Ok(Some((char_pos, Token::At)))
}
c if is_sym_first_char(c) => {
let start = self.pos.offset;
let start_pos = self.pos();
while let Some(c) = self.peek_byte() {
match c {
c if is_sym_other_char(c) => self.advance_pos(),
_ => break,
}
}
let end = self.pos.offset;
let s = &self.src[start..end];
debug_assert!(!s.is_empty());
Ok(Some((start_pos, Token::Symbol(s.to_string()))))
}
c @ (b'0'..=b'9' | b'-') => {
let start_pos = self.pos();
let mut neg = false;
if c == b'-' {
self.advance_pos();
neg = true;
}
let mut radix = 10;
// Check for prefixed literals.
match (
self.src.as_bytes().get(self.pos.offset),
self.src.as_bytes().get(self.pos.offset + 1),
) {
(Some(b'0'), Some(b'x' | b'X')) => {
self.advance_pos();
self.advance_pos();
radix = 16;
}
(Some(b'0'), Some(b'o' | b'O')) => {
self.advance_pos();
self.advance_pos();
radix = 8;
}
(Some(b'0'), Some(b'b' | b'B')) => {
self.advance_pos();
self.advance_pos();
radix = 2;
}
_ => {}
}
// Find the range in the buffer for this integer literal. We'll
// pass this range to `i64::from_str_radix` to do the actual
// string-to-integer conversion.
let start = self.pos.offset;
while let Some(c) = self.peek_byte() {
match c {
b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F' | b'_' => self.advance_pos(),
_ => break,
}
}
let end = self.pos.offset;
let s = &self.src[start..end];
let s = if s.contains('_') {
Cow::Owned(s.replace('_', ""))
} else {
Cow::Borrowed(s)
};
// Support either signed range (-2^127..2^127) or
// unsigned range (0..2^128).
let num = match u128::from_str_radix(&s, radix) {
Ok(num) => num,
Err(err) => return Err(self.error(start_pos, err.to_string())),
};
let num = match (neg, num) {
(true, 0x80000000000000000000000000000000) => {
return Err(self.error(start_pos, "integer literal cannot fit in i128"))
}
(true, _) => -(num as i128),
(false, _) => num as i128,
};
let tok = Token::Int(num);
Ok(Some((start_pos, tok)))
}
c => Err(self.error(self.pos, format!("Unexpected character '{c}'"))),
}
}
/// Get the next token from this lexer's token stream, if any.
pub fn next(&mut self) -> Result<Option<(Pos, Token)>> {
let tok = self.lookahead.take();
self.reload()?;
Ok(tok)
}
fn reload(&mut self) -> Result<()> {
if self.lookahead.is_none() && self.pos.offset < self.src.len() {
self.lookahead = self.next_token()?;
}
Ok(())
}
/// Peek ahead at the next token.
pub fn peek(&self) -> Option<&(Pos, Token)> {
self.lookahead.as_ref()
}
/// Are we at the end of the source input?
pub fn eof(&self) -> bool {
self.lookahead.is_none()
}
fn peek_byte(&self) -> Option<u8> {
self.src.as_bytes().get(self.pos.offset).copied()
}
}
impl Token {
/// Is this an `Int` token?
pub fn is_int(&self) -> bool {
matches!(self, Token::Int(_))
}
/// Is this a `Sym` token?
pub fn is_sym(&self) -> bool {
matches!(self, Token::Symbol(_))
}
}
#[cfg(test)]
mod test {
use super::*;
#[track_caller]
fn lex(src: &str) -> Vec<Token> {
let mut toks = vec![];
let mut lexer = Lexer::new(0, src).unwrap();
while let Some((_, tok)) = lexer.next().unwrap() {
toks.push(tok);
}
toks
}
#[test]
fn lexer_basic() {
assert_eq!(
lex(";; comment\n; another\r\n \t(one two three 23 -568 )\n"),
[
Token::LParen,
Token::Symbol("one".to_string()),
Token::Symbol("two".to_string()),
Token::Symbol("three".to_string()),
Token::Int(23),
Token::Int(-568),
Token::RParen
]
);
}
#[test]
fn ends_with_sym() {
assert_eq!(lex("asdf"), [Token::Symbol("asdf".to_string())]);
}
#[test]
fn ends_with_num() {
assert_eq!(lex("23"), [Token::Int(23)]);
}
#[test]
fn weird_syms() {
assert_eq!(
lex("(+ [] => !! _test!;comment\n)"),
[
Token::LParen,
Token::Symbol("+".to_string()),
Token::Symbol("[]".to_string()),
Token::Symbol("=>".to_string()),
Token::Symbol("!!".to_string()),
Token::Symbol("_test!".to_string()),
Token::RParen,
]
);
}
#[test]
fn integers() {
assert_eq!(
lex("0 1 -1"),
[Token::Int(0), Token::Int(1), Token::Int(-1)]
);
assert_eq!(
lex("340_282_366_920_938_463_463_374_607_431_768_211_455"),
[Token::Int(-1)]
);
assert_eq!(
lex("170_141_183_460_469_231_731_687_303_715_884_105_727"),
[Token::Int(i128::MAX)]
);
assert!(Lexer::new(0, "-170_141_183_460_469_231_731_687_303_715_884_105_728").is_err())
}
}