#[derive(Debug, Clone, PartialEq)]
pub struct Token {
pub kind: TokenKind,
pub line: usize,
pub column: usize,
}
impl Token {
pub fn new(kind: TokenKind, line: usize, column: usize) -> Token {
Token { kind, line, column }
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum FStringPart {
Text(String),
Name {
name: String,
line: usize,
column: usize,
},
}
pub const RESERVED_WORDS: [&str; 16] = [
"async", "await", "case", "const", "default", "defer", "enum", "finally", "is", "loop",
"match", "pub", "struct", "until", "use", "yield",
];
pub fn reserved_word(name: &str) -> Option<&'static str> {
RESERVED_WORDS.iter().copied().find(|word| *word == name)
}
pub fn reserved_as_a_name(word: &str) -> String {
format!(
"'{word}' is a keyword and cannot be a name. \
'miru migrate -w' renames it, and reads a version 1 program to do it."
)
}
#[derive(Debug, Clone, PartialEq)]
pub enum TokenKind {
Int(i64),
Float(f64),
Str(String),
Ident(String),
Fn,
Let,
Return,
If,
Else,
While,
For,
In,
Break,
Continue,
Import,
As,
Try,
True,
False,
Nil,
Match,
Reserved(&'static str),
Plus, Minus, Star, Slash, Percent, FString(Vec<FStringPart>),
PlusAssign, MinusAssign, StarAssign, SlashAssign, PercentAssign, Assign, Eq, NotEq, Lt, Gt, LtEq, GtEq, Bang, And, Or,
LParen, RParen, LBrace, RBrace, LBracket, RBracket, Comma, Ellipsis, Colon, Dot,
Newline, Eof,
}
impl TokenKind {
pub fn reserved_name(&self) -> Option<&'static str> {
match self {
TokenKind::Reserved(word) => Some(word),
TokenKind::Match => Some("match"),
_ => None,
}
}
pub fn describe(&self) -> String {
match self {
TokenKind::Int(n) => format!("integer '{n}'"),
TokenKind::Float(n) => format!("float '{n}'"),
TokenKind::Str(s) => format!("string \"{s}\""),
TokenKind::Ident(name) => format!("identifier '{name}'"),
TokenKind::Fn => "'fn'".to_string(),
TokenKind::Let => "'let'".to_string(),
TokenKind::Return => "'return'".to_string(),
TokenKind::If => "'if'".to_string(),
TokenKind::Else => "'else'".to_string(),
TokenKind::While => "'while'".to_string(),
TokenKind::For => "'for'".to_string(),
TokenKind::In => "'in'".to_string(),
TokenKind::Break => "'break'".to_string(),
TokenKind::Continue => "'continue'".to_string(),
TokenKind::Import => "'import'".to_string(),
TokenKind::As => "'as'".to_string(),
TokenKind::Try => "'try'".to_string(),
TokenKind::True => "'true'".to_string(),
TokenKind::False => "'false'".to_string(),
TokenKind::Nil => "'nil'".to_string(),
TokenKind::Match => "'match'".to_string(),
TokenKind::Reserved(word) => format!("'{word}'"),
TokenKind::Plus => "'+'".to_string(),
TokenKind::Minus => "'-'".to_string(),
TokenKind::Star => "'*'".to_string(),
TokenKind::Slash => "'/'".to_string(),
TokenKind::Percent => "'%'".to_string(),
TokenKind::FString(_) => "an f-string".to_string(),
TokenKind::PlusAssign => "'+='".to_string(),
TokenKind::MinusAssign => "'-='".to_string(),
TokenKind::StarAssign => "'*='".to_string(),
TokenKind::SlashAssign => "'/='".to_string(),
TokenKind::PercentAssign => "'%='".to_string(),
TokenKind::Assign => "'='".to_string(),
TokenKind::Eq => "'=='".to_string(),
TokenKind::NotEq => "'!='".to_string(),
TokenKind::Lt => "'<'".to_string(),
TokenKind::Gt => "'>'".to_string(),
TokenKind::LtEq => "'<='".to_string(),
TokenKind::GtEq => "'>='".to_string(),
TokenKind::Bang => "'!'".to_string(),
TokenKind::And => "'&&'".to_string(),
TokenKind::Or => "'||'".to_string(),
TokenKind::LParen => "'('".to_string(),
TokenKind::RParen => "')'".to_string(),
TokenKind::LBrace => "'{'".to_string(),
TokenKind::RBrace => "'}'".to_string(),
TokenKind::LBracket => "'['".to_string(),
TokenKind::RBracket => "']'".to_string(),
TokenKind::Comma => "','".to_string(),
TokenKind::Ellipsis => "'...'".to_string(),
TokenKind::Colon => "':'".to_string(),
TokenKind::Dot => "'.'".to_string(),
TokenKind::Newline => "end of line".to_string(),
TokenKind::Eof => "end of input".to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_reserved_word_is_also_a_builtin() {
let collisions: Vec<&str> = RESERVED_WORDS
.iter()
.copied()
.filter(|word| crate::builtins::BUILTIN_NAMES.contains(word))
.collect();
assert!(
collisions.is_empty(),
"reserving {collisions:?} would delete a builtin of the same name"
);
}
#[test]
fn no_reserved_word_ends_in_an_underscore() {
for word in RESERVED_WORDS {
assert!(!word.ends_with('_'), "{word} ends in an underscore");
}
}
#[test]
fn the_reserved_words_are_sorted_and_distinct() {
let mut sorted = RESERVED_WORDS;
sorted.sort_unstable();
assert_eq!(sorted, RESERVED_WORDS, "the list is not in order");
let mut seen = std::collections::HashSet::new();
for word in RESERVED_WORDS {
assert!(seen.insert(word), "{word} appears twice");
}
}
#[test]
fn no_reserved_word_lexes_as_a_name() {
for word in RESERVED_WORDS {
assert!(
reserved_word(word).is_some(),
"{word} is not in its own list"
);
let tokens = crate::lexer::Lexer::tokenize(&format!("{word}\n")).expect("lexes");
assert!(
!matches!(tokens[0].kind, TokenKind::Ident(_)),
"{word} still lexes as a name: {:?}",
tokens[0].kind
);
}
}
#[test]
fn a_reserved_word_with_a_grammar_gets_a_token_of_its_own() {
let tokens = crate::lexer::Lexer::tokenize("match\n").expect("lexes");
assert_eq!(tokens[0].kind, TokenKind::Match);
for word in RESERVED_WORDS.iter().filter(|w| **w != "match") {
let tokens = crate::lexer::Lexer::tokenize(&format!("{word}\n")).expect("lexes");
assert_eq!(
tokens[0].kind,
TokenKind::Reserved(word),
"{word} has no grammar, so it should share the reserved variant"
);
}
}
#[test]
fn the_version_1_lexer_reads_every_reserved_word_as_a_name() {
for word in RESERVED_WORDS {
let (tokens, _) =
crate::lexer::Lexer::tokenize_1x_with_spans(&format!("{word}\n")).expect("lexes");
assert_eq!(
tokens[0].kind,
TokenKind::Ident(word.to_string()),
"{word} is not readable as a name by the version 1 lexer"
);
}
}
}