Skip to content

Commit

Permalink
Merge pull request #23 from yazaldefilimone/refactor/parser-and-location
Browse files Browse the repository at this point in the history
refactor: ...
  • Loading branch information
yazaldefilimone committed Aug 11, 2024
2 parents 25a43cb + 4a4fc1c commit 2cd77d6
Show file tree
Hide file tree
Showing 29 changed files with 512 additions and 645 deletions.
110 changes: 96 additions & 14 deletions src/ast/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,27 @@ pub enum Statement {
Expression(Expression),
}

impl Statement {
pub fn get_range(&self) -> Range {
match self {
Statement::Assign(assign) => assign.get_range(),
Statement::Function(function) => function.get_range(),
Statement::Return(return_) => return_.get_range(),
Statement::If(if_) => if_.get_range(),
Statement::While(while_) => while_.get_range(),
Statement::Repeat(repeat) => repeat.get_range(),
Statement::For(for_) => for_.get_range(),
Statement::Break(break_) => break_.get_range(),
Statement::Goto(goto) => goto.get_range(),
Statement::Block(block) => block.get_range(),
Statement::Empty(empty) => empty.get_range(),
Statement::VariableDeclaration(variable) => variable.get_range(),
Statement::TypeDeclaration(declaration) => declaration.get_range(),
Statement::Expression(expression) => expression.get_range(),
}
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AssignStatement {
pub values: Vec<(Token, Option<Type>)>,
Expand Down Expand Up @@ -62,6 +83,7 @@ pub struct FunctionStatement {
pub generics: Vec<Type>,
pub body: Box<Statement>,
pub range: Range,
pub range_return_type: Option<Range>,
}

impl FunctionStatement {
Expand All @@ -73,8 +95,13 @@ impl FunctionStatement {
return_type: Option<Type>,
body: Statement,
range: Range,
range_return_type: Option<Range>,
) -> Self {
FunctionStatement { name, local, generics, arguments, return_type, body: Box::new(body), range }
FunctionStatement { name, local, generics, arguments, return_type, body: Box::new(body), range, range_return_type }
}

pub fn get_range(&self) -> Range {
return self.range.clone();
}
}

Expand All @@ -88,6 +115,9 @@ impl ReturnStatement {
pub fn new(values: Vec<Expression>, range: Range) -> Self {
ReturnStatement { values, range }
}
pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -102,6 +132,10 @@ impl IfStatement {
pub fn new(condition: Expression, then_body: Statement, else_body: Option<Statement>, range: Range) -> Self {
IfStatement { condition, then_body: Box::new(then_body), else_body: else_body.map(Box::new), range }
}

pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -115,6 +149,9 @@ impl WhileStatement {
pub fn new(condition: Expression, body: Statement, range: Range) -> Self {
WhileStatement { condition, body: Box::new(body), range }
}
pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -128,6 +165,10 @@ impl RepeatStatement {
pub fn new(body: Statement, condition: Expression, range: Range) -> Self {
RepeatStatement { body: Box::new(body), condition, range }
}

pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -151,6 +192,10 @@ impl ForStatement {
) -> Self {
ForStatement { variable, init, limit, step, body: Box::new(body), range }
}

pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -162,6 +207,9 @@ impl BreakStatement {
pub fn new(range: Range) -> Self {
BreakStatement { range }
}
pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand All @@ -174,24 +222,39 @@ impl GotoStatement {
pub fn new(label: Option<String>, range: Range) -> Self {
GotoStatement { label, range }
}

pub fn get_range(&self) -> Range {
self.range.clone()
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BlockStatement {
pub statements: Vec<Statement>,
pub range: Range,
}

impl BlockStatement {
pub fn new(statements: Vec<Statement>, range: Range) -> Self {
BlockStatement { statements, range }
pub fn new(statements: Vec<Statement>) -> Self {
BlockStatement { statements }
}
pub fn get_range(&self) -> Range {
if self.statements.len() == 0 {
return Range::new();
}
let first_statement = self.statements.first().unwrap();
let last_statement = self.statements.last().unwrap();
create_middle_range(&first_statement.get_range(), &last_statement.get_range())
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EmptyStatement {}

impl EmptyStatement {}
impl EmptyStatement {
pub fn get_range(&self) -> Range {
Range::new()
}
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum TypeInitializer {
Expand All @@ -211,6 +274,10 @@ impl TypeDeclaration {
pub fn new(name: Token, generis: Vec<String>, initiizer: Type, range: Range) -> Self {
TypeDeclaration { name, generis, initiizer, range }
}
pub fn get_range(&self) -> Range {
// todo: check if it's correct
create_middle_range(&self.range, &self.name.range)
}
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
Expand Down Expand Up @@ -270,8 +337,8 @@ impl Expression {
Expression::Identifier(Identifier::new(name, range))
}

pub fn new_call(name: Token, args: Expression, range: Range) -> Self {
Expression::Call(CallExpression::new(name, Box::new(args), range))
pub fn new_call(name: Token, args: Expression) -> Self {
Expression::Call(CallExpression::new(name, Box::new(args)))
}

pub fn new_require(module_name: Token, range: Range) -> Self {
Expand All @@ -286,9 +353,10 @@ impl Expression {
arguments: Vec<(Token, Option<Type>)>,
return_type: Option<Type>,
body: Statement,
loc: Range,
range: Range,
return_range: Option<Range>,
) -> Self {
Expression::Function(FunctionExpression::new(arguments, return_type, body, loc))
Expression::Function(FunctionExpression::new(arguments, return_type, body, range, return_range))
}

pub fn get_range(&self) -> Range {
Expand All @@ -303,6 +371,14 @@ impl Expression {
Expression::Function(function) => function.get_range(),
}
}

pub fn is_grouped(&self) -> bool {
matches!(self, Expression::Grouped(_))
}

pub fn is_function(&self) -> bool {
matches!(self, Expression::Function(_))
}
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -355,12 +431,11 @@ impl Identifier {
pub struct CallExpression {
pub name: Token,
pub args: Box<Expression>,
pub range: Range,
}

impl CallExpression {
pub fn new(name: Token, args: Box<Expression>, range: Range) -> Self {
CallExpression { name, args, range }
pub fn new(name: Token, args: Box<Expression>) -> Self {
CallExpression { name, args }
}

pub fn get_range(&self) -> Range {
Expand Down Expand Up @@ -399,11 +474,18 @@ pub struct FunctionExpression {
pub return_type: Option<Type>,
pub body: Box<Statement>,
pub range: Range,
pub range_return_type: Option<Range>,
}

impl FunctionExpression {
pub fn new(arguments: Vec<(Token, Option<Type>)>, return_type: Option<Type>, body: Statement, range: Range) -> Self {
FunctionExpression { arguments, return_type, body: Box::new(body), range }
pub fn new(
arguments: Vec<(Token, Option<Type>)>,
return_type: Option<Type>,
body: Statement,
range: Range,
range_return_type: Option<Range>,
) -> Self {
FunctionExpression { arguments, return_type, body: Box::new(body), range, range_return_type }
}

pub fn get_range(&self) -> Range {
Expand Down
4 changes: 2 additions & 2 deletions src/ast/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ impl TokenKind {
TokenKind::TripleDot => "...",
TokenKind::LeftParen => "(",
TokenKind::RightParen => ")",
TokenKind::LeftBrace => "{{",
TokenKind::RightBrace => "}}",
TokenKind::LeftBrace => "{",
TokenKind::RightBrace => "}",
TokenKind::LeftBracket => "[",
TokenKind::RightBracket => "]",
TokenKind::Comma => ",",
Expand Down
16 changes: 0 additions & 16 deletions src/checker/check_binary_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::{
ast::ast,
diagnostics::{Diagnostic, TypeError},
types::Type,
utils::range::Range,
};

impl<'a> Checker<'a> {
Expand All @@ -25,19 +24,4 @@ impl<'a> Checker<'a> {

Err(self.create_diagnostic(diagnostic))
}

pub fn check_add_expression(&mut self, left_t: Type, right_t: Type, range: Range) -> Result<Type, Diagnostic> {
if left_t.supports_operator(&ast::BinaryOperator::Add) && right_t.supports_operator(&ast::BinaryOperator::Add) {
return Ok(Type::Number);
}

let dignostic = TypeError::UnsupportedOperator(
left_t.to_string(),
right_t.to_string(),
ast::BinaryOperator::Add.to_str().to_owned(),
Some(range),
);

Err(self.create_diagnostic(dignostic))
}
}
28 changes: 20 additions & 8 deletions src/checker/check_call_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,32 @@ impl<'a> Checker<'a> {
pub fn check_call_expression(&mut self, call_expr: &ast::CallExpression) -> Result<Type, Diagnostic> {
let name = call_expr.name.lexeme();

let (defined, scope_idx) = self.ctx.defined_in_any_scope(name);
let (defined, scope_pointer) = self.ctx.defined_in_any_scope(name);
if !defined {
let diagnostic = TypeError::UndeclaredVariable(name.to_string(), Some(call_expr.name.range.clone()));
return Err(self.create_diagnostic(diagnostic));
}

if let Some(call_t) = self.ctx.get_function_in_scope(name, scope_idx) {
let return_t = *call_t.return_type.clone();
self.check_call_arguments(&call_expr.args, &call_t.params.to_vec())?;
return Ok(return_t);
}
let call_type = self.ctx.get_variable(name, Some(scope_pointer));

let diagnostic = TypeError::UndeclaredVariable(name.to_string(), Some(call_expr.name.range.clone()));
Err(self.create_diagnostic(diagnostic))
if call_type.is_none() {
let diagnostic = TypeError::UndeclaredVariable(name.to_string(), Some(call_expr.name.range.clone()));
return Err(self.create_diagnostic(diagnostic));
}
match call_type.unwrap() {
Type::Function(call_type) => {
let return_t = *call_type.return_type.clone();
self.check_call_arguments(&call_expr.args, &call_type.params.to_vec())?;
return Ok(return_t);
}
Type::Unknown => {
return Ok(Type::Unknown);
}
_ => {
let diagnostic = TypeError::ExpectedFunction(name.to_string(), Some(call_expr.name.range.clone()));
return Err(self.create_diagnostic(diagnostic));
}
}
}

pub fn check_call_arguments(&mut self, args_call: &ast::Expression, params_tt: &[Type]) -> Result<(), Diagnostic> {
Expand Down
7 changes: 6 additions & 1 deletion src/checker/check_function_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{

impl<'a> Checker<'a> {
pub fn check_function_expression(&mut self, function: &ast::FunctionExpression) -> Result<Type, Diagnostic> {
let mut return_type = self.check_optional_type(&function.return_type)?;
let mut return_type = self.check_optional_type(&function.return_type, false)?;
self.ctx.enter_scope();

let params = self.declare_function_params(&function.arguments)?;
Expand All @@ -16,6 +16,11 @@ impl<'a> Checker<'a> {

let last_type = self.check_statement(&function.body)?;

if !return_type.check_match(&last_type) {
let range = function.range_return_type.clone().unwrap_or(function.range.clone());
let diagnostic = self.create_type_mismatch(return_type, last_type, range);
return Err(diagnostic);
}
if return_type.can_replace(&last_type) {
return_type = replace_type(&return_type, &last_type);
}
Expand Down
16 changes: 10 additions & 6 deletions src/checker/check_function_statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@ use crate::{
impl<'a> Checker<'a> {
pub fn check_function_statement(&mut self, function: &ast::FunctionStatement) -> Result<Type, Diagnostic> {
let function_name = function.name.lexeme();
let mut return_type = self.check_optional_type(&function.return_type)?;
let mut return_type = self.check_optional_type(&function.return_type, false)?;

// declare function placeholder
let scope_idx = self.ctx.declare_function_placeholder(function_name);
let anonymous_function = self.ctx.create_anonymous_function();
let scope_pointer = self.ctx.declare_variable(function_name, anonymous_function, None);

self.ctx.enter_scope();

let params = self.declare_function_params(&function.arguments)?;

self.ctx.declare_return_param_type(return_type.clone());
self.ctx.update_function_placeholder(function_name, params.clone(), return_type.clone(), scope_idx);

let function_type = Type::new_function(params, return_type.clone());
self.ctx.redeclare_variable(function_name, function_type, Some(scope_pointer));

let last_type = self.check_statement(&function.body)?;

Expand All @@ -37,9 +40,10 @@ impl<'a> Checker<'a> {
pub fn declare_function_params(&mut self, arguments: &[(Token, Option<Type>)]) -> Result<Vec<Type>, Diagnostic> {
let mut params = Vec::with_capacity(arguments.len());
for (param, ty) in arguments.iter() {
let arg_type = ty.clone().unwrap_or(Type::Unknown);
self.ctx.declare_variable(param.lexeme(), arg_type.clone());
self.ctx.set_variable_range(param.lexeme(), param.range.clone());
let arg_type = if let Some(ty) = ty { ty.clone() } else { Type::Unknown };
let lexeme = param.lexeme();
self.ctx.declare_variable(lexeme, arg_type.clone(), None);
self.ctx.declare_variable_range(lexeme, param.range.clone());
params.push(arg_type);
}
Ok(params)
Expand Down
Loading

0 comments on commit 2cd77d6

Please sign in to comment.