1
0
dust/dust-lang/src/compiler.rs

2252 lines
73 KiB
Rust
Raw Normal View History

2024-11-06 20:40:37 +00:00
//! Compilation tools and errors
2024-11-06 00:38:26 +00:00
//!
2024-11-06 20:40:37 +00:00
//! This module provides two compilation options:
//! - [`compile`], which compiles the entire input and returns a chunk
//! - [`Compiler`], which compiles the input a token at a time while assembling a chunk
use std::{
fmt::{self, Display, Formatter},
2024-10-19 07:06:14 +00:00
mem::replace,
num::{ParseFloatError, ParseIntError},
vec,
};
2024-09-07 03:30:43 +00:00
2024-09-25 05:27:10 +00:00
use colored::Colorize;
2024-09-07 03:30:43 +00:00
use crate::{
2024-11-16 02:42:27 +00:00
value::ConcreteValue, AnnotatedError, Chunk, ChunkError, DustError, FunctionType, Instruction,
2024-11-11 00:28:21 +00:00
LexError, Lexer, Local, NativeFunction, Operation, Optimizer, Scope, Span, Token, TokenKind,
TokenOwned, Type, TypeConflict,
2024-09-07 03:30:43 +00:00
};
2024-11-06 20:40:37 +00:00
/// Compiles the input and returns a chunk.
2024-11-06 00:38:26 +00:00
///
/// # Example
///
/// ```
2024-11-06 20:40:37 +00:00
/// # use dust_lang::compile;
2024-11-06 00:38:26 +00:00
/// let source = "40 + 2 == 42";
2024-11-06 20:40:37 +00:00
/// let chunk = compile(source).unwrap();
2024-11-06 00:38:26 +00:00
///
/// assert_eq!(chunk.len(), 6);
/// ```
2024-11-06 20:40:37 +00:00
pub fn compile(source: &str) -> Result<Chunk, DustError> {
let lexer = Lexer::new(source);
2024-11-06 20:40:37 +00:00
let mut compiler =
Compiler::new(lexer).map_err(|error| DustError::Compile { error, source })?;
2024-11-06 20:40:37 +00:00
compiler
.parse_top_level()
2024-11-06 20:40:37 +00:00
.map_err(|error| DustError::Compile { error, source })?;
Ok(compiler.finish())
}
2024-11-06 20:40:37 +00:00
/// Low-level tool for compiling the input a token at a time while assembling a chunk.
2024-11-06 00:38:26 +00:00
///
2024-11-06 20:40:37 +00:00
/// See the [`compile`] function an example of how to create and use a Compiler.
2024-11-16 00:18:00 +00:00
#[derive(Debug, Eq, PartialEq, PartialOrd)]
2024-11-06 20:40:37 +00:00
pub struct Compiler<'src> {
chunk: Chunk,
2024-11-06 18:09:29 +00:00
lexer: Lexer<'src>,
2024-09-07 10:38:12 +00:00
current_token: Token<'src>,
2024-09-07 03:30:43 +00:00
current_position: Span,
previous_token: Token<'src>,
previous_position: Span,
2024-11-11 00:28:21 +00:00
return_type: Option<Type>,
local_definitions: Vec<u8>,
optimization_count: usize,
previous_expression_type: Type,
minimum_register: u8,
2024-11-11 00:28:21 +00:00
block_index: u8,
current_scope: Scope,
2024-09-07 03:30:43 +00:00
}
2024-11-06 20:40:37 +00:00
impl<'src> Compiler<'src> {
pub fn new(mut lexer: Lexer<'src>) -> Result<Self, CompileError> {
let (current_token, current_position) = lexer.next_token()?;
2024-11-06 18:09:29 +00:00
let chunk = Chunk::new(None);
2024-09-07 10:38:12 +00:00
2024-09-25 05:27:10 +00:00
log::info!(
"Begin chunk with {} at {}",
2024-09-25 05:27:10 +00:00
current_token.to_string().bold(),
current_position.to_string()
);
2024-09-07 16:15:47 +00:00
2024-11-06 20:40:37 +00:00
Ok(Compiler {
2024-11-06 18:09:29 +00:00
chunk,
2024-09-07 03:30:43 +00:00
lexer,
2024-09-07 10:38:12 +00:00
current_token,
current_position,
previous_token: Token::Eof,
previous_position: Span(0, 0),
return_type: None,
local_definitions: Vec::new(),
optimization_count: 0,
previous_expression_type: Type::None,
minimum_register: 0,
2024-11-11 00:28:21 +00:00
block_index: 0,
current_scope: Scope::default(),
})
}
pub fn finish(mut self) -> Chunk {
2024-11-06 20:40:37 +00:00
log::info!("End chunk with {} optimizations", self.optimization_count);
2024-10-09 02:56:01 +00:00
if let Type::None = *self.chunk.r#type().return_type {
self.chunk.set_type(FunctionType {
type_parameters: None,
value_parameters: None,
return_type: self
.return_type
.map_or_else(|| Box::new(Type::None), Box::new),
});
}
2024-11-16 10:16:51 +00:00
self.chunk
2024-09-07 03:30:43 +00:00
}
fn is_eof(&self) -> bool {
2024-09-07 10:38:12 +00:00
matches!(self.current_token, Token::Eof)
2024-09-07 03:30:43 +00:00
}
fn next_register(&mut self) -> u8 {
self.chunk
2024-10-25 02:37:18 +00:00
.instructions()
.iter()
.rev()
.find_map(|(instruction, _)| {
if instruction.yields_value() {
let previous = instruction.a();
let next = previous.overflowing_add(1).0;
Some(next)
} else {
None
}
})
.unwrap_or(self.minimum_register)
}
2024-11-06 20:40:37 +00:00
fn advance(&mut self) -> Result<(), CompileError> {
2024-09-10 02:57:14 +00:00
if self.is_eof() {
return Ok(());
}
2024-09-07 10:38:12 +00:00
let (new_token, position) = self.lexer.next_token()?;
2024-09-07 03:30:43 +00:00
2024-09-25 05:27:10 +00:00
log::info!(
2024-10-09 16:16:46 +00:00
"Parsing {} at {}",
2024-09-25 05:27:10 +00:00
new_token.to_string().bold(),
position.to_string()
);
self.previous_token = replace(&mut self.current_token, new_token);
self.previous_position = replace(&mut self.current_position, position);
2024-09-07 03:30:43 +00:00
Ok(())
}
2024-11-06 20:40:37 +00:00
fn get_local(&self, index: u8) -> Result<&Local, CompileError> {
self.chunk
2024-11-06 18:50:49 +00:00
.get_local(index)
2024-11-06 20:40:37 +00:00
.map_err(|error| CompileError::Chunk {
2024-11-06 18:50:49 +00:00
error,
position: self.current_position,
})
}
2024-11-06 20:40:37 +00:00
fn get_local_index(&self, identifier_text: &str) -> Result<u8, CompileError> {
self.chunk
.locals()
.iter()
.enumerate()
.rev()
.find_map(|(index, local)| {
2024-11-11 00:28:21 +00:00
let constant = self
.chunk
.constants()
2024-11-11 00:28:21 +00:00
.get(local.identifier_index as usize)?;
2024-11-16 02:42:27 +00:00
let identifier = if let ConcreteValue::String(identifier) = constant {
2024-11-11 00:28:21 +00:00
identifier
} else {
return None;
};
if identifier == identifier_text {
Some(index as u8)
} else {
None
}
})
2024-11-06 20:40:37 +00:00
.ok_or(CompileError::UndeclaredVariable {
identifier: identifier_text.to_string(),
position: self.current_position,
})
}
fn declare_local(
&mut self,
identifier: &str,
r#type: Type,
is_mutable: bool,
scope: Scope,
register_index: u8,
) -> (u8, u8) {
log::debug!("Declare local {identifier}");
2024-11-16 02:42:27 +00:00
let identifier = ConcreteValue::string(identifier);
let identifier_index = self.chunk.push_or_get_constant(identifier);
2024-11-16 10:16:51 +00:00
let local_index = self.chunk.locals().len() as u8;
self.chunk
.locals_mut()
.push(Local::new(identifier_index, r#type, is_mutable, scope));
self.local_definitions.push(register_index);
2024-11-16 10:16:51 +00:00
(local_index, identifier_index)
}
2024-11-06 20:40:37 +00:00
fn allow(&mut self, allowed: Token) -> Result<bool, CompileError> {
if self.current_token == allowed {
2024-09-07 16:15:47 +00:00
self.advance()?;
Ok(true)
} else {
Ok(false)
}
}
2024-11-06 20:40:37 +00:00
fn expect(&mut self, expected: Token) -> Result<(), CompileError> {
if self.current_token == expected {
2024-09-07 03:30:43 +00:00
self.advance()
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: expected.kind(),
2024-09-07 10:38:12 +00:00
found: self.current_token.to_owned(),
2024-09-07 03:30:43 +00:00
position: self.current_position,
})
}
}
2024-11-06 20:40:37 +00:00
fn pop_last_instruction(&mut self) -> Result<(Instruction, Span), CompileError> {
2024-11-05 21:25:55 +00:00
self.chunk
.instructions_mut()
.pop()
2024-11-06 20:40:37 +00:00
.ok_or_else(|| CompileError::ExpectedExpression {
2024-11-05 21:25:55 +00:00
found: self.previous_token.to_owned(),
position: self.previous_position,
})
}
fn get_last_operations<const COUNT: usize>(&self) -> Option<[Operation; COUNT]> {
let mut n_operations = [Operation::Return; COUNT];
for (nth, operation) in n_operations.iter_mut().rev().zip(
self.chunk
.instructions()
.iter()
.rev()
.map(|(instruction, _)| instruction.operation()),
) {
*nth = operation;
}
Some(n_operations)
}
2024-11-16 10:40:31 +00:00
fn get_last_jumpable_mut_between(
&mut self,
minimum: usize,
maximum: usize,
) -> Option<&mut Instruction> {
2024-10-30 18:48:30 +00:00
self.chunk
.instructions_mut()
.iter_mut()
.rev()
2024-11-16 10:40:31 +00:00
.skip(minimum)
.take(maximum)
2024-10-30 18:48:30 +00:00
.find_map(|(instruction, _)| {
if let Operation::LoadBoolean | Operation::LoadConstant = instruction.operation() {
Some(instruction)
} else {
None
}
})
}
pub fn get_instruction_type(&self, instruction: &Instruction) -> Result<Type, CompileError> {
use Operation::*;
match instruction.operation() {
Add | Divide | Modulo | Multiply | Subtract => {
if instruction.b_is_constant() {
self.chunk
.get_constant_type(instruction.b())
.map_err(|error| CompileError::Chunk {
error,
position: self.current_position,
})
} else {
self.get_register_type(instruction.b())
}
}
LoadBoolean | Not => Ok(Type::Boolean),
Negate => {
if instruction.b_is_constant() {
self.chunk
.get_constant_type(instruction.b())
.map_err(|error| CompileError::Chunk {
error,
position: self.current_position,
})
} else {
self.get_register_type(instruction.b())
}
}
LoadConstant => self
.chunk
.get_constant_type(instruction.b())
.map_err(|error| CompileError::Chunk {
error,
position: self.current_position,
}),
LoadList => self.get_register_type(instruction.a()),
LoadSelf => Ok(Type::SelfChunk),
GetLocal => self
.chunk
.get_local_type(instruction.b())
.cloned()
.map_err(|error| CompileError::Chunk {
error,
position: self.current_position,
}),
Call => {
let function_register = instruction.b();
let function_type = self.get_register_type(function_register)?;
match function_type {
Type::Function(FunctionType { return_type, .. }) => Ok(*return_type),
Type::SelfChunk => {
let return_type = self
.return_type
.as_ref()
.unwrap_or_else(|| &self.chunk.r#type().return_type);
Ok(return_type.clone())
}
_ => Err(CompileError::ExpectedFunctionType {
found: function_type,
position: self.current_position,
}),
}
}
CallNative => {
let native_function = NativeFunction::from(instruction.b());
Ok(*native_function.r#type().return_type)
}
_ => Ok(Type::None),
}
}
pub fn get_register_type(&self, register_index: u8) -> Result<Type, CompileError> {
for (index, (instruction, _)) in self.chunk.instructions().iter().enumerate() {
2024-11-11 00:28:21 +00:00
if instruction.a() == register_index {
if let Operation::LoadList = instruction.operation() {
let mut length = (instruction.c() - instruction.b() + 1) as usize;
let mut item_type = Type::Any;
let distance_to_end = self.chunk.len() - index;
for (instruction, _) in self
.chunk
.instructions()
.iter()
.rev()
.skip(distance_to_end)
.take(length)
{
if let Operation::Close = instruction.operation() {
length -= (instruction.c() - instruction.b()) as usize;
} else if let Type::Any = item_type {
item_type = self.get_instruction_type(instruction)?;
}
}
return Ok(Type::List {
item_type: Box::new(item_type),
length,
});
}
2024-11-11 00:28:21 +00:00
if let Operation::LoadSelf = instruction.operation() {
return Ok(Type::SelfChunk);
}
if instruction.yields_value() {
return self.get_instruction_type(instruction);
}
}
}
Err(CompileError::CannotResolveRegisterType {
register_index: register_index as usize,
position: self.current_position,
})
}
/// Updates [Self::return_type] with the given [Type].
///
/// If [Self::return_type] is already set, it will check if the given [Type] is compatible with
/// it and set it to the least restrictive of the two.
fn update_return_type(&mut self, new_return_type: Type) -> Result<(), CompileError> {
if let Some(return_type) = &self.return_type {
return_type.check(&new_return_type).map_err(|conflict| {
CompileError::ReturnTypeConflict {
conflict,
position: self.current_position,
}
})?;
if *return_type != Type::Any {
self.return_type = Some(new_return_type);
};
} else {
self.return_type = Some(new_return_type);
}
Ok(())
}
2024-11-11 00:28:21 +00:00
fn emit_instruction(&mut self, instruction: Instruction, position: Span) {
log::debug!(
"Emitting {} at {}",
instruction.operation().to_string().bold(),
position.to_string()
);
self.chunk.instructions_mut().push((instruction, position));
}
2024-11-16 02:42:27 +00:00
fn emit_constant(
&mut self,
constant: ConcreteValue,
position: Span,
) -> Result<(), CompileError> {
2024-11-11 00:28:21 +00:00
let constant_index = self.chunk.push_or_get_constant(constant);
let register = self.next_register();
self.emit_instruction(
Instruction::load_constant(register, constant_index, false),
position,
);
2024-09-07 03:30:43 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_boolean(&mut self) -> Result<(), CompileError> {
2024-09-23 10:42:41 +00:00
let position = self.current_position;
2024-09-17 21:23:37 +00:00
if let Token::Boolean(text) = self.current_token {
self.advance()?;
2024-09-23 10:42:41 +00:00
let boolean = text.parse::<bool>().unwrap();
2024-10-25 02:37:18 +00:00
let register = self.next_register();
self.emit_instruction(
Instruction::load_boolean(register, boolean, false),
position,
);
self.previous_expression_type = Type::Boolean;
Ok(())
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: TokenKind::Boolean,
found: self.current_token.to_owned(),
position,
})
}
2024-09-07 10:38:12 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_byte(&mut self) -> Result<(), CompileError> {
let position = self.current_position;
2024-09-17 21:23:37 +00:00
if let Token::Byte(text) = self.current_token {
self.advance()?;
let byte = u8::from_str_radix(&text[2..], 16)
2024-11-06 20:40:37 +00:00
.map_err(|error| CompileError::ParseIntError { error, position })?;
2024-11-16 06:29:21 +00:00
let value = ConcreteValue::Byte(byte);
2024-09-10 03:45:06 +00:00
self.emit_constant(value, position)?;
2024-09-10 03:45:06 +00:00
self.previous_expression_type = Type::Byte;
Ok(())
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: TokenKind::Byte,
found: self.current_token.to_owned(),
position,
})
}
2024-09-10 03:45:06 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_character(&mut self) -> Result<(), CompileError> {
let position = self.current_position;
2024-09-17 21:23:37 +00:00
if let Token::Character(character) = self.current_token {
self.advance()?;
2024-11-16 06:29:21 +00:00
let value = ConcreteValue::Character(character);
2024-09-10 03:45:06 +00:00
self.emit_constant(value, position)?;
2024-09-10 03:45:06 +00:00
self.previous_expression_type = Type::Character;
Ok(())
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: TokenKind::Character,
found: self.current_token.to_owned(),
position,
})
}
2024-09-10 03:45:06 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_float(&mut self) -> Result<(), CompileError> {
let position = self.current_position;
2024-09-17 21:23:37 +00:00
if let Token::Float(text) = self.current_token {
self.advance()?;
let float = text
.parse::<f64>()
2024-11-06 20:40:37 +00:00
.map_err(|error| CompileError::ParseFloatError {
error,
position: self.previous_position,
})?;
2024-11-16 06:29:21 +00:00
let value = ConcreteValue::Float(float);
2024-09-07 16:15:47 +00:00
self.emit_constant(value, position)?;
2024-09-07 16:15:47 +00:00
self.previous_expression_type = Type::Float;
Ok(())
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: TokenKind::Float,
found: self.current_token.to_owned(),
position,
})
}
2024-09-07 16:15:47 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_integer(&mut self) -> Result<(), CompileError> {
let position = self.current_position;
2024-09-17 21:23:37 +00:00
if let Token::Integer(text) = self.current_token {
self.advance()?;
let integer = text
.parse::<i64>()
2024-11-06 20:40:37 +00:00
.map_err(|error| CompileError::ParseIntError {
error,
position: self.previous_position,
})?;
2024-11-16 06:29:21 +00:00
let value = ConcreteValue::Integer(integer);
2024-09-07 03:30:43 +00:00
self.emit_constant(value, position)?;
self.previous_expression_type = Type::Integer;
Ok(())
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: TokenKind::Integer,
found: self.current_token.to_owned(),
position,
})
}
}
2024-11-06 20:50:05 +00:00
fn parse_string(&mut self) -> Result<(), CompileError> {
let position = self.current_position;
2024-09-17 21:23:37 +00:00
if let Token::String(text) = self.current_token {
self.advance()?;
2024-11-16 02:42:27 +00:00
let value = ConcreteValue::string(text);
2024-09-07 16:15:47 +00:00
self.emit_constant(value, position)?;
2024-09-07 16:15:47 +00:00
self.previous_expression_type = Type::String {
length: Some(text.len()),
};
Ok(())
} else {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedToken {
expected: TokenKind::String,
found: self.current_token.to_owned(),
position,
})
}
2024-09-07 16:15:47 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_grouped(&mut self) -> Result<(), CompileError> {
self.allow(Token::LeftParenthesis)?;
2024-10-12 14:55:34 +00:00
self.parse_expression()?;
self.expect(Token::RightParenthesis)?;
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_unary(&mut self) -> Result<(), CompileError> {
2024-09-17 23:35:33 +00:00
let operator = self.current_token;
let operator_position = self.current_position;
2024-09-17 21:23:37 +00:00
2024-09-17 23:35:33 +00:00
self.advance()?;
2024-10-12 14:55:34 +00:00
self.parse_expression()?;
2024-09-07 08:37:38 +00:00
2024-11-05 21:25:55 +00:00
let (previous_instruction, previous_position) = self.pop_last_instruction()?;
let (push_back, is_constant, argument) = {
match previous_instruction.operation() {
2024-09-24 20:49:17 +00:00
Operation::GetLocal => (false, false, previous_instruction.a()),
Operation::LoadConstant => (false, true, previous_instruction.a()),
Operation::LoadBoolean => (true, false, previous_instruction.a()),
Operation::Close => {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedExpression {
found: self.previous_token.to_owned(),
position: self.previous_position,
});
}
2024-09-24 20:49:17 +00:00
_ => (true, false, previous_instruction.a()),
2024-09-17 21:23:37 +00:00
}
2024-09-17 23:35:33 +00:00
};
if push_back {
self.emit_instruction(previous_instruction, previous_position);
}
let register = self.next_register();
2024-09-17 23:35:33 +00:00
let mut instruction = match operator.kind() {
TokenKind::Bang => Instruction::not(register, argument),
TokenKind::Minus => Instruction::negate(register, argument),
2024-09-17 23:35:33 +00:00
_ => {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedTokenMultiple {
2024-09-18 01:10:44 +00:00
expected: &[TokenKind::Bang, TokenKind::Minus],
2024-09-17 23:35:33 +00:00
found: operator.to_owned(),
position: operator_position,
})
}
};
if is_constant {
2024-09-24 20:49:17 +00:00
instruction.set_b_is_constant();
2024-09-17 21:23:37 +00:00
}
self.emit_instruction(instruction, operator_position);
if let TokenKind::Bang = operator.kind() {
self.previous_expression_type = Type::Boolean;
}
Ok(())
}
2024-09-23 04:55:39 +00:00
fn handle_binary_argument(
&mut self,
instruction: &Instruction,
2024-11-06 20:40:37 +00:00
) -> Result<(bool, bool, bool, u8), CompileError> {
2024-09-23 04:55:39 +00:00
let mut push_back = false;
let mut is_constant = false;
2024-10-05 08:33:38 +00:00
let mut is_mutable_local = false;
2024-09-23 04:55:39 +00:00
let argument = match instruction.operation() {
Operation::GetLocal => {
let local_index = instruction.b();
let local = self.get_local(local_index)?;
2024-10-05 08:33:38 +00:00
is_mutable_local = local.is_mutable;
*self
.local_definitions
.get(local_index as usize)
.ok_or_else(|| {
let identifier = self
.chunk
.constants()
.get(local.identifier_index as usize)
.unwrap()
.to_string();
CompileError::UndeclaredVariable {
identifier,
position: self.current_position,
}
})?
}
2024-09-23 04:55:39 +00:00
Operation::LoadConstant => {
is_constant = true;
2024-09-24 20:49:17 +00:00
instruction.b()
2024-09-23 04:55:39 +00:00
}
Operation::Close => {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedExpression {
2024-09-23 04:55:39 +00:00
found: self.previous_token.to_owned(),
position: self.previous_position,
});
}
_ => {
push_back = true;
2024-09-15 10:26:31 +00:00
if instruction.yields_value() {
instruction.a()
} else {
self.next_register()
}
2024-09-23 04:55:39 +00:00
}
};
2024-09-18 05:21:40 +00:00
2024-10-05 08:33:38 +00:00
Ok((push_back, is_constant, is_mutable_local, argument))
2024-09-23 04:55:39 +00:00
}
2024-09-17 17:24:45 +00:00
2024-11-06 20:40:37 +00:00
fn parse_math_binary(&mut self) -> Result<(), CompileError> {
2024-09-19 15:41:18 +00:00
let (left_instruction, left_position) =
2024-11-06 20:40:37 +00:00
self.chunk.instructions_mut().pop().ok_or_else(|| {
CompileError::ExpectedExpression {
found: self.previous_token.to_owned(),
position: self.previous_position,
2024-11-06 20:40:37 +00:00
}
})?;
2024-10-05 08:33:38 +00:00
let (push_back_left, left_is_constant, left_is_mutable_local, left) =
2024-09-23 04:55:39 +00:00
self.handle_binary_argument(&left_instruction)?;
if push_back_left {
self.emit_instruction(left_instruction, left_position);
}
2024-09-19 15:41:18 +00:00
let operator = self.current_token;
let operator_position = self.current_position;
let rule = ParseRule::from(&operator);
if let Token::PlusEqual | Token::MinusEqual | Token::StarEqual | Token::SlashEqual =
operator
2024-10-05 08:33:38 +00:00
{
if !left_is_mutable_local {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedMutableVariable {
2024-10-05 08:33:38 +00:00
found: self.previous_token.to_owned(),
position: left_position,
});
}
}
2024-09-24 12:29:33 +00:00
self.advance()?;
2024-10-13 11:14:12 +00:00
self.parse_sub_expression(&rule.precedence)?;
2024-09-24 12:29:33 +00:00
2024-11-05 21:25:55 +00:00
let (right_instruction, right_position) = self.pop_last_instruction()?;
let (push_back_right, right_is_constant, _, right) =
2024-10-05 08:33:38 +00:00
self.handle_binary_argument(&right_instruction)?;
if push_back_right {
self.emit_instruction(right_instruction, right_position);
}
2024-10-05 08:33:38 +00:00
let register = if left_is_mutable_local {
2024-10-05 06:07:26 +00:00
left
} else {
self.next_register()
2024-10-05 06:07:26 +00:00
};
let mut new_instruction = match operator {
Token::Plus => Instruction::add(register, left, right),
Token::PlusEqual => Instruction::add(register, left, right),
Token::Minus => Instruction::subtract(register, left, right),
Token::MinusEqual => Instruction::subtract(register, left, right),
Token::Star => Instruction::multiply(register, left, right),
Token::StarEqual => Instruction::multiply(register, left, right),
Token::Slash => Instruction::divide(register, left, right),
Token::SlashEqual => Instruction::divide(register, left, right),
Token::Percent => Instruction::modulo(register, left, right),
Token::PercentEqual => Instruction::modulo(register, left, right),
2024-09-07 03:30:43 +00:00
_ => {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedTokenMultiple {
2024-09-17 23:35:33 +00:00
expected: &[
TokenKind::Plus,
2024-10-05 08:33:38 +00:00
TokenKind::PlusEqual,
TokenKind::Minus,
2024-10-05 08:33:38 +00:00
TokenKind::MinusEqual,
TokenKind::Star,
2024-10-05 08:33:38 +00:00
TokenKind::StarEqual,
TokenKind::Slash,
2024-10-05 08:33:38 +00:00
TokenKind::SlashEqual,
2024-09-18 01:10:44 +00:00
TokenKind::Percent,
TokenKind::PercentEqual,
],
found: operator.to_owned(),
2024-09-07 10:38:12 +00:00
position: operator_position,
2024-09-07 03:30:43 +00:00
})
}
2024-09-07 08:37:38 +00:00
};
2024-09-15 08:25:24 +00:00
if left_is_constant {
2024-09-24 20:49:17 +00:00
new_instruction.set_b_is_constant();
2024-09-15 05:24:04 +00:00
}
2024-09-15 08:25:24 +00:00
if right_is_constant {
2024-09-24 20:49:17 +00:00
new_instruction.set_c_is_constant();
2024-09-15 05:24:04 +00:00
}
self.emit_instruction(new_instruction, operator_position);
2024-09-07 03:30:43 +00:00
if let Token::PlusEqual
| Token::MinusEqual
| Token::StarEqual
| Token::SlashEqual
| Token::PercentEqual = operator
{
self.previous_expression_type = Type::None;
} else {
self.previous_expression_type = self.get_instruction_type(&left_instruction)?;
}
2024-09-23 04:55:39 +00:00
Ok(())
}
2024-09-19 00:02:12 +00:00
2024-11-06 20:40:37 +00:00
fn parse_comparison_binary(&mut self) -> Result<(), CompileError> {
if let Some([Operation::Equal | Operation::Less | Operation::LessEqual, _, _, _]) =
self.get_last_operations()
2024-10-12 12:16:06 +00:00
{
2024-11-06 20:40:37 +00:00
return Err(CompileError::CannotChainComparison {
2024-10-12 12:16:06 +00:00
position: self.current_position,
});
}
2024-09-23 04:55:39 +00:00
let (left_instruction, left_position) =
2024-11-06 20:40:37 +00:00
self.chunk.instructions_mut().pop().ok_or_else(|| {
CompileError::ExpectedExpression {
found: self.previous_token.to_owned(),
position: self.previous_position,
2024-11-06 20:40:37 +00:00
}
})?;
2024-10-05 06:07:26 +00:00
let (push_back_left, left_is_constant, _, left) =
2024-09-23 04:55:39 +00:00
self.handle_binary_argument(&left_instruction)?;
2024-09-19 15:41:18 +00:00
2024-09-23 04:55:39 +00:00
let operator = self.current_token;
let operator_position = self.current_position;
let rule = ParseRule::from(&operator);
2024-10-09 16:16:46 +00:00
self.advance()?;
2024-10-13 11:14:12 +00:00
self.parse_sub_expression(&rule.precedence)?;
2024-10-09 16:16:46 +00:00
let (right_instruction, right_position) =
2024-11-06 20:40:37 +00:00
self.chunk.instructions_mut().pop().ok_or_else(|| {
CompileError::ExpectedExpression {
found: self.previous_token.to_owned(),
position: self.previous_position,
2024-11-06 20:40:37 +00:00
}
})?;
2024-10-09 16:16:46 +00:00
let (push_back_right, right_is_constant, _, right) =
self.handle_binary_argument(&right_instruction)?;
let mut instruction = match operator {
Token::DoubleEqual => Instruction::equal(true, left, right),
Token::BangEqual => Instruction::equal(false, left, right),
Token::Less => Instruction::less(true, left, right),
Token::LessEqual => Instruction::less_equal(true, left, right),
Token::Greater => Instruction::less_equal(false, left, right),
Token::GreaterEqual => Instruction::less(false, left, right),
2024-09-23 04:55:39 +00:00
_ => {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedTokenMultiple {
2024-09-23 04:55:39 +00:00
expected: &[
TokenKind::DoubleEqual,
TokenKind::BangEqual,
TokenKind::Less,
TokenKind::LessEqual,
TokenKind::Greater,
TokenKind::GreaterEqual,
],
2024-10-09 16:16:46 +00:00
found: operator.to_owned(),
position: operator_position,
2024-09-23 04:55:39 +00:00
})
2024-09-19 15:41:18 +00:00
}
2024-09-23 04:55:39 +00:00
};
2024-09-19 15:41:18 +00:00
2024-09-24 03:38:49 +00:00
if left_is_constant {
2024-09-24 20:49:17 +00:00
instruction.set_b_is_constant();
2024-09-23 04:55:39 +00:00
}
if right_is_constant {
2024-09-24 20:49:17 +00:00
instruction.set_c_is_constant();
2024-09-23 04:55:39 +00:00
}
if push_back_left {
self.emit_instruction(left_instruction, left_position);
}
if push_back_right {
self.emit_instruction(right_instruction, right_position);
2024-09-23 12:57:49 +00:00
}
let register = self.next_register();
self.emit_instruction(instruction, operator_position);
2024-10-30 18:48:30 +00:00
self.emit_instruction(Instruction::jump(1, true), operator_position);
self.emit_instruction(
Instruction::load_boolean(register, true, true),
operator_position,
);
self.emit_instruction(
Instruction::load_boolean(register, false, false),
operator_position,
);
2024-09-24 12:29:33 +00:00
self.previous_expression_type = Type::Boolean;
2024-09-07 03:30:43 +00:00
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_logical_binary(&mut self) -> Result<(), CompileError> {
2024-10-30 18:48:30 +00:00
let start_length = self.chunk.len();
2024-11-05 21:25:55 +00:00
let (left_instruction, left_position) = self.pop_last_instruction()?;
2024-09-23 08:01:36 +00:00
let operator = self.current_token;
let operator_position = self.current_position;
let rule = ParseRule::from(&operator);
2024-09-23 08:01:36 +00:00
2024-10-30 18:48:30 +00:00
let test_instruction = match operator {
Token::DoubleAmpersand => Instruction::test(left_instruction.a(), false),
Token::DoublePipe => Instruction::test(left_instruction.a(), true),
2024-09-23 08:01:36 +00:00
_ => {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedTokenMultiple {
2024-09-23 08:01:36 +00:00
expected: &[TokenKind::DoubleAmpersand, TokenKind::DoublePipe],
found: operator.to_owned(),
position: operator_position,
})
}
};
self.advance()?;
self.emit_instruction(left_instruction, left_position);
2024-10-30 18:48:30 +00:00
self.emit_instruction(test_instruction, operator_position);
2024-10-20 14:20:09 +00:00
2024-10-30 18:48:30 +00:00
let jump_distance = (self.chunk.len() - start_length) as u8;
2024-10-20 14:20:09 +00:00
2024-10-30 18:48:30 +00:00
self.emit_instruction(Instruction::jump(jump_distance, true), operator_position);
2024-10-13 11:14:12 +00:00
self.parse_sub_expression(&rule.precedence)?;
2024-09-23 08:01:36 +00:00
self.previous_expression_type = Type::Boolean;
2024-09-23 08:01:36 +00:00
Ok(())
2024-09-23 04:55:39 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_variable(&mut self) -> Result<(), CompileError> {
2024-09-17 21:23:37 +00:00
let start_position = self.current_position;
let identifier = if let Token::Identifier(text) = self.current_token {
self.advance()?;
2024-09-19 22:07:11 +00:00
text
} else {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedToken {
expected: TokenKind::Identifier,
found: self.current_token.to_owned(),
position: start_position,
});
};
let local_index = if let Ok(local_index) = self.get_local_index(identifier) {
local_index
} else if let Some(native_function) = NativeFunction::from_str(identifier) {
return self.parse_native_call(native_function);
} else if Some(identifier) == self.chunk.name().map(|string| string.as_str()) {
let register = self.next_register();
self.emit_instruction(Instruction::load_self(register), start_position);
self.previous_expression_type = Type::SelfChunk;
return Ok(());
} else {
2024-11-06 20:40:37 +00:00
return Err(CompileError::UndeclaredVariable {
identifier: identifier.to_string(),
position: start_position,
});
};
2024-11-05 21:07:51 +00:00
let (is_mutable, local_scope) = {
let local = self.get_local(local_index)?;
(local.is_mutable, local.scope)
};
2024-11-11 00:28:21 +00:00
if !self.current_scope.contains(&local_scope) {
2024-11-06 20:40:37 +00:00
return Err(CompileError::VariableOutOfScope {
2024-11-05 21:07:51 +00:00
identifier: self.chunk.get_identifier(local_index).unwrap(),
position: start_position,
variable_scope: local_scope,
2024-11-11 00:28:21 +00:00
access_scope: self.current_scope,
2024-11-05 21:07:51 +00:00
});
}
2024-11-05 21:07:51 +00:00
if self.allow(Token::Equal)? {
2024-09-22 22:17:21 +00:00
if !is_mutable {
2024-11-06 20:40:37 +00:00
return Err(CompileError::CannotMutateImmutableVariable {
identifier: self.chunk.get_identifier(local_index).unwrap(),
2024-09-22 22:17:21 +00:00
position: start_position,
});
}
2024-10-12 14:55:34 +00:00
self.parse_expression()?;
2024-09-15 01:05:03 +00:00
let register = self.next_register() - 1;
2024-09-19 15:41:18 +00:00
self.emit_instruction(
Instruction::set_local(register, local_index),
2024-09-19 03:02:28 +00:00
start_position,
);
self.previous_expression_type = Type::None;
2024-11-16 10:16:51 +00:00
let mut optimizer = Optimizer::new(&mut self.chunk);
let optimized = optimizer.optimize_set_local();
if optimized {
self.optimization_count += 1;
}
return Ok(());
2024-09-07 21:16:14 +00:00
}
2024-09-07 17:51:05 +00:00
let register = self.next_register();
self.emit_instruction(
Instruction::get_local(register, local_index),
self.previous_position,
);
let local = self.get_local(local_index)?;
self.previous_expression_type = local.r#type.clone();
2024-09-07 17:51:05 +00:00
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_type_from(&mut self, token: Token, position: Span) -> Result<Type, CompileError> {
match token {
Token::Bool => Ok(Type::Boolean),
Token::FloatKeyword => Ok(Type::Float),
Token::Int => Ok(Type::Integer),
Token::Str => Ok(Type::String { length: None }),
2024-11-06 20:40:37 +00:00
_ => Err(CompileError::ExpectedTokenMultiple {
expected: &[
TokenKind::Bool,
TokenKind::FloatKeyword,
TokenKind::Int,
TokenKind::Str,
],
found: self.current_token.to_owned(),
position,
}),
}
}
2024-11-06 20:50:05 +00:00
fn parse_block(&mut self) -> Result<(), CompileError> {
self.advance()?;
2024-11-11 00:28:21 +00:00
self.block_index += 1;
self.current_scope.begin(self.block_index);
2024-09-10 14:44:15 +00:00
2024-11-07 23:48:53 +00:00
while !self.allow(Token::RightBrace)? && !self.is_eof() {
2024-11-06 20:50:05 +00:00
self.parse(Precedence::None)?;
2024-09-10 14:44:15 +00:00
}
2024-11-11 00:28:21 +00:00
self.current_scope.end();
2024-09-11 07:10:12 +00:00
2024-09-10 14:44:15 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_list(&mut self) -> Result<(), CompileError> {
2024-09-18 01:10:44 +00:00
let start = self.current_position.0;
2024-09-17 23:35:33 +00:00
self.advance()?;
let start_register = self.next_register();
let mut item_type = Type::Any;
2024-09-17 23:35:33 +00:00
2024-11-07 23:48:53 +00:00
while !self.allow(Token::RightBracket)? && !self.is_eof() {
let expected_register = self.next_register();
2024-09-18 03:06:58 +00:00
2024-10-12 14:55:34 +00:00
self.parse_expression()?;
2024-09-17 23:35:33 +00:00
if expected_register > start_register {
if let Err(conflict) = item_type.check(&self.previous_expression_type) {
return Err(CompileError::ListItemTypeConflict {
conflict,
position: self.previous_position,
});
}
}
item_type = self.previous_expression_type.clone();
let actual_register = self.next_register() - 1;
if expected_register < actual_register {
self.emit_instruction(
Instruction::close(expected_register, actual_register),
2024-09-18 03:06:58 +00:00
self.current_position,
);
}
self.allow(Token::Comma)?;
2024-09-17 23:35:33 +00:00
}
let to_register = self.next_register();
2024-09-17 23:35:33 +00:00
let end = self.current_position.1;
self.emit_instruction(
Instruction::load_list(to_register, start_register),
2024-09-17 23:35:33 +00:00
Span(start, end),
);
self.previous_expression_type = Type::List {
item_type: Box::new(item_type),
length: (to_register - start_register) as usize,
};
2024-09-17 23:35:33 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_if(&mut self) -> Result<(), CompileError> {
self.advance()?;
2024-10-12 14:55:34 +00:00
self.parse_expression()?;
2024-09-22 22:17:21 +00:00
if matches!(
self.get_last_operations(),
Some([
Operation::Equal | Operation::Less | Operation::LessEqual,
Operation::Jump,
Operation::LoadBoolean,
Operation::LoadBoolean,
2024-11-06 19:46:23 +00:00
])
) {
2024-10-25 02:37:18 +00:00
self.chunk.instructions_mut().pop();
self.chunk.instructions_mut().pop();
2024-11-06 19:46:23 +00:00
self.chunk.instructions_mut().pop();
}
2024-11-06 19:46:23 +00:00
let if_block_start = self.chunk.len();
let if_block_start_position = self.current_position;
2024-10-12 14:55:34 +00:00
2024-11-07 23:48:53 +00:00
if let Token::LeftBrace = self.current_token {
2024-11-06 20:50:05 +00:00
self.parse_block()?;
} else {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedToken {
2024-11-07 23:48:53 +00:00
expected: TokenKind::LeftBrace,
found: self.current_token.to_owned(),
position: self.current_position,
});
2024-09-24 04:24:09 +00:00
}
2024-11-06 19:46:23 +00:00
let if_block_end = self.chunk.len();
let mut if_block_distance = (if_block_end - if_block_start) as u8;
let if_block_type = self.previous_expression_type.clone();
2024-11-06 19:46:23 +00:00
let if_last_register = self.next_register().saturating_sub(1);
2024-11-06 18:09:29 +00:00
2024-11-16 10:40:31 +00:00
if let Token::Else = self.current_token {
2024-11-06 19:46:23 +00:00
self.advance()?;
2024-11-06 18:09:29 +00:00
2024-11-07 23:48:53 +00:00
if let Token::LeftBrace = self.current_token {
2024-11-06 20:50:05 +00:00
self.parse_block()?;
2024-11-06 19:46:23 +00:00
} else {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedTokenMultiple {
2024-11-07 23:48:53 +00:00
expected: &[TokenKind::If, TokenKind::LeftBrace],
2024-11-06 19:46:23 +00:00
found: self.current_token.to_owned(),
position: self.current_position,
});
2024-11-06 18:09:29 +00:00
}
2024-10-30 18:48:30 +00:00
true
} else if self.previous_expression_type != Type::None {
return Err(CompileError::IfMissingElse {
position: Span(if_block_start_position.0, self.current_position.1),
});
} else {
false
};
2024-11-06 19:46:23 +00:00
let else_block_end = self.chunk.len();
let else_block_distance = (else_block_end - if_block_end) as u8;
2024-10-30 18:48:30 +00:00
if let Err(conflict) = if_block_type.check(&self.previous_expression_type) {
return Err(CompileError::IfElseBranchMismatch {
conflict,
position: Span(if_block_start_position.0, self.current_position.1),
});
}
2024-11-06 19:46:23 +00:00
match else_block_distance {
0 => {}
2024-11-16 10:40:31 +00:00
1 => {
if let Some(skippable) =
self.get_last_jumpable_mut_between(1, if_block_distance as usize)
{
2024-10-30 18:48:30 +00:00
skippable.set_c_to_boolean(true);
} else {
2024-11-06 19:46:23 +00:00
if_block_distance += 1;
self.chunk.instructions_mut().insert(
2024-11-06 19:46:23 +00:00
if_block_end,
(
2024-11-06 19:46:23 +00:00
Instruction::jump(else_block_distance, true),
self.current_position,
),
);
2024-10-30 18:48:30 +00:00
}
2024-11-06 19:46:23 +00:00
}
2.. => {
if_block_distance += 1;
self.chunk.instructions_mut().insert(
2024-11-06 19:46:23 +00:00
if_block_end,
(
2024-11-06 19:46:23 +00:00
Instruction::jump(else_block_distance, true),
self.current_position,
),
);
2024-10-30 18:48:30 +00:00
}
2024-10-25 02:37:18 +00:00
}
2024-11-06 19:46:23 +00:00
self.chunk.instructions_mut().insert(
if_block_start,
(
Instruction::jump(if_block_distance, true),
if_block_start_position,
),
);
2024-11-06 19:46:23 +00:00
if self.chunk.len() >= 4 {
2024-11-16 10:16:51 +00:00
let mut optimizer = Optimizer::new(&mut self.chunk);
let optimized = optimizer.optimize_comparison();
2024-10-25 02:37:18 +00:00
if optimized {
self.optimization_count += 1
}
2024-11-06 19:46:23 +00:00
}
2024-10-25 02:37:18 +00:00
2024-11-06 19:46:23 +00:00
let else_last_register = self.next_register().saturating_sub(1);
2024-10-30 18:48:30 +00:00
2024-11-06 19:46:23 +00:00
if if_last_register < else_last_register {
self.emit_instruction(
Instruction::r#move(else_last_register, if_last_register),
self.current_position,
);
2024-09-22 22:17:21 +00:00
}
2024-09-19 17:54:28 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_while(&mut self) -> Result<(), CompileError> {
2024-09-19 03:02:28 +00:00
self.advance()?;
2024-10-20 14:20:09 +00:00
2024-11-01 00:33:46 +00:00
let expression_start = self.chunk.len() as u8;
2024-10-20 14:20:09 +00:00
2024-10-12 14:55:34 +00:00
self.parse_expression()?;
if matches!(
self.get_last_operations(),
Some([
Operation::Equal | Operation::Less | Operation::LessEqual,
Operation::Jump,
Operation::LoadBoolean,
Operation::LoadBoolean,
],)
) {
2024-10-25 02:37:18 +00:00
self.chunk.instructions_mut().pop();
self.chunk.instructions_mut().pop();
2024-11-01 00:33:46 +00:00
self.chunk.instructions_mut().pop();
}
2024-11-01 00:33:46 +00:00
let block_start = self.chunk.len();
2024-11-06 20:50:05 +00:00
self.parse_block()?;
2024-09-19 03:02:28 +00:00
2024-11-01 00:33:46 +00:00
let block_end = self.chunk.len() as u8;
self.chunk.instructions_mut().insert(
2024-11-01 00:33:46 +00:00
block_start,
(
Instruction::jump(block_end - block_start as u8 + 1, true),
self.current_position,
),
);
2024-10-20 14:20:09 +00:00
2024-11-01 00:33:46 +00:00
let jump_back_distance = block_end - expression_start + 1;
let jump_back = Instruction::jump(jump_back_distance, false);
self.emit_instruction(jump_back, self.current_position);
self.previous_expression_type = Type::None;
2024-09-19 03:02:28 +00:00
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_native_call(&mut self, function: NativeFunction) -> Result<(), CompileError> {
let start = self.previous_position.0;
2024-10-30 07:08:25 +00:00
let start_register = self.next_register();
self.expect(Token::LeftParenthesis)?;
2024-10-30 07:08:25 +00:00
while !self.allow(Token::RightParenthesis)? {
let expected_register = self.next_register();
2024-10-30 07:08:25 +00:00
self.parse_expression()?;
2024-10-30 07:08:25 +00:00
let actual_register = self.next_register() - 1;
2024-10-30 07:08:25 +00:00
if expected_register < actual_register {
self.emit_instruction(
Instruction::close(expected_register, actual_register),
self.current_position,
);
2024-10-30 07:08:25 +00:00
}
self.allow(Token::Comma)?;
2024-10-30 07:08:25 +00:00
}
let end = self.previous_position.1;
let to_register = self.next_register();
2024-10-30 07:08:25 +00:00
let argument_count = to_register - start_register;
2024-11-16 10:16:51 +00:00
self.previous_expression_type = *function.r#type().return_type;
2024-10-30 07:08:25 +00:00
self.emit_instruction(
Instruction::call_native(to_register, function, argument_count),
2024-10-30 07:08:25 +00:00
Span(start, end),
);
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_top_level(&mut self) -> Result<(), CompileError> {
loop {
2024-11-06 20:50:05 +00:00
self.parse(Precedence::None)?;
2024-11-07 23:48:53 +00:00
if self.is_eof() || self.allow(Token::RightBrace)? {
self.parse_implicit_return()?;
break;
}
}
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_expression(&mut self) -> Result<(), CompileError> {
2024-11-06 20:50:05 +00:00
self.parse(Precedence::None)?;
2024-11-05 21:25:55 +00:00
if self.previous_expression_type == Type::None || self.chunk.is_empty() {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedExpression {
2024-11-05 21:25:55 +00:00
found: self.previous_token.to_owned(),
position: self.current_position,
});
}
Ok(())
2024-10-12 14:55:34 +00:00
}
2024-11-06 20:40:37 +00:00
fn parse_sub_expression(&mut self, precedence: &Precedence) -> Result<(), CompileError> {
2024-11-06 20:50:05 +00:00
self.parse(precedence.increment())
2024-10-13 11:14:12 +00:00
}
2024-11-06 20:50:05 +00:00
fn parse_return_statement(&mut self) -> Result<(), CompileError> {
let start = self.current_position.0;
2024-10-09 16:16:46 +00:00
self.advance()?;
2024-11-07 23:48:53 +00:00
let has_return_value = if matches!(self.current_token, Token::Semicolon | Token::RightBrace)
{
self.update_return_type(Type::None)?;
false
} else {
self.parse_expression()?;
self.update_return_type(self.previous_expression_type.clone())?;
true
};
let end = self.current_position.1;
self.emit_instruction(Instruction::r#return(has_return_value), Span(start, end));
self.previous_expression_type = Type::None;
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_implicit_return(&mut self) -> Result<(), CompileError> {
2024-11-06 19:46:23 +00:00
if self.allow(Token::Semicolon)? {
self.emit_instruction(Instruction::r#return(false), self.current_position);
} else {
self.emit_instruction(
Instruction::r#return(self.previous_expression_type != Type::None),
self.current_position,
);
}
2024-09-19 22:07:11 +00:00
2024-09-07 16:15:47 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_let_statement(&mut self) -> Result<(), CompileError> {
2024-10-09 16:16:46 +00:00
self.advance()?;
2024-09-17 21:23:37 +00:00
let is_mutable = self.allow(Token::Mut)?;
2024-09-07 16:15:47 +00:00
let position = self.current_position;
let identifier = if let Token::Identifier(text) = self.current_token {
2024-09-09 23:23:49 +00:00
self.advance()?;
2024-09-07 16:15:47 +00:00
text
2024-09-09 23:23:49 +00:00
} else {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedToken {
2024-09-09 23:23:49 +00:00
expected: TokenKind::Identifier,
found: self.current_token.to_owned(),
2024-10-09 16:16:46 +00:00
position,
2024-09-09 23:23:49 +00:00
});
};
let explicit_type = if self.allow(Token::Colon)? {
2024-10-09 16:16:46 +00:00
self.advance()?;
let r#type = self.parse_type_from(self.current_token, self.current_position)?;
2024-10-09 16:16:46 +00:00
Some(r#type)
} else {
None
};
2024-09-09 23:23:49 +00:00
self.expect(Token::Equal)?;
self.parse_expression()?;
let register = self.next_register() - 1;
let r#type = if let Some(r#type) = explicit_type {
r#type
} else {
self.get_register_type(register)?
};
2024-11-11 00:28:21 +00:00
let (local_index, _) =
self.declare_local(identifier, r#type, is_mutable, self.current_scope, register);
self.emit_instruction(
Instruction::define_local(register, local_index, is_mutable),
2024-10-09 16:16:46 +00:00
position,
);
self.previous_expression_type = Type::None;
2024-09-07 16:15:47 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_function(&mut self) -> Result<(), CompileError> {
let function_start = self.current_position.0;
2024-11-06 20:40:37 +00:00
let mut function_compiler = Compiler::new(self.lexer)?;
let identifier = if let Token::Identifier(text) = function_compiler.current_token {
let position = function_compiler.current_position;
2024-11-06 20:40:37 +00:00
function_compiler.advance()?;
function_compiler.chunk.set_name(text.to_string());
Some((text, position))
} else {
None
};
2024-10-09 02:56:01 +00:00
2024-11-06 20:40:37 +00:00
function_compiler.expect(Token::LeftParenthesis)?;
2024-10-09 02:56:01 +00:00
let mut value_parameters: Option<Vec<(u8, Type)>> = None;
2024-11-06 20:40:37 +00:00
while function_compiler.current_token != Token::RightParenthesis {
let is_mutable = function_compiler.allow(Token::Mut)?;
let parameter = if let Token::Identifier(text) = function_compiler.current_token {
function_compiler.advance()?;
2024-10-09 02:56:01 +00:00
text
} else {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedToken {
expected: TokenKind::Identifier,
2024-11-06 20:40:37 +00:00
found: function_compiler.current_token.to_owned(),
position: function_compiler.current_position,
});
};
2024-11-06 20:40:37 +00:00
function_compiler.expect(Token::Colon)?;
2024-11-06 20:40:37 +00:00
let r#type = function_compiler.parse_type_from(
function_compiler.current_token,
function_compiler.current_position,
)?;
2024-11-06 20:40:37 +00:00
function_compiler.advance()?;
let register = function_compiler.next_register();
2024-11-06 20:40:37 +00:00
let (_, identifier_index) = function_compiler.declare_local(
parameter,
r#type.clone(),
is_mutable,
2024-11-11 00:28:21 +00:00
function_compiler.current_scope,
register,
);
if let Some(value_parameters) = value_parameters.as_mut() {
value_parameters.push((identifier_index, r#type));
} else {
value_parameters = Some(vec![(identifier_index, r#type)]);
};
2024-11-06 20:40:37 +00:00
function_compiler.minimum_register += 1;
2024-11-06 20:40:37 +00:00
function_compiler.allow(Token::Comma)?;
}
2024-10-09 02:56:01 +00:00
2024-11-06 20:40:37 +00:00
function_compiler.advance()?;
2024-10-19 05:58:30 +00:00
2024-11-06 20:40:37 +00:00
let return_type = if function_compiler.allow(Token::ArrowThin)? {
let r#type = function_compiler.parse_type_from(
function_compiler.current_token,
function_compiler.current_position,
2024-10-19 05:58:30 +00:00
)?;
2024-11-06 20:40:37 +00:00
function_compiler.advance()?;
2024-10-19 05:58:30 +00:00
Box::new(r#type)
2024-10-19 05:58:30 +00:00
} else {
Box::new(Type::None)
2024-10-19 05:58:30 +00:00
};
let function_type = FunctionType {
type_parameters: None,
value_parameters,
return_type,
};
function_compiler.chunk.set_type(function_type.clone());
2024-10-19 05:58:30 +00:00
2024-11-07 23:48:53 +00:00
function_compiler.expect(Token::LeftBrace)?;
2024-11-06 20:40:37 +00:00
function_compiler.parse_top_level()?;
2024-10-09 02:56:01 +00:00
2024-11-06 20:40:37 +00:00
self.previous_token = function_compiler.previous_token;
self.previous_position = function_compiler.previous_position;
self.current_token = function_compiler.current_token;
self.current_position = function_compiler.current_position;
2024-10-09 02:56:01 +00:00
let function = ConcreteValue::Function(function_compiler.finish());
2024-11-11 00:28:21 +00:00
let constant_index = self.chunk.push_or_get_constant(function);
let function_end = self.current_position.1;
2024-11-11 00:28:21 +00:00
let register = self.next_register();
2024-10-09 02:56:01 +00:00
self.lexer.skip_to(function_end);
if let Some((identifier, identifier_position)) = identifier {
let (local_index, _) = self.declare_local(
identifier,
Type::Function(function_type),
false,
2024-11-11 00:28:21 +00:00
self.current_scope,
register,
);
2024-11-11 00:28:21 +00:00
self.emit_instruction(
Instruction::load_constant(register, constant_index, false),
Span(function_start, function_end),
);
self.emit_instruction(
Instruction::define_local(register, local_index, false),
identifier_position,
);
self.previous_expression_type = Type::None;
} else {
2024-11-11 00:28:21 +00:00
self.emit_instruction(
Instruction::load_constant(register, constant_index, false),
Span(function_start, function_end),
);
self.previous_expression_type = Type::Function(function_type);
}
2024-10-09 02:56:01 +00:00
Ok(())
}
2024-11-06 20:40:37 +00:00
fn parse_call(&mut self) -> Result<(), CompileError> {
2024-11-05 21:25:55 +00:00
let (last_instruction, _) =
self.chunk
.instructions()
.last()
2024-11-06 20:40:37 +00:00
.ok_or_else(|| CompileError::ExpectedExpression {
2024-11-05 21:25:55 +00:00
found: self.previous_token.to_owned(),
position: self.previous_position,
})?;
if !last_instruction.yields_value() {
2024-11-06 20:40:37 +00:00
return Err(CompileError::ExpectedExpression {
found: self.previous_token.to_owned(),
position: self.previous_position,
});
}
2024-10-19 21:24:22 +00:00
let function_register = last_instruction.a();
2024-11-11 00:28:21 +00:00
let register_type = self.get_register_type(function_register)?;
let function_return_type = match register_type {
Type::Function(function_type) => *function_type.return_type,
Type::SelfChunk => (*self.chunk.r#type().return_type).clone(),
_ => {
return Err(CompileError::ExpectedFunction {
found: self.previous_token.to_owned(),
2024-11-11 00:28:21 +00:00
actual_type: register_type,
position: self.previous_position,
});
2024-11-11 00:28:21 +00:00
}
};
2024-10-30 07:08:25 +00:00
let start = self.current_position.0;
2024-10-12 14:55:34 +00:00
self.advance()?;
while !self.allow(Token::RightParenthesis)? {
let expected_register = self.next_register();
self.parse_expression()?;
let actual_register = self.next_register() - 1;
if expected_register < actual_register {
self.emit_instruction(
Instruction::close(expected_register, actual_register),
self.current_position,
);
}
2024-10-13 11:14:12 +00:00
self.allow(Token::Comma)?;
2024-10-12 14:55:34 +00:00
}
let end = self.current_position.1;
2024-10-19 21:24:22 +00:00
let to_register = self.next_register();
let argument_count = to_register - function_register - 1;
self.emit_instruction(
2024-10-19 21:24:22 +00:00
Instruction::call(to_register, function_register, argument_count),
Span(start, end),
2024-10-12 14:55:34 +00:00
);
self.previous_expression_type = function_return_type;
2024-10-12 14:55:34 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn parse_semicolon(&mut self) -> Result<(), CompileError> {
2024-11-05 21:25:55 +00:00
self.advance()?;
self.previous_expression_type = Type::None;
2024-11-05 21:25:55 +00:00
Ok(())
}
2024-11-06 20:50:05 +00:00
fn expect_expression(&mut self) -> Result<(), CompileError> {
2024-11-06 20:40:37 +00:00
Err(CompileError::ExpectedExpression {
2024-11-05 21:25:55 +00:00
found: self.current_token.to_owned(),
position: self.current_position,
})
}
2024-11-06 20:50:05 +00:00
fn parse(&mut self, precedence: Precedence) -> Result<(), CompileError> {
if let Some(prefix_parser) = ParseRule::from(&self.current_token).prefix {
log::debug!(
"{} is prefix with precedence {precedence}",
2024-09-25 05:27:10 +00:00
self.current_token.to_string().bold(),
2024-09-15 10:26:31 +00:00
);
2024-09-07 21:16:14 +00:00
2024-11-06 20:50:05 +00:00
prefix_parser(self)?;
2024-09-17 21:23:37 +00:00
}
let mut infix_rule = ParseRule::from(&self.current_token);
2024-09-17 17:24:45 +00:00
while precedence <= infix_rule.precedence {
if let Some(infix_parser) = infix_rule.infix {
log::debug!(
"{} is infix with precedence {precedence}",
2024-09-25 05:27:10 +00:00
self.current_token.to_string().bold(),
2024-09-07 10:38:12 +00:00
);
2024-11-06 20:50:05 +00:00
if self.current_token == Token::Equal {
2024-11-06 20:40:37 +00:00
return Err(CompileError::InvalidAssignmentTarget {
2024-09-17 21:23:37 +00:00
found: self.current_token.to_owned(),
position: self.current_position,
2024-09-07 21:16:14 +00:00
});
}
2024-09-10 05:04:30 +00:00
infix_parser(self)?;
} else {
break;
}
2024-09-17 21:23:37 +00:00
infix_rule = ParseRule::from(&self.current_token);
}
2024-10-09 16:16:46 +00:00
Ok(())
2024-09-07 03:30:43 +00:00
}
}
2024-11-06 20:50:05 +00:00
/// Operator precedence levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Precedence {
None,
Assignment,
Conditional,
LogicalOr,
LogicalAnd,
Equality,
Comparison,
Term,
Factor,
Unary,
Call,
Primary,
}
impl Precedence {
fn increment(&self) -> Self {
match self {
Precedence::None => Precedence::Assignment,
Precedence::Assignment => Precedence::Conditional,
Precedence::Conditional => Precedence::LogicalOr,
Precedence::LogicalOr => Precedence::LogicalAnd,
Precedence::LogicalAnd => Precedence::Equality,
Precedence::Equality => Precedence::Comparison,
Precedence::Comparison => Precedence::Term,
Precedence::Term => Precedence::Factor,
Precedence::Factor => Precedence::Unary,
Precedence::Unary => Precedence::Call,
Precedence::Call => Precedence::Primary,
Precedence::Primary => Precedence::Primary,
}
}
}
impl Display for Precedence {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
2024-11-06 20:50:05 +00:00
type Parser<'a> = fn(&mut Compiler<'a>) -> Result<(), CompileError>;
2024-11-06 20:50:05 +00:00
/// Rule that defines how to parse a token.
#[derive(Debug, Clone, Copy)]
2024-10-09 16:16:46 +00:00
struct ParseRule<'a> {
2024-11-06 20:50:05 +00:00
pub prefix: Option<Parser<'a>>,
pub infix: Option<Parser<'a>>,
pub precedence: Precedence,
}
impl From<&Token<'_>> for ParseRule<'_> {
fn from(token: &Token) -> Self {
match token {
2024-10-19 05:58:30 +00:00
Token::ArrowThin => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
2024-10-19 05:58:30 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Async => todo!(),
Token::Bang => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_unary),
infix: None,
2024-09-22 22:17:21 +00:00
precedence: Precedence::Unary,
},
Token::BangEqual => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_comparison_binary),
2024-09-22 22:17:21 +00:00
precedence: Precedence::Equality,
2024-09-07 16:15:47 +00:00
},
Token::Bool => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::Boolean(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_boolean),
2024-09-07 10:38:12 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Break => todo!(),
Token::Byte(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_byte),
2024-09-10 03:45:06 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Character(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_character),
2024-09-10 03:45:06 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Colon => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::Comma => ParseRule {
2024-09-17 23:35:33 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
Token::Dot => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::DoubleAmpersand => ParseRule {
2024-09-10 05:04:30 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_logical_binary),
2024-09-10 05:04:30 +00:00
precedence: Precedence::LogicalAnd,
},
Token::DoubleEqual => ParseRule {
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_comparison_binary),
precedence: Precedence::Equality,
},
Token::DoublePipe => ParseRule {
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_logical_binary),
precedence: Precedence::LogicalOr,
},
Token::DoubleDot => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::Eof => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
Token::Equal => ParseRule {
2024-09-17 21:23:37 +00:00
prefix: None,
infix: None,
precedence: Precedence::Assignment,
},
Token::Else => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
Token::Float(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_float),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::None,
},
Token::FloatKeyword => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::Fn => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_function),
2024-10-09 02:56:01 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Greater => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_comparison_binary),
2024-09-22 22:17:21 +00:00
precedence: Precedence::Comparison,
},
Token::GreaterEqual => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_comparison_binary),
2024-09-22 22:17:21 +00:00
precedence: Precedence::Comparison,
},
Token::Identifier(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_variable),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::None,
},
Token::If => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_if),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Int => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::Integer(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_integer),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::None,
},
2024-11-07 23:48:53 +00:00
Token::LeftBrace => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_block),
2024-09-10 14:44:15 +00:00
infix: None,
precedence: Precedence::None,
},
Token::LeftParenthesis => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_grouped),
infix: Some(Compiler::parse_call),
2024-10-12 14:55:34 +00:00
precedence: Precedence::Call,
},
2024-11-07 23:48:53 +00:00
Token::LeftBracket => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_list),
2024-09-17 23:35:33 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Less => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_comparison_binary),
2024-09-22 22:17:21 +00:00
precedence: Precedence::Comparison,
},
Token::LessEqual => ParseRule {
2024-09-22 22:17:21 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_comparison_binary),
2024-09-22 22:17:21 +00:00
precedence: Precedence::Comparison,
},
Token::Let => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_let_statement),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::Assignment,
2024-09-22 22:17:21 +00:00
},
Token::Loop => todo!(),
Token::Map => todo!(),
Token::Minus => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_unary),
infix: Some(Compiler::parse_math_binary),
precedence: Precedence::Term,
},
Token::MinusEqual => ParseRule {
2024-10-05 08:33:38 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
2024-10-05 08:33:38 +00:00
precedence: Precedence::Assignment,
},
Token::Mut => ParseRule {
2024-09-18 15:27:41 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
Token::Percent => ParseRule {
2024-09-18 15:27:41 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
2024-09-18 15:27:41 +00:00
precedence: Precedence::Factor,
},
Token::PercentEqual => ParseRule {
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
precedence: Precedence::Assignment,
},
Token::Plus => ParseRule {
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
precedence: Precedence::Term,
},
Token::PlusEqual => ParseRule {
2024-10-05 08:33:38 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
2024-10-05 08:33:38 +00:00
precedence: Precedence::Assignment,
},
Token::Return => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_return_statement),
2024-10-09 16:16:46 +00:00
infix: None,
precedence: Precedence::None,
},
2024-11-07 23:48:53 +00:00
Token::RightBrace => ParseRule {
2024-09-10 14:44:15 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
Token::RightParenthesis => ParseRule {
2024-09-07 10:38:12 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
2024-11-07 23:48:53 +00:00
Token::RightBracket => ParseRule {
2024-09-17 23:35:33 +00:00
prefix: None,
infix: None,
precedence: Precedence::None,
},
Token::Semicolon => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_semicolon),
2024-09-07 16:15:47 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Slash => ParseRule {
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
precedence: Precedence::Factor,
},
Token::SlashEqual => ParseRule {
2024-10-05 08:33:38 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
2024-10-05 08:33:38 +00:00
precedence: Precedence::Assignment,
},
Token::Star => ParseRule {
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
precedence: Precedence::Factor,
},
Token::StarEqual => ParseRule {
2024-10-05 08:33:38 +00:00
prefix: None,
2024-11-06 20:40:37 +00:00
infix: Some(Compiler::parse_math_binary),
2024-10-05 08:33:38 +00:00
precedence: Precedence::Assignment,
},
Token::Str => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::expect_expression),
infix: None,
precedence: Precedence::None,
},
Token::String(_) => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_string),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::None,
},
Token::Struct => todo!(),
Token::While => ParseRule {
2024-11-06 20:40:37 +00:00
prefix: Some(Compiler::parse_while),
2024-09-22 22:17:21 +00:00
infix: None,
precedence: Precedence::None,
},
}
}
}
2024-11-06 20:50:05 +00:00
/// Compilation errors
2024-11-06 18:50:49 +00:00
#[derive(Clone, Debug, PartialEq)]
2024-11-06 20:40:37 +00:00
pub enum CompileError {
// Token errors
ExpectedToken {
expected: TokenKind,
found: TokenOwned,
2024-10-12 12:16:06 +00:00
position: Span,
},
ExpectedTokenMultiple {
expected: &'static [TokenKind],
found: TokenOwned,
2024-09-19 00:02:12 +00:00
position: Span,
},
2024-11-06 20:50:05 +00:00
// Parsing errors
CannotChainComparison {
position: Span,
},
ExpectedExpression {
2024-09-07 03:30:43 +00:00
found: TokenOwned,
position: Span,
},
ExpectedFunction {
found: TokenOwned,
2024-11-11 00:28:21 +00:00
actual_type: Type,
position: Span,
},
ExpectedFunctionType {
found: Type,
position: Span,
},
2024-11-06 20:50:05 +00:00
InvalidAssignmentTarget {
found: TokenOwned,
position: Span,
},
UnexpectedReturn {
position: Span,
},
// Variable errors
CannotMutateImmutableVariable {
identifier: String,
2024-09-07 03:30:43 +00:00
position: Span,
},
2024-10-05 08:33:38 +00:00
ExpectedMutableVariable {
found: TokenOwned,
position: Span,
},
UndeclaredVariable {
identifier: String,
position: Span,
},
2024-11-05 21:07:51 +00:00
VariableOutOfScope {
identifier: String,
variable_scope: Scope,
access_scope: Scope,
position: Span,
},
// Type errors
CannotResolveRegisterType {
register_index: usize,
position: Span,
},
CannotResolveVariableType {
identifier: String,
position: Span,
},
IfElseBranchMismatch {
conflict: TypeConflict,
position: Span,
},
IfMissingElse {
position: Span,
},
ListItemTypeConflict {
conflict: TypeConflict,
position: Span,
},
ReturnTypeConflict {
conflict: TypeConflict,
position: Span,
},
2024-11-06 18:50:49 +00:00
// Wrappers around foreign errors
Chunk {
error: ChunkError,
position: Span,
},
2024-09-07 03:30:43 +00:00
Lex(LexError),
ParseFloatError {
error: ParseFloatError,
position: Span,
},
ParseIntError {
error: ParseIntError,
position: Span,
},
2024-09-07 03:30:43 +00:00
}
2024-11-06 20:40:37 +00:00
impl AnnotatedError for CompileError {
fn title() -> &'static str {
2024-11-06 20:40:37 +00:00
"Compilation Error"
}
fn description(&self) -> &'static str {
match self {
Self::CannotChainComparison { .. } => "Cannot chain comparison operations",
2024-09-19 00:02:12 +00:00
Self::CannotMutateImmutableVariable { .. } => "Cannot mutate immutable variable",
Self::CannotResolveRegisterType { .. } => "Cannot resolve register type",
Self::CannotResolveVariableType { .. } => "Cannot resolve type",
2024-11-06 18:50:49 +00:00
Self::Chunk { .. } => "Chunk error",
Self::ExpectedExpression { .. } => "Expected an expression",
Self::ExpectedFunction { .. } => "Expected a function",
Self::ExpectedFunctionType { .. } => "Expected a function type",
Self::ExpectedMutableVariable { .. } => "Expected a mutable variable",
Self::ExpectedToken { .. } => "Expected a specific token",
Self::ExpectedTokenMultiple { .. } => "Expected one of multiple tokens",
Self::IfElseBranchMismatch { .. } => "Type mismatch in if/else branches",
Self::IfMissingElse { .. } => "If statement missing else branch",
Self::InvalidAssignmentTarget { .. } => "Invalid assignment target",
Self::Lex(error) => error.description(),
Self::ListItemTypeConflict { .. } => "List item type conflict",
Self::ParseFloatError { .. } => "Failed to parse float",
Self::ParseIntError { .. } => "Failed to parse integer",
Self::ReturnTypeConflict { .. } => "Return type conflict",
Self::UndeclaredVariable { .. } => "Undeclared variable",
Self::UnexpectedReturn { .. } => "Unexpected return",
2024-11-05 21:07:51 +00:00
Self::VariableOutOfScope { .. } => "Variable out of scope",
}
}
fn details(&self) -> Option<String> {
match self {
2024-09-19 00:02:12 +00:00
Self::CannotMutateImmutableVariable { identifier, .. } => {
Some(format!("{identifier} is immutable"))
2024-09-19 00:02:12 +00:00
}
2024-11-06 18:50:49 +00:00
Self::Chunk { error, .. } => Some(error.to_string()),
Self::ExpectedExpression { found, .. } => Some(format!("Found {found}")),
2024-11-11 00:28:21 +00:00
Self::ExpectedFunction { found, actual_type, .. } => {
Some(format!("Expected \"{found}\" to be a function but it has type {actual_type}"))
}
Self::ExpectedFunctionType { found, .. } => {
Some(format!("Expected a function type but found {found}"))
}
Self::ExpectedToken {
expected, found, ..
} => Some(format!("Expected {expected} but found {found}")),
Self::ExpectedTokenMultiple {
expected, found, ..
2024-09-19 15:41:18 +00:00
} => {
2024-09-24 04:24:09 +00:00
let mut details = String::from("Expected");
for (index, token) in expected.iter().enumerate() {
details.push_str(&format!(" {token}"));
2024-09-24 04:24:09 +00:00
if index < expected.len() - 2 {
details.push_str(", ");
}
if index == expected.len() - 2 {
details.push_str(" or");
}
}
details.push_str(&format!(" but found {found}"));
2024-09-19 15:41:18 +00:00
2024-09-24 04:24:09 +00:00
Some(details)
2024-09-19 15:41:18 +00:00
}
Self::ExpectedMutableVariable { found, .. } => Some(format!("Found {found}")),
Self::IfElseBranchMismatch {
conflict: TypeConflict { expected, actual },
..
} => Some(
format!("This if block evaluates to type \"{expected}\" but the else block evaluates to \"{actual}\"")
),
Self::IfMissingElse { .. } => Some(
"This \"if\" expression evaluates to a value but is missing an else block"
.to_string(),
),
Self::InvalidAssignmentTarget { found, .. } => {
Some(format!("Cannot assign to {found}"))
}
Self::Lex(error) => error.details(),
Self::ParseFloatError { error, .. } => Some(error.to_string()),
Self::ParseIntError { error, .. } => Some(error.to_string()),
Self::ReturnTypeConflict {
conflict: TypeConflict { expected, actual },
..
} => Some(format!(
"Expected return type \"{expected}\" but found \"{actual}\""
)),
2024-10-09 16:16:46 +00:00
Self::UndeclaredVariable { identifier, .. } => {
Some(format!("{identifier} has not been declared"))
2024-09-11 07:10:12 +00:00
}
2024-10-09 16:16:46 +00:00
Self::UnexpectedReturn { .. } => None,
2024-11-05 21:07:51 +00:00
Self::VariableOutOfScope { identifier, .. } => {
Some(format!("{identifier} is out of scope"))
2024-11-05 21:07:51 +00:00
}
_ => None,
}
}
fn position(&self) -> Span {
match self {
2024-10-12 12:16:06 +00:00
Self::CannotChainComparison { position } => *position,
2024-09-19 00:02:12 +00:00
Self::CannotMutateImmutableVariable { position, .. } => *position,
Self::CannotResolveRegisterType { position, .. } => *position,
Self::CannotResolveVariableType { position, .. } => *position,
2024-11-06 18:50:49 +00:00
Self::Chunk { position, .. } => *position,
Self::ExpectedExpression { position, .. } => *position,
Self::ExpectedFunction { position, .. } => *position,
Self::ExpectedFunctionType { position, .. } => *position,
Self::ExpectedMutableVariable { position, .. } => *position,
Self::ExpectedToken { position, .. } => *position,
Self::ExpectedTokenMultiple { position, .. } => *position,
Self::IfElseBranchMismatch { position, .. } => *position,
Self::IfMissingElse { position } => *position,
Self::InvalidAssignmentTarget { position, .. } => *position,
Self::Lex(error) => error.position(),
Self::ListItemTypeConflict { position, .. } => *position,
Self::ParseFloatError { position, .. } => *position,
Self::ParseIntError { position, .. } => *position,
Self::ReturnTypeConflict { position, .. } => *position,
Self::UndeclaredVariable { position, .. } => *position,
Self::UnexpectedReturn { position } => *position,
2024-11-05 21:07:51 +00:00
Self::VariableOutOfScope { position, .. } => *position,
}
2024-09-07 03:30:43 +00:00
}
}
2024-11-06 20:40:37 +00:00
impl From<LexError> for CompileError {
2024-09-07 03:30:43 +00:00
fn from(error: LexError) -> Self {
Self::Lex(error)
}
}