Add type system and refator for having only epression
This commit is contained in:
Giulio Agostini
2026-07-06 10:43:17 +02:00
parent 9f15a00b98
commit 842216729b
23 changed files with 940 additions and 979 deletions
+158 -302
View File
@@ -1,5 +1,5 @@
use crate::{
common::base_value::BaseValue,
common::{base_value::BaseValue, types::Type},
frontend::{source_registry::SourceSlice, tokens::TokenType},
};
use std::fmt::{Debug, Display};
@@ -22,65 +22,66 @@ impl NodeId {
NodeId(NEXT_NODE_ID.fetch_add(1, Ordering::Relaxed))
}
}
/*
* grammar:
* program -> statement* EOF
* statement -> expression_statement
* | print_statement
* | var_statement
* | block_statement
* | if_statement
*
* expression_statement -> expression ";"
* print_statement -> "print" expression ";"
* var_statement -> ("var"|"dyn"|"mut")? IDENTIFIER (":" IDENTIFIER)? (("=" expression)? ";")| function_declaration
* function_declaration -> "::" "(" parameters? ")" ("->" IDENTIFIER)? block_statement
* parameters -> ( IDENTIFIER (":" IDENTIFIER)? ("," IDENTIFIER (":" IDENTIFIER)? )* )
* block_statement -> "do" statement* "end"
* if_statement -> "if" expression "then" statement ("elif" expression "then" statement)* ("else" statement)? "end"
* while_statement -> "while" expression "do" statement "end"
*
* expression -> assignment
* assignment -> IDENTIFIER "=" assignment | logical_or
* logical_or -> logical_and (("or" logical_and)*
* logical_and -> logical_is (("and" logical_is)*
* logical_is -> equality (("is" equality)*
* equality -> comparison (("==" | "!=") comparison)*
* comparison -> term ((">" | ">=" | "<" | "<=") term)*
* term -> factor (("+" | "-") factor)*
* factor -> unary (("*" | "/") unary)*
* unary -> ("!" | "-") unary | call
* call -> primary ("(" arguments ")")*
* arguments -> expression ("," expression)*
* primary -> NUMBER | STRING | "true" | "false" | "nil" | "(" expression ")" | IDENTIFIER
*/
#[derive(Clone, PartialEq)]
pub enum Expr {
Literal {
value: BaseValue,
value: Box<BaseValue>,
},
Binary {
left: Box<AstNode<Expr>>,
left: Box<AstNode>,
operator: TokenType,
right: Box<AstNode<Expr>>,
right: Box<AstNode>,
},
Unary {
operator: TokenType,
operand: Box<AstNode<Expr>>,
operand: Box<AstNode>,
},
Grouping {
expression: Box<AstNode<Expr>>,
expression: Box<AstNode>,
},
Identifier {
name: String,
},
Call {
callee: Box<AstNode<Expr>>,
arguments: Vec<AstNode<Expr>>,
callee: Box<AstNode>,
arguments: Vec<AstNode>,
},
Assign {
name: String,
value: Box<AstNode<Expr>>,
value: Box<AstNode>,
},
Print {
expression: Box<AstNode>,
},
VarDeclaration {
name: String,
var_type: Type,
initializer: Option<Box<AstNode>>,
},
Return {
expression: Box<AstNode>,
label: String,
},
Block {
statements: Box<Vec<AstNode>>,
label: String,
},
If {
condition: Box<AstNode>,
then_branch: Box<AstNode>,
elif_branches: Vec<(Box<AstNode>, Box<AstNode>)>,
else_branch: Option<Box<AstNode>>,
},
While {
condition: Box<AstNode>,
body: Box<AstNode>,
},
For {
variable: Box<AstNode>,
condition: Box<AstNode>,
increment: Box<AstNode>,
body: Box<AstNode>,
},
}
@@ -95,8 +96,10 @@ impl std::fmt::Display for Expr {
right,
} => write!(f, "Binary ({} {} {})", left.node, operator, right.node),
Expr::Unary { operator, operand } => write!(f, "Unary ({} {})", operator, operand.node),
Expr::Grouping { expression } => write!(f, "Grouping (group {})", expression.node),
Expr::Identifier { name } => write!(f, "Identifier (variable {})", name),
Expr::Grouping { expression } => write!(f, "Grouping (group {})", expression.node,),
Expr::Identifier { name } => {
write!(f, "Identifier (variable {})", name)
}
Expr::Call { callee, arguments } => write!(
f,
"Call ({}({}))",
@@ -108,6 +111,59 @@ impl std::fmt::Display for Expr {
.join(", ")
),
Expr::Assign { name, value } => write!(f, "Assign ({} = {})", name, value.node),
Expr::If {
condition,
then_branch,
elif_branches,
else_branch,
} => {
let mut result = format!("IF ({}) {{\n{}\n}}", condition.node, then_branch.node);
for (condition, branch) in elif_branches {
result.push_str(&format!(
" ELIF ({}) {{\n{}\n}}",
condition.node, branch.node,
));
}
if let Some(else_branch) = else_branch {
result.push_str(&format!(" ELSE {{\n{}\n}}", else_branch.node));
}
write!(f, "IfStmt {}", result)
}
Expr::Print { expression } => write!(f, "Print({})", expression.node),
Expr::VarDeclaration {
name,
initializer,
var_type,
} => match initializer {
Some(init) => write!(f, "Var({} : {:?} = {})", name, var_type, init.node),
None => write!(f, "Var({} : {:?})", name, var_type),
},
Expr::Return { expression, label } => {
write!(f, "Return({}, {})", expression.node, label)
}
Expr::Block { statements, label } => write!(
f,
"Block [{}] ([\n{}\n])",
label,
statements
.iter()
.map(|stmt| format!("\t \t{}", stmt.node))
.collect::<Vec<_>>()
.join("\n"),
),
Expr::While { condition, body } => {
write!(f, "While({}) {{\n{}\n}}", condition.node, body.node)
}
Expr::For {
variable,
condition,
increment,
body,
} => write!(
f,
"For({} = {} in {}) {{\n{}\n}}",
variable.node, condition.node, increment.node, body.node
),
}
}
}
@@ -115,15 +171,21 @@ impl std::fmt::Display for Expr {
impl Debug for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expr::Literal { value } => write!(f, "{:?}", value),
Expr::Literal { value } => write!(f, "{:?} ", value,),
Expr::Binary {
left,
operator,
right,
} => write!(f, "({:?} {:?} {:?})", operator, left.node, right.node),
Expr::Unary { operator, operand } => write!(f, "({:?} {:?})", operator, operand.node),
Expr::Grouping { expression } => write!(f, "(group {:?})", expression.node),
Expr::Identifier { name } => write!(f, "(variable {:?})", name),
} => write!(f, "({:?} {:?} {:?}) ", operator, left.node, right.node,),
Expr::Unary { operator, operand } => {
write!(f, "(Unary {:?} {:?}) ", operator, operand.node,)
}
Expr::Grouping { expression } => {
write!(f, "(Grouping {:?})", expression.node,)
}
Expr::Identifier { name } => {
write!(f, "(variable {:?})", name,)
}
Expr::Call { callee, arguments } => write!(
f,
"Call ({}({}))",
@@ -132,306 +194,90 @@ impl Debug for Expr {
.iter()
.map(|arg| arg.node.to_string())
.collect::<Vec<String>>()
.join(", ")
.join(", "),
),
Expr::Assign { name, value } => write!(f, "(assign {:?} {:?})", name, value.node),
}
}
}
#[derive(Clone, PartialEq)]
pub enum Stmt {
Expression {
expression: Box<AstNode<Expr>>,
return_value: Box<BaseValue>,
},
Print {
expression: Box<AstNode<Expr>>,
return_value: Box<BaseValue>,
},
VarDeclaration {
name: String,
initializer: Option<Box<AstNode<Expr>>>,
return_value: Box<BaseValue>,
},
Return {
expression: Box<AstNode<Expr>>,
label: String,
return_value: Box<BaseValue>,
},
Block {
statements: Box<Vec<AstNode<Stmt>>>,
label: String,
return_value: Box<BaseValue>,
},
If {
condition: Box<AstNode<Expr>>,
then_branch: Box<AstNode<Stmt>>,
elif_branch: Vec<(Box<AstNode<Expr>>, Box<AstNode<Stmt>>)>,
else_branch: Option<Box<AstNode<Stmt>>>,
return_value: Box<BaseValue>,
},
While {
condition: Box<AstNode<Expr>>,
body: Box<AstNode<Stmt>>,
return_value: Box<BaseValue>,
},
For {
variable: Box<AstNode<Stmt>>,
condition: Box<AstNode<Expr>>,
increment: Box<AstNode<Stmt>>,
body: Box<AstNode<Stmt>>,
return_value: Box<BaseValue>,
},
}
impl Display for Stmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Stmt::Expression {
expression,
return_value,
} => write!(f, "Expression ({}) -> {:?}", expression.node, return_value),
Stmt::If {
Expr::Assign { name, value } => {
write!(f, "(assign {:?} {:?})", name, value.node,)
}
Expr::If {
condition,
then_branch,
elif_branch,
elif_branches,
else_branch,
return_value,
} => {
let mut result = format!("IF ({}) {{\n{}\n}}", condition.node, then_branch.node);
for (condition, branch) in elif_branch {
let mut result =
format!("IF ({:?}) {{\n{:?}\n}}", condition.node, then_branch.node,);
for (condition, branch) in elif_branches {
result.push_str(&format!(
" ELIF ({}) {{\n{}\n}} -> {:?}",
condition.node, branch.node, return_value
" ELIF ({:?}) {{\n{:?}\n}}",
condition.node, branch.node,
));
}
if let Some(else_branch) = else_branch {
result.push_str(&format!(
" ELSE {{\n{}\n}} -> {:?}",
else_branch.node, return_value
));
}
write!(f, "IfStmt {}", result)
}
Stmt::Print {
expression,
return_value,
} => write!(f, "Print({}) -> {:?};", expression.node, return_value),
Stmt::VarDeclaration {
name,
initializer,
return_value,
} => match initializer {
Some(init) => write!(f, "Var({} = {}) -> {:?};", name, init.node, return_value),
None => write!(f, "Var({}) -> {:?};", name, return_value),
},
Stmt::Return {
expression,
return_value,
label,
} => write!(
f,
"Return({}, {}) -> {:?};",
expression.node, label, return_value
),
Stmt::Block {
statements,
label,
return_value,
} => write!(
f,
"Block [{}] ([\n{}\n]) -> {:?}",
label,
statements
.iter()
.map(|stmt| format!("\t \t{}", stmt.node))
.collect::<Vec<_>>()
.join("\n"),
return_value
),
Stmt::While {
condition,
body,
return_value,
} => {
write!(
f,
"While({}) {{\n{}\n}} -> {:?}",
condition.node, body.node, return_value
)
}
Stmt::For {
variable,
condition,
increment,
body,
return_value,
} => write!(
f,
"For({} = {} in {}) {{\n{}\n}} -> {:?}",
variable.node, condition.node, increment.node, body.node, return_value
),
}
}
}
impl Debug for Stmt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Stmt::Expression {
expression,
return_value,
} => write!(
f,
" Expression ({:?}) -> {:?}",
expression.node, return_value
),
Stmt::If {
condition,
then_branch,
elif_branch,
else_branch,
return_value,
} => {
let mut result = format!(
"IF ({:?}) {{\n{:?}\n}} -> {:?} ",
condition.node, then_branch.node, return_value
);
for (condition, branch) in elif_branch {
result.push_str(&format!(
" ELIF ({:?}) {{\n{:?}\n}} -> {:?} ",
condition.node, branch.node, return_value
));
}
if let Some(else_branch) = else_branch {
result.push_str(&format!(
" ELSE {{\n{:?}\n}} -> {:?}",
else_branch.node, return_value
));
result.push_str(&format!(" ELSE {{\n{:?}\n}}", else_branch.node,));
}
write!(f, "IfStmt {:?}", result)
}
Stmt::Print {
expression,
return_value,
} => write!(f, "Print({:?}) -> {:?};", expression.node, return_value),
Stmt::VarDeclaration {
Expr::Print { expression } => {
write!(f, "Print({:?});", expression.node,)
}
Expr::VarDeclaration {
name,
initializer,
return_value,
var_type,
} => match initializer {
Some(init) => write!(
f,
"Var({:?} = {:?}) -> {:?};",
name, init.node, return_value
),
None => write!(f, "Var({:?}) -> {:?};", name, return_value),
Some(init) => write!(f, "Var({:?}: {:?} = {:?});", name, var_type, init.node,),
None => write!(f, "Var({:?}: {:?});", name, var_type,),
},
Stmt::Return {
expression,
return_value,
label,
} => write!(
Expr::Return { expression, label } => {
write!(f, "Return({:?}, {}) ;", expression.node, label,)
}
Expr::Block { label, statements } => write!(
f,
"Return({:?}, {}) -> {:?};",
expression.node, label, return_value
),
Stmt::Block {
label,
statements,
return_value,
} => write!(
f,
"Block [{}] ([\n{:?}\n]) -> {:?}",
"Block [{}] ([\n{:?}\n])",
label,
statements
.iter()
.map(|stmt| format!("{:?}", stmt.node))
.collect::<Vec<_>>()
.join("\t\t\n"),
return_value
),
Stmt::While {
condition,
body,
return_value,
} => {
write!(
f,
"While({:?}) {{\n{:?}\n}} -> {:?}",
condition.node, body.node, return_value
)
Expr::While { condition, body } => {
write!(f, "While({:?}) {{\n{:?}\n}}", condition.node, body.node,)
}
Stmt::For {
Expr::For {
variable,
condition,
increment,
body,
return_value,
} => write!(
f,
"For({:?} = {:?} in {:?}) {{\n{:?}\n}} -> {:?}",
variable.node, condition.node, increment.node, body.node, return_value
"For({:?} = {:?} in {:?}) {{\n{:?}\n}} ",
variable.node, condition.node, increment.node, body.node,
),
}
}
}
pub trait AstNodeKind {
fn kind(&self) -> &'static str;
}
impl AstNodeKind for Expr {
fn kind(&self) -> &'static str {
match self {
Expr::Literal { value: _ } => "literal",
Expr::Binary {
left: _,
operator: _,
right: _,
} => "binary expression",
Expr::Unary { .. } => "unary expression",
Expr::Grouping { .. } => "grouping expression",
Expr::Identifier { .. } => "variable expression",
Expr::Call { .. } => "call expression",
Expr::Assign { .. } => "assignment expression",
}
}
}
impl AstNodeKind for Stmt {
fn kind(&self) -> &'static str {
match self {
Stmt::Expression { .. } => "expression",
Stmt::VarDeclaration { .. } => "variable declaration",
Stmt::Return { .. } => "return statement",
Stmt::Block { .. } => "block statement",
Stmt::If { .. } => "if statement",
Stmt::Print { .. } => "print statement",
Stmt::While { .. } => "while statement",
Stmt::For { .. } => "for statement",
}
}
}
#[derive(Clone)]
pub struct AstNode<T: AstNodeKind + Debug + Display> {
pub struct AstNode {
/// Stable identity, assigned at construction and preserved across clones.
pub id: NodeId,
pub node: T,
pub node: Expr,
pub is_statement: bool,
pub source_slice: SourceSlice,
pub return_type: Type,
}
// Identity (`id`) deliberately does not participate in equality: two nodes are
// equal when their content and location match, regardless of node id.
impl<T: AstNodeKind + Debug + Display + PartialEq> PartialEq for AstNode<T> {
impl PartialEq for AstNode {
fn eq(&self, other: &Self) -> bool {
self.node == other.node && self.source_slice == other.source_slice
}
}
impl<T: AstNodeKind + Debug + Display> Display for AstNode<T> {
impl Display for AstNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
@@ -441,7 +287,7 @@ impl<T: AstNodeKind + Debug + Display> Display for AstNode<T> {
}
}
impl<T: AstNodeKind + Debug + Display> Debug for AstNode<T> {
impl Debug for AstNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
@@ -451,12 +297,22 @@ impl<T: AstNodeKind + Debug + Display> Debug for AstNode<T> {
}
}
impl<T: AstNodeKind + Debug + Display> AstNode<T> {
pub fn new(node: T, source_slice: SourceSlice) -> Self {
impl AstNode {
fn new(node: Expr, source_slice: SourceSlice, type_name: String, is_statement: bool) -> Self {
AstNode {
id: NodeId::next(),
node,
is_statement,
source_slice,
return_type: Type::Unresolved(type_name),
}
}
pub fn new_statement(node: Expr, source_slice: SourceSlice) -> Self {
Self::new(node, source_slice, "Nil".to_string(), true)
}
pub fn new_expression(node: Expr, source_slice: SourceSlice, type_name: String) -> Self {
Self::new(node, source_slice, type_name, false)
}
}
+28 -17
View File
@@ -1,12 +1,12 @@
use core::fmt;
use std::collections::HashMap;
use std::fmt::Display;
use std::ops::{Add, Div, Mul, Not, Rem, Sub};
use crate::backend::environment::Environment;
use crate::common::lox_result::{runtime_error, LoxResult};
use crate::common::types::Type;
use crate::{
backend::environment::EnvironmentStack,
common::ast::{AstNode, Expr, Stmt},
backend::environment::EnvironmentStack, common::ast::AstNode,
frontend::source_registry::SourceSlice,
};
#[derive(Debug, Clone, PartialEq)]
@@ -272,15 +272,20 @@ pub enum BaseValue {
Nil,
Function(LoxFunction),
NativeFunction(NativeFunction),
Struct(Struct),
}
struct Dict {
map: HashMap<String, BaseValue>,
}
struct ReturnValue {
label: Vec<String>,
value: BaseValue,
value: Type,
}
impl ReturnValue {
pub fn new(label: Vec<String>, value: BaseValue) -> Self {
pub fn new(label: Vec<String>, value: Type) -> Self {
Self { label, value }
}
}
@@ -304,39 +309,40 @@ impl Display for BaseValue {
BaseValue::Nil => write!(f, "nil"),
BaseValue::Function(..) => write!(f, "<fn lox function>"),
BaseValue::NativeFunction(..) => write!(f, "<native native function>"),
BaseValue::Struct(_) => write!(f, "<struct>"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LoxFunction {
pub parameters: Vec<(String, String)>,
pub return_type: Option<String>,
pub body: AstNode<Stmt>,
pub parameters: Vec<(String, Type)>,
pub return_type: Type,
pub body: AstNode,
pub closure: Option<EnvironmentStack<BaseValue>>,
pub guard: Option<Box<AstNode<Expr>>>,
pub guard: Option<Box<AstNode>>,
}
impl LoxFunction {
pub fn new(
parameters: Vec<(String, String)>,
body: AstNode<Stmt>,
parameters: Vec<(String, Type)>,
body: AstNode,
closure: Option<EnvironmentStack<BaseValue>>,
guard: Option<Box<AstNode<Expr>>>,
guard: Option<Box<AstNode>>,
) -> Self {
LoxFunction {
parameters,
return_type: None,
return_type: Type::Any,
body,
closure,
guard,
}
}
pub fn anonymous_function(parameters: Vec<(String, String)>, body: AstNode<Stmt>) -> Self {
pub fn anonymous_function(parameters: Vec<(String, Type)>, body: AstNode) -> Self {
LoxFunction {
parameters,
return_type: None,
return_type: Type::Any,
body,
closure: None,
guard: None,
@@ -346,12 +352,12 @@ impl LoxFunction {
#[derive(Debug, Clone, PartialEq)]
pub struct NativeFunction {
pub parameters: Vec<(String, String)>,
pub parameters: Vec<(String, Type)>,
pub function: fn(&[BaseValue]) -> BaseValue,
}
impl NativeFunction {
pub fn new(parameters: Vec<(String, String)>, function: fn(&[BaseValue]) -> BaseValue) -> Self {
pub fn new(parameters: Vec<(String, Type)>, function: fn(&[BaseValue]) -> BaseValue) -> Self {
NativeFunction {
parameters,
function,
@@ -359,6 +365,11 @@ impl NativeFunction {
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Struct {
pub fields: Vec<(String, BaseValue)>,
}
// Trait implementations for BaseValue
pub trait Truthy {
+1
View File
@@ -1,3 +1,4 @@
pub mod ast;
pub mod base_value;
pub mod lox_result;
pub mod types;
+70
View File
@@ -0,0 +1,70 @@
use std::{fmt::Display, rc::Rc};
#[derive(Debug, Clone, PartialEq)]
pub enum Type {
Any,
Number,
String,
Boolean,
Nil,
Function(FunctionType),
Struct(Rc<StructType>),
Unresolved(String),
}
impl Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Type::Any => write!(f, "any"),
Type::Number => write!(f, "number"),
Type::String => write!(f, "string"),
Type::Boolean => write!(f, "boolean"),
Type::Nil => write!(f, "nil"),
Type::Function(fun) => write!(f, "{}", fun),
Type::Struct(struct_) => write!(f, "{}", struct_),
Type::Unresolved(name) => write!(f, "{}", name),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionType {
pub params: Vec<(String, Box<Type>)>,
pub return_type: Box<Type>,
}
impl Display for FunctionType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let rendered_params = self
.params
.iter()
.map(|(name, ty)| format!("{}: {}", name, ty))
.collect::<Vec<_>>()
.join(", ");
write!(f, "fn({}) -> {}", rendered_params, self.return_type)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StructType {
pub fields: Vec<(String, Box<Type>)>,
pub methods: Vec<(String, FunctionType)>,
}
impl Display for StructType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let rendered_field = self
.fields
.iter()
.map(|(name, ty)| format!("{}: {}", name, ty))
.collect::<Vec<_>>()
.join(", ");
let rendered_method = self
.methods
.iter()
.map(|(name, ty)| format!("{}: {}", name, ty))
.collect::<Vec<_>>()
.join(", ");
write!(f, "struct {{ {}, {} }}", rendered_field, rendered_method)
}
}