updated compiler to support multiple frontends and backends
This commit is contained in:
@@ -0,0 +1,627 @@
|
||||
use std::iter::Peekable;
|
||||
use std::str::Chars;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum Token {
|
||||
// Keywords
|
||||
Fn,
|
||||
Let,
|
||||
If,
|
||||
Else,
|
||||
Loop,
|
||||
While,
|
||||
Break,
|
||||
Return,
|
||||
Continue,
|
||||
Include,
|
||||
Static,
|
||||
Const,
|
||||
|
||||
// Identifiers and literals
|
||||
Identifier(Name),
|
||||
String(String),
|
||||
Integer(u64),
|
||||
Char(char),
|
||||
|
||||
// Symbols
|
||||
LeftParen, // (
|
||||
RightParen, // )
|
||||
LeftBrace, // {
|
||||
RightBrace, // }
|
||||
Semicolon, // ;
|
||||
Colon, // :
|
||||
Comma, // ,
|
||||
|
||||
// Operators
|
||||
Plus, // +
|
||||
Minus, // -
|
||||
Star, // *
|
||||
Amphersand, // &
|
||||
Slash, // /
|
||||
Assign, // =
|
||||
EqualEqual, // ==
|
||||
Bang, // !
|
||||
BangEqual, // !=
|
||||
Less, // <
|
||||
LessEqual, // <=
|
||||
Greater, // >
|
||||
GreaterEqual, // >=
|
||||
RightArrow, // ->
|
||||
|
||||
// Special
|
||||
Eof,
|
||||
}
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::model::Name;
|
||||
|
||||
impl fmt::Display for Name {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if let Some(ref ns) = self.namespace {
|
||||
write!(f, "{}::{}", ns, self.name)
|
||||
} else {
|
||||
write!(f, "{}", self.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Token {
|
||||
pub fn tt(&self) -> &str {
|
||||
match self {
|
||||
Token::Const => "Const",
|
||||
Token::Static => "Static",
|
||||
Token::Include => "Include",
|
||||
Token::Fn => "Fn",
|
||||
Token::If => "If",
|
||||
Token::Let => "Let",
|
||||
Token::Else => "Else",
|
||||
Token::Loop => "Loop",
|
||||
Token::While => "While",
|
||||
Token::Break => "Break",
|
||||
Token::Return => "Return",
|
||||
Token::Continue => "Continue",
|
||||
Token::Identifier(_) => "Identifier",
|
||||
Token::String(_) => "String",
|
||||
Token::Integer(_) => "UnsignedInt",
|
||||
Token::Char(_) => "Char",
|
||||
Token::LeftParen => "LeftParen",
|
||||
Token::RightParen => "RightParen",
|
||||
Token::LeftBrace => "LeftBrace",
|
||||
Token::RightBrace => "RightBrace",
|
||||
Token::Semicolon => "Semicolon",
|
||||
Token::Colon => "Colon",
|
||||
Token::Comma => "Comma",
|
||||
Token::RightArrow => "RightArrow",
|
||||
Token::Plus => "Plus",
|
||||
Token::Minus => "Minus",
|
||||
Token::Star => "Star",
|
||||
Token::Amphersand => "Amphersand",
|
||||
Token::Slash => "Slash",
|
||||
Token::Assign => "Assign",
|
||||
Token::EqualEqual => "EqualEqual",
|
||||
Token::Bang => "Bang",
|
||||
Token::BangEqual => "BangEqual",
|
||||
Token::Less => "Less",
|
||||
Token::LessEqual => "LessEqual",
|
||||
Token::Greater => "Greater",
|
||||
Token::GreaterEqual => "GreaterEqual",
|
||||
Token::Eof => "Eof",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Lexer<'a> {
|
||||
chars: Peekable<Chars<'a>>,
|
||||
current: Option<char>,
|
||||
line: usize,
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub fn new(input: &'a str) -> Self {
|
||||
let mut chars = input.chars().peekable();
|
||||
let current = chars.next();
|
||||
|
||||
Lexer {
|
||||
chars,
|
||||
current,
|
||||
line: 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&mut self) -> Option<char> {
|
||||
self.current = self.chars.next();
|
||||
self.current
|
||||
}
|
||||
|
||||
fn peek(&mut self) -> Option<&char> {
|
||||
self.chars.peek()
|
||||
}
|
||||
|
||||
fn skip_whitespace(&mut self) {
|
||||
while let Some(c) = self.current {
|
||||
if !c.is_whitespace() {
|
||||
break;
|
||||
}
|
||||
if c == '\n' {
|
||||
self.line += 1;
|
||||
}
|
||||
self.advance();
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_line_comment(&mut self) {
|
||||
// Skip the two slashes
|
||||
self.advance(); // first /
|
||||
self.advance(); // second /
|
||||
|
||||
// Skip until newline or EOF
|
||||
while let Some(c) = self.current {
|
||||
if c == '\n' {
|
||||
self.line += 1;
|
||||
self.advance();
|
||||
break;
|
||||
}
|
||||
self.advance();
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_block_comment(&mut self) -> Result<(), String> {
|
||||
// Skip the /*
|
||||
self.advance(); // /
|
||||
self.advance(); // *
|
||||
|
||||
let start_line = self.line;
|
||||
|
||||
// Look for */
|
||||
while let Some(c) = self.current {
|
||||
if c == '\n' {
|
||||
self.line += 1;
|
||||
}
|
||||
|
||||
if c == '*' {
|
||||
if let Some(&next) = self.peek() {
|
||||
if next == '/' {
|
||||
self.advance(); // *
|
||||
self.advance(); // /
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.advance();
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"Unterminated block comment starting at line {}",
|
||||
start_line
|
||||
))
|
||||
}
|
||||
|
||||
fn skip_whitespace_and_comments(&mut self) {
|
||||
loop {
|
||||
self.skip_whitespace();
|
||||
|
||||
// Check for comments
|
||||
if let Some('/') = self.current {
|
||||
if let Some(&next) = self.peek() {
|
||||
match next {
|
||||
'/' => {
|
||||
self.skip_line_comment();
|
||||
continue;
|
||||
}
|
||||
'*' => {
|
||||
if let Err(e) = self.skip_block_comment() {
|
||||
eprintln!("Lexer error: {}", e);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fn read_identifier(&mut self) -> String {
|
||||
let mut ident = String::new();
|
||||
|
||||
// Include the current character if it's valid
|
||||
if let Some(c) = self.current {
|
||||
if c.is_alphabetic() || c == '_' {
|
||||
ident.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
// Read remaining characters
|
||||
while let Some(&c) = self.peek() {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
self.advance();
|
||||
ident.push(c);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ident
|
||||
}
|
||||
|
||||
fn keyword_or_identifier(&mut self) -> Token {
|
||||
let first_ident = self.read_identifier();
|
||||
|
||||
// Check if it's a keyword first (keywords can't have namespaces)
|
||||
let keyword = match first_ident.as_str() {
|
||||
"fn" => Some(Token::Fn),
|
||||
"if" => Some(Token::If),
|
||||
"else" => Some(Token::Else),
|
||||
"while" => Some(Token::While),
|
||||
"loop" => Some(Token::Loop),
|
||||
"break" => Some(Token::Break),
|
||||
"return" => Some(Token::Return),
|
||||
"continue" => Some(Token::Continue),
|
||||
"include" => Some(Token::Include),
|
||||
"let" => Some(Token::Let),
|
||||
"const" => Some(Token::Const),
|
||||
"static" => Some(Token::Static),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(kw) = keyword {
|
||||
return kw;
|
||||
}
|
||||
|
||||
// Not a keyword - check for namespace separator (::)
|
||||
// We need to peek TWO characters ahead without consuming anything
|
||||
if let Some(&':') = self.peek() {
|
||||
// We see one colon, but we need to check if there's another one after it
|
||||
// We can't peek two ahead directly, so we need a different approach
|
||||
|
||||
// Save the current position by using a temporary peekable iterator
|
||||
// Actually, we can't do that easily. Instead, let's just check:
|
||||
// If we see ':', temporarily advance and check the next char
|
||||
|
||||
// Create a temporary check
|
||||
let mut temp_chars = self.chars.clone();
|
||||
let _ = temp_chars.next(); // This is the ':' we already saw
|
||||
let second_peek = temp_chars.peek();
|
||||
|
||||
if let Some(&':') = second_peek {
|
||||
// It's :: - consume both colons
|
||||
self.advance(); // consume first :
|
||||
self.advance(); // consume second :
|
||||
|
||||
// Read the second identifier (the actual name)
|
||||
let second_ident = self.read_identifier();
|
||||
|
||||
// Return namespaced identifier
|
||||
return Token::Identifier(Name {
|
||||
namespace: Some(first_ident),
|
||||
name: second_ident,
|
||||
});
|
||||
}
|
||||
// else: It's a single colon (type annotation) - DON'T consume it
|
||||
// Just fall through and return the identifier
|
||||
}
|
||||
|
||||
// No namespace separator - just a regular identifier
|
||||
Token::Identifier(Name {
|
||||
namespace: None,
|
||||
name: first_ident,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_number(&mut self) -> Result<u64, String> {
|
||||
let current = self.current.unwrap();
|
||||
|
||||
// Check for hex (0x) or binary (0b) prefix
|
||||
if current == '0' {
|
||||
if let Some(&next_char) = self.peek() {
|
||||
match next_char {
|
||||
'x' | 'X' => {
|
||||
self.advance(); // consume '0'
|
||||
self.advance(); // consume 'x'
|
||||
return self.read_hex_number();
|
||||
}
|
||||
'b' | 'B' => {
|
||||
self.advance(); // consume '0'
|
||||
self.advance(); // consume 'b'
|
||||
return self.read_binary_number();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Read decimal number
|
||||
self.read_decimal_number()
|
||||
}
|
||||
|
||||
fn read_decimal_number(&mut self) -> Result<u64, String> {
|
||||
let mut num_str = String::new();
|
||||
|
||||
if let Some(c) = self.current {
|
||||
num_str.push(c);
|
||||
}
|
||||
|
||||
while let Some(&c) = self.peek() {
|
||||
if c.is_ascii_digit() {
|
||||
self.advance();
|
||||
num_str.push(c);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
num_str
|
||||
.parse::<u64>()
|
||||
.map_err(|_| format!("Invalid decimal number: {}", num_str))
|
||||
}
|
||||
|
||||
fn read_hex_number(&mut self) -> Result<u64, String> {
|
||||
let mut num_str = String::new();
|
||||
|
||||
// Read current character if it's a hex digit
|
||||
if let Some(c) = self.current {
|
||||
if c.is_ascii_hexdigit() {
|
||||
num_str.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(&c) = self.peek() {
|
||||
if c.is_ascii_hexdigit() {
|
||||
self.advance();
|
||||
num_str.push(c);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if num_str.is_empty() {
|
||||
return Err("Invalid hexadecimal number: no digits after 0x".to_string());
|
||||
}
|
||||
|
||||
u64::from_str_radix(&num_str, 16)
|
||||
.map_err(|_| format!("Invalid hexadecimal number: {}", num_str))
|
||||
}
|
||||
|
||||
fn read_binary_number(&mut self) -> Result<u64, String> {
|
||||
let mut num_str = String::new();
|
||||
|
||||
// Read current character if it's a binary digit
|
||||
if let Some(c) = self.current {
|
||||
if c == '0' || c == '1' {
|
||||
num_str.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(&c) = self.peek() {
|
||||
if c == '0' || c == '1' {
|
||||
self.advance();
|
||||
num_str.push(c);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if num_str.is_empty() {
|
||||
return Err("Invalid binary number: no digits after 0b".to_string());
|
||||
}
|
||||
|
||||
u64::from_str_radix(&num_str, 2)
|
||||
.map_err(|_| format!("Invalid binary number: {}", num_str))
|
||||
}
|
||||
|
||||
fn read_string(&mut self) -> Result<String, String> {
|
||||
self.advance(); // Skip the opening quote
|
||||
let mut s = String::new();
|
||||
|
||||
while let Some(c) = self.current {
|
||||
if c == '"' {
|
||||
return Ok(s);
|
||||
}
|
||||
|
||||
// Handle escape sequences
|
||||
if c == '\\' {
|
||||
self.advance();
|
||||
if let Some(escaped) = self.current {
|
||||
let escaped_char = match escaped {
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
'r' => '\r',
|
||||
'\\' => '\\',
|
||||
'"' => '"',
|
||||
_ => escaped, // For now, just use the character as-is
|
||||
};
|
||||
s.push(escaped_char);
|
||||
} else {
|
||||
return Err("Unexpected end of string after escape".to_string());
|
||||
}
|
||||
} else {
|
||||
s.push(c);
|
||||
}
|
||||
|
||||
self.advance();
|
||||
}
|
||||
|
||||
Err("Unterminated string literal".to_string())
|
||||
}
|
||||
|
||||
fn match_next(&mut self, expected: char) -> bool {
|
||||
match self.peek() {
|
||||
Some(&c) if c == expected => {
|
||||
self.advance();
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_single_char_token(&mut self, c: char) -> Option<Token> {
|
||||
match c {
|
||||
'(' => Some(Token::LeftParen),
|
||||
')' => Some(Token::RightParen),
|
||||
'{' => Some(Token::LeftBrace),
|
||||
'}' => Some(Token::RightBrace),
|
||||
';' => Some(Token::Semicolon),
|
||||
',' => Some(Token::Comma),
|
||||
'&' => Some(Token::Amphersand),
|
||||
'+' => Some(Token::Plus),
|
||||
'*' => Some(Token::Star),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_operator(&mut self, c: char) -> Option<Token> {
|
||||
match c {
|
||||
'-' => Some(if self.match_next('>') {
|
||||
Token::RightArrow
|
||||
} else {
|
||||
Token::Minus
|
||||
}),
|
||||
'!' => Some(if self.match_next('=') {
|
||||
Token::BangEqual
|
||||
} else {
|
||||
Token::Bang
|
||||
}),
|
||||
'=' => Some(if self.match_next('=') {
|
||||
Token::EqualEqual
|
||||
} else {
|
||||
Token::Assign
|
||||
}),
|
||||
'<' => Some(if self.match_next('=') {
|
||||
Token::LessEqual
|
||||
} else {
|
||||
Token::Less
|
||||
}),
|
||||
'>' => Some(if self.match_next('=') {
|
||||
Token::GreaterEqual
|
||||
} else {
|
||||
Token::Greater
|
||||
}),
|
||||
':' => {
|
||||
// Single colon (for type annotations)
|
||||
// Note: :: is handled in keyword_or_identifier for namespaces
|
||||
Some(Token::Colon)
|
||||
}
|
||||
'/' => {
|
||||
// Check if it's a comment or division
|
||||
if let Some(&next) = self.peek() {
|
||||
if next == '/' || next == '*' {
|
||||
// It's a comment, don't consume it here
|
||||
// Let skip_whitespace_and_comments handle it
|
||||
None
|
||||
} else {
|
||||
Some(Token::Slash)
|
||||
}
|
||||
} else {
|
||||
Some(Token::Slash)
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_token(&mut self) -> Token {
|
||||
self.skip_whitespace_and_comments();
|
||||
|
||||
let Some(c) = self.current else {
|
||||
return Token::Eof;
|
||||
};
|
||||
|
||||
// Try single-character tokens first
|
||||
if let Some(token) = self.scan_single_char_token(c) {
|
||||
self.advance();
|
||||
return token;
|
||||
}
|
||||
|
||||
// Try operators (may be multi-character)
|
||||
if let Some(token) = self.scan_operator(c) {
|
||||
self.advance();
|
||||
return token;
|
||||
}
|
||||
|
||||
// Char literals
|
||||
if c == '\'' {
|
||||
let mut value = ' ';
|
||||
self.advance();
|
||||
if let Some(ch) = self.current {
|
||||
value = ch;
|
||||
self.advance();
|
||||
}
|
||||
if self.current == Some('\'') {
|
||||
self.advance();
|
||||
return Token::Char(value);
|
||||
}
|
||||
eprintln!("Lexer error on line {}: Invalid char literal", self.line);
|
||||
}
|
||||
|
||||
// String literals
|
||||
if c == '"' {
|
||||
let token = match self.read_string() {
|
||||
Ok(s) => Token::String(s),
|
||||
Err(e) => {
|
||||
eprintln!("Lexer error on line {}: {}", self.line, e);
|
||||
// Skip to next quote or end
|
||||
while let Some(ch) = self.current {
|
||||
if ch == '"' || ch == '\n' {
|
||||
break;
|
||||
}
|
||||
self.advance();
|
||||
}
|
||||
Token::String(String::new())
|
||||
}
|
||||
};
|
||||
self.advance();
|
||||
return token;
|
||||
}
|
||||
|
||||
// Identifiers and keywords (including namespaced identifiers)
|
||||
if c.is_alphabetic() || c == '_' {
|
||||
let token = self.keyword_or_identifier();
|
||||
self.advance();
|
||||
return token;
|
||||
}
|
||||
|
||||
// Numbers (decimal, hex, binary)
|
||||
if c.is_ascii_digit() {
|
||||
let token = match self.read_number() {
|
||||
Ok(num) => Token::Integer(num),
|
||||
Err(e) => {
|
||||
eprintln!("Lexer error on line {}: {}", self.line, e);
|
||||
// Skip invalid number
|
||||
while let Some(&ch) = self.peek() {
|
||||
if !ch.is_alphanumeric() {
|
||||
break;
|
||||
}
|
||||
self.advance();
|
||||
}
|
||||
Token::Integer(0)
|
||||
}
|
||||
};
|
||||
self.advance();
|
||||
return token;
|
||||
}
|
||||
|
||||
// Unknown character - skip it
|
||||
eprintln!(
|
||||
"Lexer warning on line {}: Skipping unknown character '{}'",
|
||||
self.line, c
|
||||
);
|
||||
self.advance();
|
||||
self.next_token()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Lexer<'a> {
|
||||
type Item = Token;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.next_token() {
|
||||
Token::Eof => None,
|
||||
token => Some(token),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user