Browse Source

Add JS generator

github-actions
Garrit Franke 3 years ago
parent
commit
90207296b1
  1. 3
      examples_out/out.js
  2. 31
      src/generator/js.rs
  3. 1
      src/generator/mod.rs
  4. 4
      src/main.rs

3
examples_out/out.js

@ -0,0 +1,3 @@
function main() {}
function fib() {}
main()

31
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
}

1
src/generator/mod.rs

@ -1,5 +1,6 @@
use crate::parser::node_type::Program;
pub mod js;
pub mod x86;
pub trait Generator {

4
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(())

Loading…
Cancel
Save