use crate::token::Span;
use crate::Error;
use std::borrow::Cow;
use std::char;
use std::fmt;
use std::slice;
use std::str;
#[derive(Clone)]
pub struct Lexer<'a> {
input: &'a str,
allow_confusing_unicode: bool,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Token {
pub kind: TokenKind,
pub offset: usize,
pub len: u32,
}
const _: () = {
assert!(std::mem::size_of::<Token>() <= std::mem::size_of::<u64>() * 2);
};
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TokenKind {
LineComment,
BlockComment,
Whitespace,
LParen,
RParen,
String,
Id,
Keyword,
Reserved,
Integer(IntegerKind),
Float(FloatKind),
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct IntegerKind {
sign: Option<SignToken>,
has_underscores: bool,
hex: bool,
}
#[allow(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum FloatKind {
#[doc(hidden)]
Inf { negative: bool },
#[doc(hidden)]
Nan { negative: bool },
#[doc(hidden)]
NanVal {
negative: bool,
has_underscores: bool,
},
#[doc(hidden)]
Normal { has_underscores: bool, hex: bool },
}
enum ReservedKind {
String,
Idchars,
Reserved,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LexError {
DanglingBlockComment,
Unexpected(char),
InvalidStringElement(char),
InvalidStringEscape(char),
InvalidHexDigit(char),
InvalidDigit(char),
Expected {
wanted: char,
found: char,
},
UnexpectedEof,
NumberTooBig,
InvalidUnicodeValue(u32),
LoneUnderscore,
ConfusingUnicode(char),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SignToken {
Plus,
Minus,
}
#[derive(Debug, PartialEq)]
pub struct Integer<'a> {
sign: Option<SignToken>,
val: Cow<'a, str>,
hex: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Float<'a> {
Nan {
val: Option<Cow<'a, str>>,
negative: bool,
},
Inf {
#[allow(missing_docs)]
negative: bool,
},
Val {
hex: bool,
integral: Cow<'a, str>,
decimal: Option<Cow<'a, str>>,
exponent: Option<Cow<'a, str>>,
},
}
macro_rules! idchars {
() => {
b'0'..=b'9'
| b'A'..=b'Z'
| b'a'..=b'z'
| b'!'
| b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'/'
| b':'
| b'<'
| b'='
| b'>'
| b'?'
| b'@'
| b'\\'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
}
}
impl<'a> Lexer<'a> {
pub fn new(input: &str) -> Lexer<'_> {
Lexer {
input,
allow_confusing_unicode: false,
}
}
pub fn input(&self) -> &'a str {
self.input
}
pub fn allow_confusing_unicode(&mut self, allow: bool) -> &mut Self {
self.allow_confusing_unicode = allow;
self
}
pub fn parse(&self, pos: &mut usize) -> Result<Option<Token>, Error> {
let offset = *pos;
Ok(match self.parse_kind(pos)? {
Some(kind) => Some(Token {
kind,
offset,
len: (*pos - offset).try_into().unwrap(),
}),
None => None,
})
}
fn parse_kind(&self, pos: &mut usize) -> Result<Option<TokenKind>, Error> {
let start = *pos;
let remaining = &self.input.as_bytes()[start..];
let byte = match remaining.first() {
Some(b) => b,
None => return Ok(None),
};
match byte {
b'(' => match remaining.get(1) {
Some(b';') => {
let mut level = 1;
let mut iter = remaining[2..].iter();
while let Some(ch) = iter.next() {
match ch {
b'(' => {
if let Some(b';') = iter.as_slice().first() {
level += 1;
iter.next();
}
}
b';' => {
if let Some(b')') = iter.as_slice().first() {
level -= 1;
iter.next();
if level == 0 {
let len = remaining.len() - iter.as_slice().len();
let comment = &self.input[start..][..len];
*pos += len;
self.check_confusing_comment(*pos, comment)?;
return Ok(Some(TokenKind::BlockComment));
}
}
}
_ => {}
}
}
Err(self.error(start, LexError::DanglingBlockComment))
}
_ => {
*pos += 1;
Ok(Some(TokenKind::LParen))
}
},
b')' => {
*pos += 1;
Ok(Some(TokenKind::RParen))
}
b' ' | b'\n' | b'\r' | b'\t' => {
self.skip_ws(pos);
Ok(Some(TokenKind::Whitespace))
}
c @ (idchars!() | b'"') => {
let (kind, src) = self.parse_reserved(pos)?;
match kind {
ReservedKind::String => return Ok(Some(TokenKind::String)),
ReservedKind::Idchars => {
if let Some(ret) = self.classify_number(src) {
return Ok(Some(ret));
} else if *c == b'$' && src.len() > 1 {
return Ok(Some(TokenKind::Id));
} else if b'a' <= *c && *c <= b'z' {
return Ok(Some(TokenKind::Keyword));
}
}
ReservedKind::Reserved => {}
}
Ok(Some(TokenKind::Reserved))
}
b';' => match remaining.get(1) {
Some(b';') => {
let remaining = &self.input[*pos..];
let byte_pos = memchr::memchr2(b'\n', b'\r', remaining.as_bytes())
.unwrap_or(remaining.len());
*pos += byte_pos;
let comment = &remaining[..byte_pos];
self.check_confusing_comment(*pos, comment)?;
Ok(Some(TokenKind::LineComment))
}
_ => {
*pos += 1;
Ok(Some(TokenKind::Reserved))
}
},
b',' | b'[' | b']' | b'{' | b'}' => {
*pos += 1;
Ok(Some(TokenKind::Reserved))
}
_ => {
let ch = self.input[start..].chars().next().unwrap();
Err(self.error(*pos, LexError::Unexpected(ch)))
}
}
}
fn skip_ws(&self, pos: &mut usize) {
#[rustfmt::skip]
const WS: [u8; 256] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let remaining = &self.input[*pos..];
let non_ws_pos = remaining
.as_bytes()
.iter()
.position(|b| WS[*b as usize] != 1)
.unwrap_or(remaining.len());
*pos += non_ws_pos;
}
fn parse_reserved(&self, pos: &mut usize) -> Result<(ReservedKind, &'a str), Error> {
let mut idchars = false;
let mut strings = 0u32;
let start = *pos;
while let Some(byte) = self.input.as_bytes().get(*pos) {
match byte {
idchars!() => {
idchars = true;
*pos += 1;
}
b'"' => {
strings += 1;
*pos += 1;
let mut it = self.input[*pos..].chars();
let result = Lexer::parse_str(&mut it, self.allow_confusing_unicode);
*pos = self.input.len() - it.as_str().len();
match result {
Ok(_) => {}
Err(e) => {
let err_pos = match &e {
LexError::UnexpectedEof => self.input.len(),
_ => self.input[..*pos].char_indices().next_back().unwrap().0,
};
return Err(self.error(err_pos, e));
}
}
}
_ => break,
}
}
let ret = &self.input[start..*pos];
Ok(match (idchars, strings) {
(false, 0) => unreachable!(),
(false, 1) => (ReservedKind::String, ret),
(true, 0) => (ReservedKind::Idchars, ret),
_ => (ReservedKind::Reserved, ret),
})
}
fn classify_number(&self, src: &str) -> Option<TokenKind> {
let (sign, num) = if let Some(stripped) = src.strip_prefix('+') {
(Some(SignToken::Plus), stripped)
} else if let Some(stripped) = src.strip_prefix('-') {
(Some(SignToken::Minus), stripped)
} else {
(None, src)
};
let negative = sign == Some(SignToken::Minus);
if num == "inf" {
return Some(TokenKind::Float(FloatKind::Inf { negative }));
} else if num == "nan" {
return Some(TokenKind::Float(FloatKind::Nan { negative }));
} else if let Some(stripped) = num.strip_prefix("nan:0x") {
let mut it = stripped.as_bytes().iter();
let has_underscores = skip_underscores(&mut it, |x| char::from(x).is_ascii_hexdigit())?;
if it.next().is_some() {
return None;
}
return Some(TokenKind::Float(FloatKind::NanVal {
negative,
has_underscores,
}));
}
let test_valid: fn(u8) -> bool;
let (mut it, hex) = if let Some(stripped) = num.strip_prefix("0x") {
test_valid = |x: u8| char::from(x).is_ascii_hexdigit();
(stripped.as_bytes().iter(), true)
} else {
test_valid = |x: u8| char::from(x).is_ascii_digit();
(num.as_bytes().iter(), false)
};
let mut has_underscores = skip_underscores(&mut it, test_valid)?;
match it.clone().next() {
Some(_) => {}
None => {
return Some(TokenKind::Integer(IntegerKind {
has_underscores,
sign,
hex,
}))
}
}
if it.clone().next() == Some(&b'.') {
it.next();
match it.clone().next() {
Some(c) if test_valid(*c) => {
if skip_underscores(&mut it, test_valid)? {
has_underscores = true;
}
}
Some(_) | None => {}
}
};
match (hex, it.next()) {
(true, Some(b'p')) | (true, Some(b'P')) | (false, Some(b'e')) | (false, Some(b'E')) => {
match it.clone().next() {
Some(b'-') => {
it.next();
}
Some(b'+') => {
it.next();
}
_ => {}
}
if skip_underscores(&mut it, |x| char::from(x).is_ascii_digit())? {
has_underscores = true;
}
}
(_, None) => {}
_ => return None,
}
if it.next().is_some() {
return None;
}
return Some(TokenKind::Float(FloatKind::Normal {
has_underscores,
hex,
}));
fn skip_underscores<'a>(
it: &mut slice::Iter<'_, u8>,
good: fn(u8) -> bool,
) -> Option<bool> {
let mut last_underscore = false;
let mut has_underscores = false;
let first = *it.next()?;
if !good(first) {
return None;
}
while let Some(c) = it.clone().next() {
if *c == b'_' && !last_underscore {
has_underscores = true;
it.next();
last_underscore = true;
continue;
}
if !good(*c) {
break;
}
last_underscore = false;
it.next();
}
if last_underscore {
return None;
}
Some(has_underscores)
}
}
fn check_confusing_comment(&self, end: usize, comment: &str) -> Result<(), Error> {
if self.allow_confusing_unicode {
return Ok(());
}
let bytes = comment.as_bytes();
for pos in memchr::Memchr::new(0xe2, bytes) {
if let Some(c) = comment[pos..].chars().next() {
if is_confusing_unicode(c) {
let pos = end - comment.len() + pos;
return Err(self.error(pos, LexError::ConfusingUnicode(c)));
}
}
}
Ok(())
}
fn parse_str(
it: &mut str::Chars<'a>,
allow_confusing_unicode: bool,
) -> Result<Cow<'a, [u8]>, LexError> {
enum State {
Start,
String(Vec<u8>),
}
let orig = it.as_str();
let mut state = State::Start;
loop {
match it.next().ok_or(LexError::UnexpectedEof)? {
'"' => break,
'\\' => {
match state {
State::String(_) => {}
State::Start => {
let pos = orig.len() - it.as_str().len() - 1;
state = State::String(orig[..pos].as_bytes().to_vec());
}
}
let buf = match &mut state {
State::String(b) => b,
State::Start => unreachable!(),
};
match it.next().ok_or(LexError::UnexpectedEof)? {
'"' => buf.push(b'"'),
'\'' => buf.push(b'\''),
't' => buf.push(b'\t'),
'n' => buf.push(b'\n'),
'r' => buf.push(b'\r'),
'\\' => buf.push(b'\\'),
'u' => {
Lexer::must_eat_char(it, '{')?;
let n = Lexer::hexnum(it)?;
let c = char::from_u32(n).ok_or(LexError::InvalidUnicodeValue(n))?;
buf.extend(c.encode_utf8(&mut [0; 4]).as_bytes());
Lexer::must_eat_char(it, '}')?;
}
c1 if c1.is_ascii_hexdigit() => {
let c2 = Lexer::hexdigit(it)?;
buf.push(to_hex(c1) * 16 + c2);
}
c => return Err(LexError::InvalidStringEscape(c)),
}
}
c if (c as u32) < 0x20 || c as u32 == 0x7f => {
return Err(LexError::InvalidStringElement(c))
}
c if !allow_confusing_unicode && is_confusing_unicode(c) => {
return Err(LexError::ConfusingUnicode(c))
}
c => match &mut state {
State::Start => {}
State::String(v) => {
v.extend(c.encode_utf8(&mut [0; 4]).as_bytes());
}
},
}
}
match state {
State::Start => Ok(orig[..orig.len() - it.as_str().len() - 1].as_bytes().into()),
State::String(s) => Ok(s.into()),
}
}
fn hexnum(it: &mut str::Chars<'_>) -> Result<u32, LexError> {
let n = Lexer::hexdigit(it)?;
let mut last_underscore = false;
let mut n = n as u32;
while let Some(c) = it.clone().next() {
if c == '_' {
it.next();
last_underscore = true;
continue;
}
if !c.is_ascii_hexdigit() {
break;
}
last_underscore = false;
it.next();
n = n
.checked_mul(16)
.and_then(|n| n.checked_add(to_hex(c) as u32))
.ok_or(LexError::NumberTooBig)?;
}
if last_underscore {
return Err(LexError::LoneUnderscore);
}
Ok(n)
}
fn hexdigit(it: &mut str::Chars<'_>) -> Result<u8, LexError> {
let ch = Lexer::must_char(it)?;
if ch.is_ascii_hexdigit() {
Ok(to_hex(ch))
} else {
Err(LexError::InvalidHexDigit(ch))
}
}
fn must_char(it: &mut str::Chars<'_>) -> Result<char, LexError> {
it.next().ok_or(LexError::UnexpectedEof)
}
fn must_eat_char(it: &mut str::Chars<'_>, wanted: char) -> Result<(), LexError> {
let found = Lexer::must_char(it)?;
if wanted == found {
Ok(())
} else {
Err(LexError::Expected { wanted, found })
}
}
fn error(&self, pos: usize, kind: LexError) -> Error {
Error::lex(Span { offset: pos }, self.input, kind)
}
pub fn iter(&self, mut pos: usize) -> impl Iterator<Item = Result<Token, Error>> + '_ {
std::iter::from_fn(move || self.parse(&mut pos).transpose())
}
pub fn annotation(&self, mut pos: usize) -> Option<&'a str> {
let bytes = self.input.as_bytes();
if bytes.get(pos) != Some(&b'@') {
return None;
}
match self.parse(&mut pos) {
Ok(Some(token)) => {
match token.kind {
TokenKind::Reserved => {}
_ => return None,
}
if token.len == 1 {
None } else {
Some(&token.src(self.input)[1..])
}
}
Ok(None) | Err(_) => None,
}
}
}
impl Token {
pub fn src<'a>(&self, s: &'a str) -> &'a str {
&s[self.offset..][..self.len.try_into().unwrap()]
}
pub fn id<'a>(&self, s: &'a str) -> &'a str {
&self.src(s)[1..]
}
pub fn keyword<'a>(&self, s: &'a str) -> &'a str {
self.src(s)
}
pub fn reserved<'a>(&self, s: &'a str) -> &'a str {
self.src(s)
}
pub fn string<'a>(&self, s: &'a str) -> Cow<'a, [u8]> {
let mut ch = self.src(s).chars();
ch.next().unwrap();
Lexer::parse_str(&mut ch, true).unwrap()
}
pub fn float<'a>(&self, s: &'a str, kind: FloatKind) -> Float<'a> {
match kind {
FloatKind::Inf { negative } => Float::Inf { negative },
FloatKind::Nan { negative } => Float::Nan {
val: None,
negative,
},
FloatKind::NanVal {
negative,
has_underscores,
} => {
let src = self.src(s);
let src = if src.starts_with("n") { src } else { &src[1..] };
let mut val = Cow::Borrowed(src.strip_prefix("nan:0x").unwrap());
if has_underscores {
*val.to_mut() = val.replace("_", "");
}
Float::Nan {
val: Some(val),
negative,
}
}
FloatKind::Normal {
has_underscores,
hex,
} => {
let src = self.src(s);
let (integral, decimal, exponent) = match src.find('.') {
Some(i) => {
let integral = &src[..i];
let rest = &src[i + 1..];
let exponent = if hex {
rest.find('p').or_else(|| rest.find('P'))
} else {
rest.find('e').or_else(|| rest.find('E'))
};
match exponent {
Some(i) => (integral, Some(&rest[..i]), Some(&rest[i + 1..])),
None => (integral, Some(rest), None),
}
}
None => {
let exponent = if hex {
src.find('p').or_else(|| src.find('P'))
} else {
src.find('e').or_else(|| src.find('E'))
};
match exponent {
Some(i) => (&src[..i], None, Some(&src[i + 1..])),
None => (src, None, None),
}
}
};
let mut integral = Cow::Borrowed(integral.strip_prefix('+').unwrap_or(integral));
let mut decimal = decimal.and_then(|s| {
if s.is_empty() {
None
} else {
Some(Cow::Borrowed(s))
}
});
let mut exponent =
exponent.map(|s| Cow::Borrowed(s.strip_prefix('+').unwrap_or(s)));
if has_underscores {
*integral.to_mut() = integral.replace("_", "");
if let Some(decimal) = &mut decimal {
*decimal.to_mut() = decimal.replace("_", "");
}
if let Some(exponent) = &mut exponent {
*exponent.to_mut() = exponent.replace("_", "");
}
}
if hex {
*integral.to_mut() = integral.replace("0x", "");
}
Float::Val {
hex,
integral,
decimal,
exponent,
}
}
}
}
pub fn integer<'a>(&self, s: &'a str, kind: IntegerKind) -> Integer<'a> {
let src = self.src(s);
let val = match kind.sign {
Some(SignToken::Plus) => src.strip_prefix('+').unwrap(),
Some(SignToken::Minus) => src,
None => src,
};
let mut val = Cow::Borrowed(val);
if kind.has_underscores {
*val.to_mut() = val.replace("_", "");
}
if kind.hex {
*val.to_mut() = val.replace("0x", "");
}
Integer {
sign: kind.sign,
hex: kind.hex,
val,
}
}
}
impl<'a> Integer<'a> {
pub fn sign(&self) -> Option<SignToken> {
self.sign
}
pub fn val(&self) -> (&str, u32) {
(&self.val, if self.hex { 16 } else { 10 })
}
}
fn to_hex(c: char) -> u8 {
match c {
'a'..='f' => c as u8 - b'a' + 10,
'A'..='F' => c as u8 - b'A' + 10,
_ => c as u8 - b'0',
}
}
impl fmt::Display for LexError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use LexError::*;
match self {
DanglingBlockComment => f.write_str("unterminated block comment")?,
Unexpected(c) => write!(f, "unexpected character '{}'", escape_char(*c))?,
InvalidStringElement(c) => {
write!(f, "invalid character in string '{}'", escape_char(*c))?
}
InvalidStringEscape(c) => write!(f, "invalid string escape '{}'", escape_char(*c))?,
InvalidHexDigit(c) => write!(f, "invalid hex digit '{}'", escape_char(*c))?,
InvalidDigit(c) => write!(f, "invalid decimal digit '{}'", escape_char(*c))?,
Expected { wanted, found } => write!(
f,
"expected '{}' but found '{}'",
escape_char(*wanted),
escape_char(*found)
)?,
UnexpectedEof => write!(f, "unexpected end-of-file")?,
NumberTooBig => f.write_str("number is too big to parse")?,
InvalidUnicodeValue(c) => write!(f, "invalid unicode scalar value 0x{:x}", c)?,
LoneUnderscore => write!(f, "bare underscore in numeric literal")?,
ConfusingUnicode(c) => write!(f, "likely-confusing unicode character found {:?}", c)?,
}
Ok(())
}
}
fn escape_char(c: char) -> String {
match c {
'\t' => String::from("\\t"),
'\r' => String::from("\\r"),
'\n' => String::from("\\n"),
'\\' => String::from("\\\\"),
'\'' => String::from("\\\'"),
'\"' => String::from("\""),
'\x20'..='\x7e' => String::from(c),
_ => c.escape_unicode().to_string(),
}
}
fn is_confusing_unicode(ch: char) -> bool {
matches!(
ch,
'\u{202a}'
| '\u{202b}'
| '\u{202d}'
| '\u{202e}'
| '\u{2066}'
| '\u{2067}'
| '\u{2068}'
| '\u{206c}'
| '\u{2069}'
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ws_smoke() {
fn get_whitespace(input: &str) -> &str {
let token = get_token(input);
match token.kind {
TokenKind::Whitespace => token.src(input),
other => panic!("unexpected {:?}", other),
}
}
assert_eq!(get_whitespace(" "), " ");
assert_eq!(get_whitespace(" "), " ");
assert_eq!(get_whitespace(" \n "), " \n ");
assert_eq!(get_whitespace(" x"), " ");
assert_eq!(get_whitespace(" ;"), " ");
}
#[test]
fn line_comment_smoke() {
fn get_line_comment(input: &str) -> &str {
let token = get_token(input);
match token.kind {
TokenKind::LineComment => token.src(input),
other => panic!("unexpected {:?}", other),
}
}
assert_eq!(get_line_comment(";;"), ";;");
assert_eq!(get_line_comment(";; xyz"), ";; xyz");
assert_eq!(get_line_comment(";; xyz\nabc"), ";; xyz");
assert_eq!(get_line_comment(";;\nabc"), ";;");
assert_eq!(get_line_comment(";; \nabc"), ";; ");
assert_eq!(get_line_comment(";; \rabc"), ";; ");
assert_eq!(get_line_comment(";; \r\nabc"), ";; ");
}
#[test]
fn block_comment_smoke() {
fn get_block_comment(input: &str) -> &str {
let token = get_token(input);
match token.kind {
TokenKind::BlockComment => token.src(input),
other => panic!("unexpected {:?}", other),
}
}
assert_eq!(get_block_comment("(;;)"), "(;;)");
assert_eq!(get_block_comment("(; ;)"), "(; ;)");
assert_eq!(get_block_comment("(; (;;) ;)"), "(; (;;) ;)");
}
fn get_token(input: &str) -> Token {
Lexer::new(input)
.parse(&mut 0)
.expect("no first token")
.expect("no token")
}
#[test]
fn lparen() {
assert_eq!(get_token("((").kind, TokenKind::LParen);
}
#[test]
fn rparen() {
assert_eq!(get_token(")(").kind, TokenKind::RParen);
}
#[test]
fn strings() {
fn get_string(input: &str) -> Vec<u8> {
let token = get_token(input);
match token.kind {
TokenKind::String => token.string(input).to_vec(),
other => panic!("not keyword {:?}", other),
}
}
assert_eq!(&*get_string("\"\""), b"");
assert_eq!(&*get_string("\"a\""), b"a");
assert_eq!(&*get_string("\"a b c d\""), b"a b c d");
assert_eq!(&*get_string("\"\\\"\""), b"\"");
assert_eq!(&*get_string("\"\\'\""), b"'");
assert_eq!(&*get_string("\"\\n\""), b"\n");
assert_eq!(&*get_string("\"\\t\""), b"\t");
assert_eq!(&*get_string("\"\\r\""), b"\r");
assert_eq!(&*get_string("\"\\\\\""), b"\\");
assert_eq!(&*get_string("\"\\01\""), &[1]);
assert_eq!(&*get_string("\"\\u{1}\""), &[1]);
assert_eq!(
&*get_string("\"\\u{0f3}\""),
'\u{0f3}'.encode_utf8(&mut [0; 4]).as_bytes()
);
assert_eq!(
&*get_string("\"\\u{0_f_3}\""),
'\u{0f3}'.encode_utf8(&mut [0; 4]).as_bytes()
);
for i in 0..=255i32 {
let s = format!("\"\\{:02x}\"", i);
assert_eq!(&*get_string(&s), &[i as u8]);
}
}
#[test]
fn id() {
fn get_id(input: &str) -> &str {
let token = get_token(input);
match token.kind {
TokenKind::Id => token.id(input),
other => panic!("not id {:?}", other),
}
}
assert_eq!(get_id("$x"), "x");
assert_eq!(get_id("$xyz"), "xyz");
assert_eq!(get_id("$x_z"), "x_z");
assert_eq!(get_id("$0^"), "0^");
assert_eq!(get_id("$0^;;"), "0^");
assert_eq!(get_id("$0^ ;;"), "0^");
}
#[test]
fn keyword() {
fn get_keyword(input: &str) -> &str {
let token = get_token(input);
match token.kind {
TokenKind::Keyword => token.keyword(input),
other => panic!("not keyword {:?}", other),
}
}
assert_eq!(get_keyword("x"), "x");
assert_eq!(get_keyword("xyz"), "xyz");
assert_eq!(get_keyword("x_z"), "x_z");
assert_eq!(get_keyword("x_z "), "x_z");
assert_eq!(get_keyword("x_z "), "x_z");
}
#[test]
fn reserved() {
fn get_reserved(input: &str) -> &str {
let token = get_token(input);
match token.kind {
TokenKind::Reserved => token.reserved(input),
other => panic!("not reserved {:?}", other),
}
}
assert_eq!(get_reserved("$ "), "$");
assert_eq!(get_reserved("^_x "), "^_x");
}
#[test]
fn integer() {
fn get_integer(input: &str) -> String {
let token = get_token(input);
match token.kind {
TokenKind::Integer(i) => token.integer(input, i).val.to_string(),
other => panic!("not integer {:?}", other),
}
}
assert_eq!(get_integer("1"), "1");
assert_eq!(get_integer("0"), "0");
assert_eq!(get_integer("-1"), "-1");
assert_eq!(get_integer("+1"), "1");
assert_eq!(get_integer("+1_000"), "1000");
assert_eq!(get_integer("+1_0_0_0"), "1000");
assert_eq!(get_integer("+0x10"), "10");
assert_eq!(get_integer("-0x10"), "-10");
assert_eq!(get_integer("0x10"), "10");
}
#[test]
fn float() {
fn get_float(input: &str) -> Float<'_> {
let token = get_token(input);
match token.kind {
TokenKind::Float(f) => token.float(input, f),
other => panic!("not float {:?}", other),
}
}
assert_eq!(
get_float("nan"),
Float::Nan {
val: None,
negative: false
},
);
assert_eq!(
get_float("-nan"),
Float::Nan {
val: None,
negative: true,
},
);
assert_eq!(
get_float("+nan"),
Float::Nan {
val: None,
negative: false,
},
);
assert_eq!(
get_float("+nan:0x1"),
Float::Nan {
val: Some("1".into()),
negative: false,
},
);
assert_eq!(
get_float("nan:0x7f_ffff"),
Float::Nan {
val: Some("7fffff".into()),
negative: false,
},
);
assert_eq!(get_float("inf"), Float::Inf { negative: false });
assert_eq!(get_float("-inf"), Float::Inf { negative: true });
assert_eq!(get_float("+inf"), Float::Inf { negative: false });
assert_eq!(
get_float("1.2"),
Float::Val {
integral: "1".into(),
decimal: Some("2".into()),
exponent: None,
hex: false,
},
);
assert_eq!(
get_float("1.2e3"),
Float::Val {
integral: "1".into(),
decimal: Some("2".into()),
exponent: Some("3".into()),
hex: false,
},
);
assert_eq!(
get_float("-1_2.1_1E+0_1"),
Float::Val {
integral: "-12".into(),
decimal: Some("11".into()),
exponent: Some("01".into()),
hex: false,
},
);
assert_eq!(
get_float("+1_2.1_1E-0_1"),
Float::Val {
integral: "12".into(),
decimal: Some("11".into()),
exponent: Some("-01".into()),
hex: false,
},
);
assert_eq!(
get_float("0x1_2.3_4p5_6"),
Float::Val {
integral: "12".into(),
decimal: Some("34".into()),
exponent: Some("56".into()),
hex: true,
},
);
assert_eq!(
get_float("+0x1_2.3_4P-5_6"),
Float::Val {
integral: "12".into(),
decimal: Some("34".into()),
exponent: Some("-56".into()),
hex: true,
},
);
assert_eq!(
get_float("1."),
Float::Val {
integral: "1".into(),
decimal: None,
exponent: None,
hex: false,
},
);
assert_eq!(
get_float("0x1p-24"),
Float::Val {
integral: "1".into(),
decimal: None,
exponent: Some("-24".into()),
hex: true,
},
);
}
}