diff --git a/examples/playground.sb b/examples/playground.sb index 0000e32..7c788be 100644 --- a/examples/playground.sb +++ b/examples/playground.sb @@ -1,5 +1,5 @@ fn main() { - let x = (1 + (2 * 3)) + let x = 2 println(x) } \ No newline at end of file diff --git a/src/parser/infer.rs b/src/parser/infer.rs new file mode 100644 index 0000000..62efaca --- /dev/null +++ b/src/parser/infer.rs @@ -0,0 +1,34 @@ +use super::node_type::*; + +/// Try to infer types of variables +pub(super) fn infer(program: &mut Program) -> Result<(), String> { + // TODO: Fix aweful nesting + for func in &mut program.func { + if let Statement::Block(statements) = &mut func.body { + for statement in statements { + match statement { + Statement::Declare(var, expr) => { + if let None = &var.ty { + if let Some(e) = expr { + dbg!(&var); + var.ty = infer_expression(&e); + dbg!(&var); + } + } + } + _ => {} + } + } + } + } + Ok(()) +} + +fn infer_expression(expr: &Expression) -> Option { + match expr { + Expression::Int(_) => Some(Type::Int), + Expression::Bool(_) => Some(Type::Bool), + Expression::Str(_) => Some(Type::Str), + _ => None, + } +} diff --git a/src/parser/mod.rs b/src/parser/mod.rs index d8e1ff4..e12f180 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -1,3 +1,4 @@ +mod infer; /** * Copyright 2020 Garrit Franke * diff --git a/src/parser/parser.rs b/src/parser/parser.rs index c92b412..794a701 100644 --- a/src/parser/parser.rs +++ b/src/parser/parser.rs @@ -1,3 +1,5 @@ +use crate::lexer::Keyword; +use crate::lexer::{Token, TokenKind}; /** * Copyright 2020 Garrit Franke * @@ -13,8 +15,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -use crate::lexer::Keyword; -use crate::lexer::{Token, TokenKind}; +use crate::parser::infer::infer; use crate::parser::node_type::*; use crate::util::string_util::highlight_position_in_file; use std::convert::TryFrom; @@ -45,7 +46,11 @@ impl Parser { } pub fn parse(&mut self) -> Result { - self.parse_program() + let mut program = self.parse_program()?; + // infer types + infer(&mut program)?; + + Ok(program) } pub(super) fn next(&mut self) -> Result {