Browse Source

feat: basic type inference

github-actions
Garrit Franke 3 years ago
parent
commit
ce8ccce0b3
  1. 2
      examples/playground.sb
  2. 34
      src/parser/infer.rs
  3. 1
      src/parser/mod.rs
  4. 11
      src/parser/parser.rs

2
examples/playground.sb

@ -1,5 +1,5 @@
fn main() {
let x = (1 + (2 * 3))
let x = 2
println(x)
}

34
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<Type> {
match expr {
Expression::Int(_) => Some(Type::Int),
Expression::Bool(_) => Some(Type::Bool),
Expression::Str(_) => Some(Type::Str),
_ => None,
}
}

1
src/parser/mod.rs

@ -1,3 +1,4 @@
mod infer;
/**
* Copyright 2020 Garrit Franke
*

11
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<Program, String> {
self.parse_program()
let mut program = self.parse_program()?;
// infer types
infer(&mut program)?;
Ok(program)
}
pub(super) fn next(&mut self) -> Result<Token, String> {

Loading…
Cancel
Save