Skip to content

Commit

Permalink
Added benchmark code
Browse files Browse the repository at this point in the history
  • Loading branch information
VoltagedDebunked committed Oct 16, 2024
1 parent fda9e44 commit 73c3fdc
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 57 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ colored = "2.1.0"
deno_core = "0.314.0"
tokio = { version = "1.40.0", features = ["full"] }
regex = "1.11.0"
wasmtime = "25.0.2"
clap = { version = "4.5.20", features = ["derive"] }
url = "2.5.2"
reqwest = { version = "0.12.7", features = ["json"]}
serde = "1.0.210"
Expand Down
23 changes: 23 additions & 0 deletions src/benchmark-code.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function countPrimes(upTo) {
let count = 0;
const isPrime = Array(upTo + 1).fill(true);
isPrime[0] = isPrime[1] = false;

for (let i = 2; i * i <= upTo; i++) {
if (isPrime[i]) {
for (let j = i * i; j <= upTo; j += i) {
isPrime[j] = false;
}
}
}

for (let i = 2; i <= upTo; i++) {
if (isPrime[i]) {
count++;
}
}

console.log(`Number of primes up to ${upTo}: ${count}`);
}

countPrimes(100000);
140 changes: 83 additions & 57 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,40 @@ mod runtime;
mod init;
mod tasks;
mod fmt;
mod wasm;

use colored::Colorize;
use std::{env, thread::{self, JoinHandle}};
use std::thread::{self, JoinHandle};
use tokio::runtime::Builder;
use runtime::JsExecutor;
use fmt::Formatter;
use wasm::WasmExecutor; // Import WasmExecutor
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "zen")]
#[command(about = "A JavaScript runtime", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}

#[derive(Subcommand)]
enum Commands {
Run {
files: Vec<String>,
},
Init,
Task {
name: String,
},
Fmt {
files: Vec<String>,
},
Wasm {
file: String,
},
}

fn execute_file(file_path: String) -> JoinHandle<Result<(), deno_core::error::AnyError>> {
thread::spawn(move || {
Expand All @@ -20,82 +48,80 @@ fn execute_file(file_path: String) -> JoinHandle<Result<(), deno_core::error::An
})
}

fn print_manual(command: &str) {
match command {
"run" => {
println!("{}", "Usage: zen run <file1.js> <file2.js> ...".green());
println!("Executes the specified JavaScript files.");
}
"init" => {
println!("{}", "Usage: zen init".green());
println!("Initializes a new project.");
}
"task" => {
println!("{}", "Usage: zen task <task_name>".green());
println!("Handles the specified task.");
}
"fmt" => {
println!("{}", "Usage: zen fmt <file1.js> <file2.js> ...".green());
println!("Formats the specified JavaScript files.");
}
_ => {
println!("{}", "Available commands: run, init, fmt, task".green());
println!("Use zen <command> for more information on a command.");
}
}
fn execute_wasm(file_path: String) -> JoinHandle<Result<(), String>> {
thread::spawn(move || {
let executor = WasmExecutor::new();
executor.run(&file_path)
})
}

#[tokio::main]
async fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("{}", "Usage: zen <command>".yellow().bold());
return;
}

let command: &String = &args[1];
if args.len() == 2 {
print_manual(command);
return;
}
let cli = Cli::parse();

let formatter = match Formatter::new() {
Ok(fmt) => fmt,
Err(e) => {
eprintln!("Error installing Dprint: {}", e.to_string().red().bold());
return;
}
};
match cli.command {
Commands::Run { files } => {
if files.is_empty() {
eprintln!("{}", "No files specified to run.".red());
return;
}

match command.as_str() {
"run" => {
let handles: Vec<_> = args[2..]
let handles: Vec<_> = files
.iter()
.map(|file| execute_file(file.to_string()))
.collect();

for handle in handles {
if let Err(error) = handle.join().unwrap() {
eprintln!("Error executing file: {}", error.to_string().red().bold());
for (file, handle) in files.iter().zip(handles) {
match handle.join() {
Ok(result) => {
if let Err(error) = result {
eprintln!("Error executing file {}: {}", file.red(), error.to_string().red().bold());
} else {
println!("Successfully executed file {}", file.green());
}
}
Err(_) => {
eprintln!("Thread for file {} panicked", file.red());
}
}
}
}
Commands::Wasm { file } => {
let handle = execute_wasm(file);
match handle.join() {
Ok(result) => {
if let Err(error) = result {
eprintln!("Error executing WASM file {}: {}", file.red(), error.red().bold());
} else {
println!("Successfully executed WASM file {}", file.green());
}
}
Err(_) => {
eprintln!("Thread for WASM file {} panicked", file.red());
}
}
}
"init" => {
Commands::Init => {
init::initialize_project();
}
"task" => {
tasks::handle_task(&args[2]);
Commands::Task { name } => {
tasks::handle_task(&name);
}
"fmt" => {
for file in &args[2..] {
match formatter.format_js(file) {
Commands::Fmt { files } => {
let formatter = match Formatter::new() {
Ok(fmt) => fmt,
Err(e) => {
eprintln!("Error initializing formatter: {}", e.to_string().red().bold());
return;
}
};

for file in files {
match formatter.format_js(&file) {
Ok(_) => println!("Formatted {}", file),
Err(e) => eprintln!("Error formatting file {}: {}", file, e.to_string().red().bold()),
}
}
}
_ => {
eprintln!("{}", "Invalid command. Commands: Run, Init, Fmt, Task".red().bold());
}
}
}
25 changes: 25 additions & 0 deletions src/wasm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use wasmtime::{Engine, Module, Instance, Store, Linker};
use std::path::Path;

pub struct WasmExecutor {
engine: Engine,
}

impl WasmExecutor {
pub fn new() -> Self {
let engine = Engine::default();
WasmExecutor { engine }
}

pub fn run(&self, file_path: &str) -> Result<(), String> {
let store = Store::new(&self.engine);
let module = Module::from_file(&self.engine, file_path).map_err(|e| e.to_string())?;
let instance = Instance::new(&store, &module, &[]).map_err(|e| e.to_string())?;

if let Some(start) = instance.get_func("_start") {
start.call(&[]).map_err(|e| e.to_string())?;
}

Ok(())
}
}

0 comments on commit 73c3fdc

Please sign in to comment.