From 687d482853b55407db44869f05cbdae9d0d474f1 Mon Sep 17 00:00:00 2001 From: greg Date: Wed, 21 Feb 2018 04:32:17 -0800 Subject: [PATCH] More type implementing - WIP This has a borrowing bug currently --- TODO.md | 2 ++ src/schala_lang/typechecking.rs | 38 ++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/TODO.md b/TODO.md index 4f1e01b..4cc369d 100644 --- a/TODO.md +++ b/TODO.md @@ -40,3 +40,5 @@ struct CompilerPass { name: String, run: fn(PrevPass) -> NextPass } + +-change "Type...." names in parser.rs to "Anno..." for non-collision with names in typechecking.rs diff --git a/src/schala_lang/typechecking.rs b/src/schala_lang/typechecking.rs index 3f73c2d..4dbf209 100644 --- a/src/schala_lang/typechecking.rs +++ b/src/schala_lang/typechecking.rs @@ -7,14 +7,20 @@ pub struct TypeContext { } #[derive(Debug, PartialEq, Clone)] pub enum Type { Unit, + Const(TConst), + Void +} + +#[derive(Debug, PartialEq, Clone)] +pub enum TConst { Int, Float, StringT, Bool, - Custom(Rc), - Void + Custom(String), } + type TypeResult = Result; impl TypeContext { @@ -45,21 +51,33 @@ impl TypeContext { fn type_infer(&mut self, expr: &parsing::Expression) -> TypeResult { use self::parsing::Expression; use self::parsing::ExpressionType::*; - use self::Type::*; + use self::Type::*; use self::TConst::*; match expr { - &Expression(ref e, Some(ref ty)) => Err(format!("Anno not implemented")), + &Expression(ref e, Some(ref anno)) => { + let anno_ty = self.type_from_anno(anno)?; + let expr = Expression(*e, None); + let ty = self.type_infer(&expr)?; + self.unify(ty, anno_ty) + }, &Expression(ref e, None) => match e { - &IntLiteral(_) => Ok(Int), - &FloatLiteral(_) => Ok(Float), - &StringLiteral(_) => Ok(StringT), - &BoolLiteral(_) => Ok(Bool), + &IntLiteral(_) => Ok(Const(Int)), + &FloatLiteral(_) => Ok(Const(Float)), + &StringLiteral(_) => Ok(Const(StringT)), + &BoolLiteral(_) => Ok(Const(Bool)), _ => Err(format!("Type not yet implemented")) } } } - fn unify(&mut self, t1: Type, t2: Type) -> TypeResult { - use self::Type::*; + fn type_from_anno(&mut self, anno: &parsing::TypeName) -> TypeResult { + use self::Type::*; use self::TConst::*; Ok(Unit) } + fn unify(&mut self, t1: Type, t2: Type) -> TypeResult { + use self::Type::*; use self::TConst::*; + match (t1, t2) { + (Const(ref a), Const(ref b)) if a == b => Ok(Const(a.clone())), + (a, b) => Err(format!("Types {:?} and {:?} don't unify", a, b)) + } + } }