Fork of daniellemaywood.uk/gleam — Wasm codegen work
2.4 kB
87 lines
1use ecow::EcoString;
2
3use crate::{ast, type_};
4
5#[derive(Debug, Default)]
6pub struct Module {
7 functions: Vec<Function>,
8}
9
10#[derive(Debug)]
11pub struct Function {
12 pub name: EcoString,
13 pub parameters: Vec<FunctionParameter>,
14}
15
16#[derive(Debug)]
17pub struct FunctionParameter {
18 pub type_: Type,
19 pub name: Option<EcoString>,
20}
21
22#[derive(Debug, Default)]
23pub struct Translator {
24 module: Module,
25}
26
27#[derive(Debug, Clone, Copy)]
28pub enum Type {
29 Int,
30 Float,
31}
32
33impl Translator {
34 pub fn translate(mut self, module: &ast::TypedModule) -> Module {
35 for definition in &module.definitions {
36 match definition {
37 ast::Definition::Function(function) => {
38 self.module
39 .functions
40 .push(Self::translate_function(function));
41 }
42 ast::Definition::TypeAlias(_type_alias) => todo!(),
43 ast::Definition::CustomType(_custom_type) => todo!(),
44 ast::Definition::Import(_import) => todo!(),
45 ast::Definition::ModuleConstant(_module_constant) => todo!(),
46 }
47 }
48
49 self.module
50 }
51
52 fn translate_function(function: &ast::TypedFunction) -> Function {
53 let (_, name) = function.name.clone().expect("function should have a name");
54
55 let parameters = Iterator::collect(function.arguments.iter().map(|argument| {
56 let name = argument.get_variable_name().cloned();
57 let type_ = Self::translate_type(&argument.type_);
58
59 FunctionParameter { name, type_ }
60 }));
61
62 Function { name, parameters }
63 }
64
65 fn translate_type(type_: &type_::Type) -> Type {
66 match type_ {
67 type_::Type::Named {
68 publicity: _,
69 package: _,
70 module,
71 name,
72 arguments: _,
73 inferred_variant: _,
74 } => match (module.as_str(), name.as_str()) {
75 ("gleam", "Int") => Type::Int,
76 ("gleam", "Float") => Type::Float,
77 (_, _) => todo!(),
78 },
79 type_::Type::Fn {
80 arguments: _,
81 return_: _,
82 } => todo!(),
83 type_::Type::Var { type_: _ } => todo!(),
84 type_::Type::Tuple { elements: _ } => todo!(),
85 }
86 }
87}