use std::{collections::HashMap, ops::Deref}; use ecow::{EcoString, eco_format}; use num_bigint::BigInt; use vec1::Vec1; use crate::{ast, exhaustiveness, parse, type_}; #[derive(Debug, PartialEq, Eq, Default)] pub struct Module { pub functions: Vec, } #[derive(Debug, PartialEq, Eq)] pub struct Function { pub name: EcoString, pub return_type: Type, pub parameters: Vec, pub body: Expression, } #[derive(Debug, PartialEq, Eq)] pub struct FunctionParameter { pub type_: Type, pub name: Option, } #[derive(Debug, Default, PartialEq, Eq)] pub struct Translator { module: Module, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Type { Int, Float, Bool, Generic, } #[derive(Debug, PartialEq, Eq, Clone)] pub struct Var { pub name: EcoString, } #[derive(Debug, PartialEq, Eq, Clone)] pub enum Expression { Block(Vec), FunctionRef { module: EcoString, name: EcoString, }, Var(Var), Int { value: BigInt, }, Equals { lhs: Box, rhs: Box, }, IntAdd { lhs: Box, rhs: Box, }, IntSub { lhs: Box, rhs: Box, }, Set { name: Var, value: Box, }, If { cond: Box, then: Box, else_: Box, }, Call { target: Box, args: Vec, }, } impl Translator { pub fn translate(mut self, module: &ast::TypedModule) -> Module { for definition in &module.definitions { match definition { ast::Definition::Function(function) => { self.module .functions .push(Self::translate_function(function)); } ast::Definition::TypeAlias(_type_alias) => todo!(), ast::Definition::CustomType(_custom_type) => todo!(), ast::Definition::Import(_import) => todo!(), ast::Definition::ModuleConstant(_module_constant) => todo!(), } } self.module } fn translate_function(function: &ast::TypedFunction) -> Function { let (_, name) = function.name.clone().expect("function should have a name"); let return_type = Self::translate_type(&function.return_type); let parameters = Iterator::collect(function.arguments.iter().map(|argument| { let name = argument.get_variable_name().cloned(); let type_ = Self::translate_type(&argument.type_); FunctionParameter { name, type_ } })); let mut translator = BodyTranslator::default(); for argument in &function.arguments { if let Some(name) = argument.get_variable_name() { _ = translator.make_var(name.clone()); } } let body = translator.translate(&function.body); let body = Self::flatten_expression(body); let body = Self::remove_unused_code(body); Function { name, body, return_type, parameters, } } fn translate_type(type_: &type_::Type) -> Type { match type_ { type_::Type::Named { publicity: _, package: _, module, name, arguments: _, inferred_variant: _, } => match (module.as_str(), name.as_str()) { ("gleam", "Int") => Type::Int, ("gleam", "Float") => Type::Float, ("gleam", "Bool") => Type::Bool, (_, _) => todo!(), }, type_::Type::Fn { arguments: _, return_: _, } => todo!(), type_::Type::Var { type_ } => match type_.borrow().deref() { type_::TypeVar::Link { type_ } => Self::translate_type(type_), type_::TypeVar::Unbound { id: _ } | type_::TypeVar::Generic { id: _ } => { Type::Generic } }, type_::Type::Tuple { elements: _ } => todo!(), } } fn flatten_expression(expression: Expression) -> Expression { match expression { Expression::Block(expressions) => { let mut block = vec![]; for expression in expressions { let expression = Self::flatten_expression(expression); match expression { Expression::Block(mut expressions) => block.append(&mut expressions), Expression::Var { .. } | Expression::FunctionRef { .. } | Expression::Int { .. } | Expression::Equals { .. } | Expression::IntAdd { .. } | Expression::IntSub { .. } | Expression::Set { .. } | Expression::If { .. } | Expression::Call { .. } => block.push(expression), }; } match block.as_slice() { [single] => single.clone(), _ => Expression::Block(block), } } Expression::FunctionRef { module, name } => Expression::FunctionRef { module, name }, Expression::Var(var) => Expression::Var(var), Expression::Int { value } => Expression::Int { value }, Expression::Equals { lhs, rhs } => Expression::Equals { lhs: Box::new(Self::flatten_expression(*lhs)), rhs: Box::new(Self::flatten_expression(*rhs)), }, Expression::IntAdd { lhs, rhs } => Expression::IntAdd { lhs: Box::new(Self::flatten_expression(*lhs)), rhs: Box::new(Self::flatten_expression(*rhs)), }, Expression::IntSub { lhs, rhs } => Expression::IntSub { lhs: Box::new(Self::flatten_expression(*lhs)), rhs: Box::new(Self::flatten_expression(*rhs)), }, Expression::Set { name, value } => Expression::Set { name, value: Box::new(Self::flatten_expression(*value)), }, Expression::If { cond, then, else_ } => Expression::If { cond: Box::new(Self::flatten_expression(*cond)), then: Box::new(Self::flatten_expression(*then)), else_: Box::new(Self::flatten_expression(*else_)), }, Expression::Call { target, args } => Expression::Call { target: Box::new(Self::flatten_expression(*target)), args: args.into_iter().map(Self::flatten_expression).collect(), }, } } fn remove_unused_code(expression: Expression) -> Expression { match expression { Expression::Block(expressions) => { let mut block = vec![]; let last_expression_index = expressions.len() - 1; for (index, expression) in expressions.into_iter().enumerate() { let expression = Self::remove_unused_code(expression); match expression { Expression::Var { .. } | Expression::FunctionRef { .. } if index != last_expression_index => {} Expression::Block(_) | Expression::FunctionRef { .. } | Expression::Var { .. } | Expression::Int { .. } | Expression::Equals { .. } | Expression::IntAdd { .. } | Expression::IntSub { .. } | Expression::Set { .. } | Expression::If { .. } | Expression::Call { .. } => block.push(expression), } } match block.as_slice() { [single] => single.clone(), _ => Expression::Block(block), } } Expression::FunctionRef { module, name } => Expression::FunctionRef { module, name }, Expression::Var(var) => Expression::Var(var), Expression::Int { value } => Expression::Int { value }, Expression::Equals { lhs, rhs } => Expression::Equals { lhs: Box::new(Self::remove_unused_code(*lhs)), rhs: Box::new(Self::remove_unused_code(*rhs)), }, Expression::IntAdd { lhs, rhs } => Expression::IntAdd { lhs: Box::new(Self::remove_unused_code(*lhs)), rhs: Box::new(Self::remove_unused_code(*rhs)), }, Expression::IntSub { lhs, rhs } => Expression::IntSub { lhs: Box::new(Self::remove_unused_code(*lhs)), rhs: Box::new(Self::remove_unused_code(*rhs)), }, Expression::Set { name, value } => Expression::Set { name, value: Box::new(Self::remove_unused_code(*value)), }, Expression::If { cond, then, else_ } => Expression::If { cond: Box::new(Self::remove_unused_code(*cond)), then: Box::new(Self::remove_unused_code(*then)), else_: Box::new(Self::remove_unused_code(*else_)), }, Expression::Call { target, args } => Expression::Call { target: Box::new(Self::remove_unused_code(*target)), args: args.into_iter().map(Self::remove_unused_code).collect(), }, } } } #[derive(Debug, Default)] pub struct BodyTranslator { variables: HashMap, variable_count: usize, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum DecisionKind { Case, Let, } impl BodyTranslator { fn make_tmp_var(&mut self) -> Var { self.make_var("_tmp".into()) } fn make_var(&mut self, name: EcoString) -> Var { self.variable_count += 1; let entry = eco_format!("{}${}", name.clone(), self.variable_count); _ = self.variables.insert(name.clone(), entry.clone()); Var { name: entry } } fn get_var(&mut self, name: &EcoString) -> Var { let variable = self .variables .get(name) .cloned() .unwrap_or_else(|| panic!("variable '{name}' not found")); Var { name: variable } } fn in_var_scope(&mut self, func: impl Fn(&mut Self) -> T) -> T { let snapshot = self.variables.clone(); let result = func(self); self.variables = snapshot; result } fn translate(mut self, body: &Vec1) -> Expression { self.translate_statements(body) } fn translate_statements(&mut self, statements: &[ast::TypedStatement]) -> Expression { Expression::Block(Iterator::collect( statements.iter().map(|stmt| self.translate_statement(stmt)), )) } fn translate_statement(&mut self, statement: &ast::TypedStatement) -> Expression { match statement { ast::Statement::Expression(expression) => self.translate_expression(expression), ast::Statement::Assignment(assignment) => self.translate_assignment(assignment), ast::Statement::Use(_) => todo!(), ast::Statement::Assert(_) => todo!(), } } fn translate_expression(&mut self, expression: &ast::TypedExpr) -> Expression { match expression { ast::TypedExpr::Int { location: _, type_: _, value: _, int_value, } => Expression::Int { value: int_value.clone(), }, ast::TypedExpr::Float { location: _, type_: _, value: _, } => todo!(), ast::TypedExpr::String { location: _, type_: _, value: _, } => todo!(), ast::TypedExpr::Block { location: _, statements, } => self.in_var_scope(|this| this.translate_statements(statements)), ast::TypedExpr::Pipeline { location: _, first_value: _, assignments: _, finally: _, finally_kind: _, } => todo!(), ast::TypedExpr::Var { location: _, constructor, name, } => match &constructor.variant { type_::ValueConstructorVariant::LocalVariable { location: _, origin: _, } => Expression::Var(self.get_var(name)), type_::ValueConstructorVariant::ModuleConstant { documentation: _, location: _, module: _, name: _, literal: _, implementations: _, } => todo!(), type_::ValueConstructorVariant::LocalConstant { literal: _ } => todo!(), type_::ValueConstructorVariant::ModuleFn { name, field_map: _, module, arity: _, location: _, documentation: _, implementations: _, external_erlang: _, external_javascript: _, external_cranelift: _, purity: _, } => Expression::FunctionRef { module: module.clone(), name: name.clone(), }, type_::ValueConstructorVariant::Record { name: _, arity: _, field_map: _, location: _, module: _, variants_count: _, variant_index: _, documentation: _, } => todo!(), }, ast::TypedExpr::Fn { location: _, type_: _, kind: _, arguments: _, body: _, return_annotation: _, purity: _, } => todo!(), ast::TypedExpr::List { location: _, type_: _, elements: _, tail: _, } => todo!(), ast::TypedExpr::Call { location: _, type_: _, fun, arguments, } => { let target = self.translate_expression(fun); let args = arguments .iter() .map(|arg| self.translate_expression(&arg.value)) .collect(); Expression::Call { target: Box::new(target), args, } } ast::TypedExpr::BinOp { location: _, type_: _, name, name_location: _, left, right, } => { let lhs = Box::new(self.translate_expression(left)); let rhs = Box::new(self.translate_expression(right)); match name { ast::BinOp::And => todo!(), ast::BinOp::Or => todo!(), ast::BinOp::Eq => Expression::Equals { lhs, rhs }, ast::BinOp::NotEq => todo!(), ast::BinOp::LtInt => todo!(), ast::BinOp::LtEqInt => todo!(), ast::BinOp::LtFloat => todo!(), ast::BinOp::LtEqFloat => todo!(), ast::BinOp::GtEqInt => todo!(), ast::BinOp::GtInt => todo!(), ast::BinOp::GtEqFloat => todo!(), ast::BinOp::GtFloat => todo!(), ast::BinOp::AddInt => Expression::IntAdd { lhs, rhs }, ast::BinOp::AddFloat => todo!(), ast::BinOp::SubInt => Expression::IntSub { lhs, rhs }, ast::BinOp::SubFloat => todo!(), ast::BinOp::MultInt => todo!(), ast::BinOp::MultFloat => todo!(), ast::BinOp::DivInt => todo!(), ast::BinOp::DivFloat => todo!(), ast::BinOp::RemainderInt => todo!(), ast::BinOp::Concatenate => todo!(), } } ast::TypedExpr::Case { location: _, type_: _, subjects, clauses, compiled_case, } => { let mut block = vec![]; let subject_vars: Vec<_> = Iterator::collect(subjects.iter().map(|subject| { let name = self.make_tmp_var(); let value = self.translate_expression(subject); block.push(Expression::Set { name: name.clone(), value: Box::new(value), }); return name; })); block.push(self.translate_decision( DecisionKind::Case, &subject_vars, clauses, &compiled_case.tree, )); Expression::Block(block) } ast::TypedExpr::RecordAccess { location: _, field_start: _, type_: _, label: _, index: _, record: _, } => todo!(), ast::TypedExpr::ModuleSelect { location: _, field_start: _, type_: _, label: _, module_name: _, module_alias: _, constructor: _, } => todo!(), ast::TypedExpr::Tuple { location: _, type_: _, elements: _, } => todo!(), ast::TypedExpr::TupleIndex { location: _, type_: _, index: _, tuple: _, } => todo!(), ast::TypedExpr::Todo { location: _, message: _, kind: _, type_: _, } => todo!(), ast::TypedExpr::Panic { location: _, message: _, type_: _, } => todo!(), ast::TypedExpr::Echo { location: _, type_: _, expression: _, message: _, } => todo!(), ast::TypedExpr::BitArray { location: _, type_: _, segments: _, } => todo!(), ast::TypedExpr::RecordUpdate { location: _, type_: _, record_assignment: _, constructor: _, arguments: _, } => todo!(), ast::TypedExpr::NegateBool { location: _, value: _, } => todo!(), ast::TypedExpr::NegateInt { location: _, value: _, } => todo!(), ast::TypedExpr::Invalid { location: _, type_: _, } => todo!(), } } fn translate_assignment(&mut self, assignment: &ast::TypedAssignment) -> Expression { let mut block = vec![]; let value_var = self.make_tmp_var(); let value = self.translate_expression(&assignment.value); block.push(Expression::Set { name: value_var.clone(), value: Box::new(value), }); block.push(self.translate_decision( DecisionKind::Let, &[value_var.clone()], &[], &assignment.compiled_case.tree, )); block.push(Expression::Var(value_var)); Expression::Block(block) } fn translate_decision( &mut self, kind: DecisionKind, subjects: &[Var], clauses: &[ast::TypedClause], decision: &exhaustiveness::Decision, ) -> Expression { match decision { exhaustiveness::Decision::Run { body } => { let mut block = vec![]; for (binding, value) in &body.bindings { let binding = self.make_var(binding.clone()); block.push(self.translate_binding(subjects, binding.clone(), value)); } if kind == DecisionKind::Case { block.push(self.translate_expression(&clauses[body.clause_index].then)); } Expression::Block(block) } exhaustiveness::Decision::Guard { guard, if_true, if_false, } => { let mut block = vec![]; let guard = clauses[*guard] .guard .as_ref() .expect("expected clause to have a guard"); let referenced_in_guard = guard.referenced_variables(); let (guard_bindings, if_true_bindings): (Vec<_>, Vec<_>) = if_true .bindings .iter() .partition(|(binding, _)| referenced_in_guard.contains(binding)); for (binding, value) in guard_bindings { let binding = self.make_var(binding.clone()); block.push(self.translate_binding(subjects, binding, value)); } let cond = self.translate_guard(guard); let if_true = { let mut block = vec![]; for (binding, value) in if_true_bindings { let binding = self.make_var(binding.clone()); block.push(self.translate_binding(subjects, binding.clone(), value)); } block.push(self.translate_expression(&clauses[if_true.clause_index].then)); block }; let if_false = self.translate_decision(kind, subjects, clauses, if_false); block.push(Expression::If { cond: Box::new(cond), then: Box::new(Expression::Block(if_true)), else_: Box::new(if_false), }); Expression::Block(block) } exhaustiveness::Decision::Switch { var, choices, fallback, fallback_check: _, } => { let fallback = self.translate_decision(kind, subjects, clauses, fallback); DoubleEndedIterator::rfold(choices.iter(), fallback, |fallback, (check, then)| { Expression::If { cond: Box::new(self.translate_runtime_check( check, Expression::Var(subjects[var.id].clone()), )), then: Box::new(self.translate_decision(kind, subjects, clauses, then)), else_: Box::new(fallback), } }) } exhaustiveness::Decision::Fail => todo!(), } } fn translate_guard(&mut self, guard: &ast::TypedClauseGuard) -> Expression { match guard { ast::ClauseGuard::Block { location: _, value: _, } => todo!(), ast::ClauseGuard::Equals { location: _, left, right, } => { let lhs = self.translate_guard(left); let rhs = self.translate_guard(right); Expression::Equals { lhs: Box::new(lhs), rhs: Box::new(rhs), } } ast::ClauseGuard::NotEquals { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::GtInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::GtEqInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::LtInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::LtEqInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::GtFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::GtEqFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::LtFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::LtEqFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::AddInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::AddFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::SubInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::SubFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::MultInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::MultFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::DivInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::DivFloat { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::RemainderInt { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::Or { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::And { location: _, left: _, right: _, } => todo!(), ast::ClauseGuard::Not { location: _, expression: _, } => todo!(), ast::ClauseGuard::Var { location: _, type_: _, name, definition_location: _, } => Expression::Var(self.get_var(name)), ast::ClauseGuard::TupleIndex { location: _, index: _, type_: _, tuple: _, } => todo!(), ast::ClauseGuard::FieldAccess { label_location: _, index: _, label: _, type_: _, container: _, } => todo!(), ast::ClauseGuard::ModuleSelect { location: _, type_: _, label: _, module_name: _, module_alias: _, literal: _, } => todo!(), ast::ClauseGuard::Constant(constant) => self.translate_constant(constant), } } fn translate_constant(&mut self, constant: &ast::TypedConstant) -> Expression { match constant { ast::Constant::Int { location: _, value: _, int_value, } => Expression::Int { value: int_value.clone(), }, ast::Constant::Float { location: _, value: _, } => todo!(), ast::Constant::String { location: _, value: _, } => todo!(), ast::Constant::Tuple { location: _, elements: _, } => todo!(), ast::Constant::List { location: _, elements: _, type_: _, } => todo!(), ast::Constant::Record { location: _, module: _, name: _, arguments: _, tag: _, type_: _, field_map: _, record_constructor: _, } => todo!(), ast::Constant::BitArray { location: _, segments: _, } => todo!(), ast::Constant::Var { location: _, module: _, name: _, constructor: _, type_: _, } => todo!(), ast::Constant::StringConcatenation { location: _, left: _, right: _, } => todo!(), ast::Constant::Invalid { location: _, type_: _, } => todo!(), } } fn translate_binding( &mut self, subjects: &[Var], binding: Var, value: &exhaustiveness::BoundValue, ) -> Expression { let value = match value { exhaustiveness::BoundValue::Variable(variable) => { Expression::Var(subjects[variable.id].clone()) } exhaustiveness::BoundValue::LiteralString(_eco_string) => todo!(), exhaustiveness::BoundValue::LiteralInt(big_int) => Expression::Int { value: big_int.clone(), }, exhaustiveness::BoundValue::LiteralFloat(_eco_string) => todo!(), exhaustiveness::BoundValue::BitArraySlice { bit_array: _, read_action: _, } => todo!(), }; Expression::Set { name: binding, value: Box::new(value), } } fn translate_runtime_check( &mut self, check: &exhaustiveness::RuntimeCheck, against: Expression, ) -> Expression { match check { exhaustiveness::RuntimeCheck::Int { value } => { let value = parse::parse_int_value(&value).expect("unable to parse integer value"); Expression::Equals { lhs: Box::new(against), rhs: Box::new(Expression::Int { value }), } } exhaustiveness::RuntimeCheck::Float { value: _ } => todo!(), exhaustiveness::RuntimeCheck::String { value: _ } => todo!(), exhaustiveness::RuntimeCheck::StringPrefix { prefix: _, rest: _ } => todo!(), exhaustiveness::RuntimeCheck::Tuple { size: _, elements: _, } => todo!(), exhaustiveness::RuntimeCheck::BitArray { test: _ } => todo!(), exhaustiveness::RuntimeCheck::Variant { match_: _, index: _, labels: _, fields: _, } => todo!(), exhaustiveness::RuntimeCheck::NonEmptyList { first: _, rest: _ } => todo!(), exhaustiveness::RuntimeCheck::EmptyList => todo!(), } } } #[cfg(test)] mod tests { use std::collections::{HashMap, HashSet}; use super::*; use crate::analyse::TargetSupport; use crate::build::{Origin, Target}; use crate::config::PackageConfig; use crate::line_numbers::LineNumbers; use crate::parse::parse_module; use crate::type_::PRELUDE_MODULE_NAME; use crate::uid::UniqueIdGenerator; use crate::warning::{TypeWarningEmitter, WarningEmitter}; use camino::Utf8PathBuf; fn compile_module(src: &str) -> ast::TypedModule { use crate::type_::build_prelude; let parsed = parse_module(Utf8PathBuf::from("test/path"), src, &WarningEmitter::null()) .expect("syntax error"); let ast = parsed.module; let ids = UniqueIdGenerator::new(); let mut config = PackageConfig::default(); config.name = "thepackage".into(); let mut modules = im::HashMap::new(); let _ = modules.insert(PRELUDE_MODULE_NAME.into(), build_prelude(&ids)); let line_numbers = LineNumbers::new(src); crate::analyse::ModuleAnalyzerConstructor::<()> { target: Target::Erlang, ids: &ids, origin: Origin::Src, importable_modules: &modules, warnings: &TypeWarningEmitter::null(), direct_dependencies: &HashMap::new(), dev_dependencies: &HashSet::new(), target_support: TargetSupport::Enforced, package_config: &config, } .infer_module(ast, line_numbers, "".into()) .expect("should successfully infer") } fn translate(src: &str) -> Module { let typed_module = compile_module(src); Translator::default().translate(&typed_module) } #[test] fn translates_samples() { insta::assert_debug_snapshot!(translate( r#"pub fn add(lhs: Int, rhs: Int) -> Int { lhs + rhs }"# )); insta::assert_debug_snapshot!(translate( r#"pub fn some_case(n: Int) -> Int { case n { 0 -> 2 1 -> 4 _ -> 6 } }"# )); insta::assert_debug_snapshot!(translate( r#"pub fn some_case(n: Int) -> Int { case n { y if y == 0 -> 2 1 -> 4 _ -> 6 } }"# )); insta::assert_debug_snapshot!(translate( r#"pub fn fib(n: Int) -> Int { case n { 0 -> 0 1 -> 1 _ -> fib(n - 1) + fib(n - 2) } }"# )); } }