From 90207296b1d3a2749b129913d6921c41921a3c46 Mon Sep 17 00:00:00 2001 From: Garrit Franke Date: Sat, 5 Dec 2020 15:52:00 +0100 Subject: [PATCH] Add JS generator --- examples_out/out.js | 3 +++ src/generator/js.rs | 31 +++++++++++++++++++++++++++++++ src/generator/mod.rs | 1 + src/main.rs | 4 ++-- 4 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 examples_out/out.js create mode 100644 src/generator/js.rs diff --git a/examples_out/out.js b/examples_out/out.js new file mode 100644 index 0000000..983f673 --- /dev/null +++ b/examples_out/out.js @@ -0,0 +1,3 @@ +function main() {} +function fib() {} +main() \ No newline at end of file diff --git a/src/generator/js.rs b/src/generator/js.rs new file mode 100644 index 0000000..90a6ede --- /dev/null +++ b/src/generator/js.rs @@ -0,0 +1,31 @@ +use crate::generator::Generator; +use crate::parser::node_type::*; + +pub struct JsGenerator; + +impl Generator for JsGenerator { + fn generate(prog: Program) -> String { + let mut code = prog + .func + .into_iter() + .map(|f| generate_function(f)) + .collect(); + + code += "main()"; + + return code; + } +} + +fn generate_function(func: Function) -> String { + let arguments: String = func + .arguments + .into_iter() + .map(|arg: Variable| format!("{},", arg.name)) + .collect(); + let mut raw = format!("function {N}({A}) ", N = func.name, A = arguments); + + raw += "{}\n"; + + raw +} diff --git a/src/generator/mod.rs b/src/generator/mod.rs index 5d0ee9b..e7357f2 100644 --- a/src/generator/mod.rs +++ b/src/generator/mod.rs @@ -1,5 +1,6 @@ use crate::parser::node_type::Program; +pub mod js; pub mod x86; pub trait Generator { diff --git a/src/main.rs b/src/main.rs index 844bc0c..28f8987 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,8 +19,8 @@ fn main() -> Result<(), String> { let program = parser::parse(tokens, Some(contents))?; - let output = generator::x86::X86Generator::generate(program); - let mut file = std::fs::File::create("examples_out/out.asm").expect("create failed"); + let output = generator::js::JsGenerator::generate(program); + let mut file = std::fs::File::create("examples_out/out.js").expect("create failed"); file.write_all(output.as_bytes()).expect("write failed"); file.flush().expect("Could not flush file"); Ok(())