separate typed and untyped ASTs

This commit is contained in:
Romain Paquet 2023-10-16 22:22:10 +02:00
parent 91148b1a20
commit 86d4f7fffb
14 changed files with 512 additions and 262 deletions

92
src/typing/error.rs Normal file
View file

@ -0,0 +1,92 @@
use crate::typing::{BinaryOperator, Identifier, ModulePath, Type, TypeContext};
#[derive(Debug)]
pub struct TypeError {
file: Option<std::path::PathBuf>,
module: ModulePath,
function: Option<String>,
kind: TypeErrorKind,
}
impl std::fmt::Display for TypeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Error\n")?;
if let Some(path) = &self.file {
f.write_fmt(format_args!(" in file {}\n", path.display()))?;
}
f.write_fmt(format_args!(" in module {}\n", self.module))?;
if let Some(name) = &self.function {
f.write_fmt(format_args!(" in function {}\n", name))?;
}
f.write_fmt(format_args!("{:#?}", self.kind))?;
Ok(())
}
}
#[derive(Default)]
pub struct TypeErrorBuilder {
file: Option<std::path::PathBuf>,
module: Option<ModulePath>,
function: Option<String>,
kind: Option<TypeErrorKind>,
}
impl TypeError {
pub fn builder() -> TypeErrorBuilder {
TypeErrorBuilder::default()
}
}
impl TypeErrorBuilder {
pub fn context(mut self, ctx: &TypeContext) -> Self {
self.file = ctx.file.clone();
self.module = Some(ctx.module.clone());
self.function = ctx.function.clone();
self
}
pub fn kind(mut self, kind: TypeErrorKind) -> Self {
self.kind = Some(kind);
self
}
pub fn build(self) -> TypeError {
TypeError {
file: self.file,
module: self.module.expect("TypeError builder is missing module"),
function: self.function,
kind: self.kind.expect("TypeError builder is missing kind"),
}
}
}
#[derive(Debug)]
pub enum TypeErrorKind {
InvalidBinaryOperator {
operator: BinaryOperator,
lht: Type,
rht: Type,
},
BlockTypeDoesNotMatchFunctionType {
block_type: Type,
function_type: Type,
},
ReturnTypeDoesNotMatchFunctionType {
function_type: Type,
return_type: Type,
},
UnknownIdentifier {
identifier: String,
},
AssignmentMismatch {
lht: Type,
rht: Type,
},
AssignUndeclared,
VariableRedeclaration,
ReturnStatementsMismatch,
UnknownFunctionCalled(Identifier),
WrongFunctionArguments,
ConditionIsNotBool,
IfElseMismatch,
}

View file

@ -1,9 +1,11 @@
use std::collections::HashMap;
use crate::ast::{
module::{Module, ModulePath},
*,
};
use crate::ast::untyped::*;
use crate::ast::untyped::module::Module;
use crate::ast::ModulePath;
mod error;
use crate::typing::error::{TypeError, TypeErrorKind};
#[derive(Debug, PartialEq, Clone)]
pub enum Type {
@ -25,22 +27,22 @@ impl From<&str> for Type {
}
}
impl FunctionDefinition {
impl untyped::FunctionDefinition {
fn signature(&self) -> (Vec<Type>, Type) {
let return_type = self.return_type.unwrap_or(Type::Unit);
let params_types = self.parameters.iter().map(|p| p.typ).collect();
let return_type = self.return_type.clone().unwrap_or(Type::Unit);
let params_types = self.parameters.iter().map(|p| p.typ.clone()).collect();
(params_types, return_type)
}
}
impl Module {
pub fn type_check(&self) -> Result<(), TypeError> {
let mut ctx = TypeContext::new(self.path);
let mut ctx = TypeContext::new(self.path.clone());
ctx.file = self.file.clone();
// Register all function signatures
for Definition::FunctionDefinition(func) in &self.definitions {
if let Some(previous) = ctx.functions.insert(func.name.clone(), func.signature()) {
if let Some(_previous) = ctx.functions.insert(func.name.clone(), func.signature()) {
todo!("handle redefinition of function or identical function names across different files");
}
}
@ -50,103 +52,13 @@ impl Module {
// Type-check the function bodies
for Definition::FunctionDefinition(func) in &self.definitions {
func.typ(&mut ctx)?;
ctx.variables.clear();
}
Ok(())
}
}
#[derive(Debug)]
pub struct TypeError {
file: Option<std::path::PathBuf>,
module: ModulePath,
function: Option<String>,
kind: TypeErrorKind,
}
impl std::fmt::Display for TypeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Error\n")?;
if let Some(path) = &self.file {
f.write_fmt(format_args!(" in file {}\n", path.display()))?;
}
f.write_fmt(format_args!(" in module {}\n", self.module))?;
if let Some(name) = &self.function {
f.write_fmt(format_args!(" in function {}\n", name))?;
}
f.write_fmt(format_args!("{:#?}", self.kind))?;
Ok(())
}
}
#[derive(Default)]
struct TypeErrorBuilder {
file: Option<std::path::PathBuf>,
module: Option<ModulePath>,
function: Option<String>,
kind: Option<TypeErrorKind>,
}
impl TypeError {
fn builder() -> TypeErrorBuilder {
TypeErrorBuilder::default()
}
}
impl TypeErrorBuilder {
fn context(mut self, ctx: &TypeContext) -> Self {
self.file = ctx.file.clone();
self.module = Some(ctx.module.clone());
self.function = ctx.function.clone();
self
}
fn kind(mut self, kind: TypeErrorKind) -> Self {
self.kind = Some(kind);
self
}
fn build(self) -> TypeError {
TypeError {
file: self.file,
module: self.module.expect("TypeError builder is missing module"),
function: self.function,
kind: self.kind.expect("TypeError builder is missing kind"),
}
}
}
#[derive(Debug)]
pub enum TypeErrorKind {
InvalidBinaryOperator {
operator: BinaryOperator,
lht: Type,
rht: Type,
},
BlockTypeDoesNotMatchFunctionType {
block_type: Type,
function_type: Type,
},
ReturnTypeDoesNotMatchFunctionType {
function_type: Type,
return_type: Type,
},
UnknownIdentifier {
identifier: String,
},
AssignmentMismatch {
lht: Type,
rht: Type,
},
AssignUndeclared,
VariableRedeclaration,
ReturnStatementsMismatch,
UnknownFunctionCalled(Identifier),
WrongFunctionArguments,
ConditionIsNotBool,
IfElseMismatch,
}
pub struct TypeContext {
pub file: Option<std::path::PathBuf>,
pub module: ModulePath,
@ -157,36 +69,37 @@ pub struct TypeContext {
impl TypeContext {
pub fn new(path: ModulePath) -> Self {
TypeContext {
let builtin_functions =
HashMap::from([(String::from("println"), (vec![Type::Str], Type::Unit))]);
Self {
file: None,
module: path,
function: None,
functions: Default::default(),
functions: builtin_functions,
variables: Default::default(),
}
}
}
/// Trait for nodes which have a deducible type.
pub trait Typ {
pub trait TypeCheck {
/// Try to resolve the type of the node.
fn typ(&self, ctx: &mut TypeContext) -> Result<Type, TypeError>;
}
impl Typ for FunctionDefinition {
impl TypeCheck for FunctionDefinition {
fn typ(&self, ctx: &mut TypeContext) -> Result<Type, TypeError> {
let func = self;
ctx.function = Some(self.name.clone());
ctx.function = Some(func.name.clone());
for param in &func.parameters {
for param in &self.parameters {
ctx.variables.insert(param.name.clone(), param.typ.clone());
}
let body_type = &func.body.typ(ctx)?;
let body_type = &self.body.typ(ctx)?;
// If the return type is not specified, it is unit.
let func_return_type = match &func.return_type {
let func_return_type = match &self.return_type {
Some(typ) => typ,
None => &Type::Unit,
};
@ -203,7 +116,7 @@ impl Typ for FunctionDefinition {
}
// Check coherence with return statements.
for statement in &func.body.statements {
for statement in &self.body.statements {
if let Statement::ReturnStatement(value) = statement {
let ret_type = match value {
Some(expr) => expr.typ(ctx)?,
@ -225,7 +138,7 @@ impl Typ for FunctionDefinition {
}
}
impl Typ for Block {
impl TypeCheck for Block {
fn typ(&self, ctx: &mut TypeContext) -> Result<Type, TypeError> {
let mut return_typ: Option<Type> = None;
@ -320,9 +233,9 @@ impl Typ for Block {
}
}
impl Typ for Call {
impl TypeCheck for Call {
fn typ(&self, ctx: &mut TypeContext) -> Result<Type, TypeError> {
match &self.callee {
match &*self.callee {
Expr::Identifier(ident) => {
let signature = match ctx.functions.get(ident) {
Some(sgn) => sgn.clone(),
@ -356,7 +269,7 @@ impl Typ for Call {
}
}
impl Typ for Expr {
impl TypeCheck for Expr {
fn typ(&self, ctx: &mut TypeContext) -> Result<Type, TypeError> {
match self {
Expr::Identifier(identifier) => {
@ -426,6 +339,7 @@ impl Typ for Expr {
}
},
Expr::StringLiteral(_) => Ok(Type::Str),
Expr::UnitLiteral => Ok(Type::Unit),
Expr::Call(call) => call.typ(ctx),
Expr::Block(block) => block.typ(ctx),
Expr::IfExpr(cond, true_block, else_value) => {
@ -450,3 +364,115 @@ impl Typ for Expr {
}
}
}
struct Typed<T: TypeCheck> {
inner: T,
typ: Type,
}
trait IntoTyped<T: TypeCheck> {
fn into_typed(self: Self, ctx: &mut TypeContext) -> Result<Typed<T>, TypeError>;
}
impl IntoTyped<Block> for Block {
fn into_typed(self: Block, ctx: &mut TypeContext) -> Result<Typed<Block>, TypeError> {
let mut return_typ: Option<Type> = None;
// Check declarations and assignments.
for statement in &self.statements {
match statement {
Statement::DeclareStatement(ident, expr) => {
let typ = expr.typ(ctx)?;
if let Some(_typ) = ctx.variables.insert(ident.clone(), typ) {
// XXX: Shadowing? (illegal for now)
return Err(TypeError::builder()
.context(ctx)
.kind(TypeErrorKind::VariableRedeclaration)
.build());
}
}
Statement::AssignStatement(ident, expr) => {
let rhs_typ = expr.typ(ctx)?;
let Some(lhs_typ) = ctx.variables.get(ident) else {
return Err(TypeError::builder()
.context(ctx)
.kind(TypeErrorKind::AssignUndeclared)
.build());
};
// Ensure same type on both sides.
if rhs_typ != *lhs_typ {
return Err(TypeError::builder()
.context(ctx)
.kind(TypeErrorKind::AssignmentMismatch {
lht: lhs_typ.clone(),
rht: rhs_typ.clone(),
})
.build());
}
}
Statement::ReturnStatement(maybe_expr) => {
let expr_typ = if let Some(expr) = maybe_expr {
expr.typ(ctx)?
} else {
Type::Unit
};
if let Some(typ) = &return_typ {
if expr_typ != *typ {
return Err(TypeError::builder()
.context(ctx)
.kind(TypeErrorKind::ReturnStatementsMismatch)
.build());
}
} else {
return_typ = Some(expr_typ);
}
}
Statement::CallStatement(call) => {
call.typ(ctx)?;
}
Statement::UseStatement(_path) => {
// TODO: import the signatures (and types)
}
Statement::IfStatement(cond, block) => {
if cond.typ(ctx)? != Type::Bool {
return Err(TypeError::builder()
.context(ctx)
.kind(TypeErrorKind::ConditionIsNotBool)
.build());
}
block.typ(ctx)?;
}
Statement::WhileStatement(cond, block) => {
if cond.typ(ctx)? != Type::Bool {
return Err(TypeError::builder()
.context(ctx)
.kind(TypeErrorKind::ConditionIsNotBool)
.build());
}
block.typ(ctx)?;
}
}
}
// Check if there is an expression at the end of the block.
let typ = if let Some(expr) = &self.value {
expr.typ(ctx)?
} else {
Type::Unit
};
Ok(Typed { inner: self, typ })
// TODO/FIXME: find a way to return `return_typ` so that the
// top-level block (the function) can check if this return type
// (and eventually those from other block) matches the type of
// the function.
}
}