Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4c7084563f | |||
| ef8e97b15a | |||
| b069237b91 | |||
| 369ccbe84e | |||
| 6cb51c4120 |
4
Cargo.lock
generated
4
Cargo.lock
generated
@ -561,7 +561,7 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jrpc-cli"
|
name = "jrpc-cli"
|
||||||
version = "0.1.0"
|
version = "0.1.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@ -607,7 +607,7 @@ checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libjrpc"
|
name = "libjrpc"
|
||||||
version = "0.1.0"
|
version = "0.1.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
name = "jrpc-cli"
|
name = "jrpc-cli"
|
||||||
version = "0.1.0"
|
version = "0.1.5"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
@ -12,6 +12,7 @@ anyhow = "1"
|
|||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
libjrpc = { path = "libjrpc" }
|
libjrpc = { path = "libjrpc" }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
simple_logger = { version = "5.0.0", features = ["threads"] }
|
simple_logger = { version = "5", features = ["threads"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
walkdir = "2"
|
walkdir = "2"
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "libjrpc"
|
name = "libjrpc"
|
||||||
version = "0.1.0"
|
version = "0.1.5"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
@ -8,9 +8,9 @@ default = ["http"]
|
|||||||
http = ["dep:reqwest", "dep:url"]
|
http = ["dep:reqwest", "dep:url"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.89"
|
anyhow = "1"
|
||||||
lazy_static = "1.5.0"
|
lazy_static = "1"
|
||||||
log = "0.4.22"
|
log = "0.4"
|
||||||
regex = "1.10.6"
|
regex = "1"
|
||||||
reqwest = { version = "0.12.7", optional = true, features = ["blocking"] }
|
reqwest = { version = "0.12", optional = true, features = ["blocking"] }
|
||||||
url = { version = "2.5.2", optional = true }
|
url = { version = "2", optional = true }
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf};
|
use std::{collections::BTreeMap, path::PathBuf};
|
||||||
|
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
@ -8,7 +8,7 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub trait Compile {
|
pub trait Compile {
|
||||||
fn new(options: &HashMap<String, String>) -> Result<Self>
|
fn new(options: &BTreeMap<String, String>) -> Result<Self>
|
||||||
where
|
where
|
||||||
Self: Sized;
|
Self: Sized;
|
||||||
|
|
||||||
@ -88,6 +88,7 @@ impl CompileContext {
|
|||||||
pub fn write_file(&self, filename: &str, content: &str) -> Result<()> {
|
pub fn write_file(&self, filename: &str, content: &str) -> Result<()> {
|
||||||
let res_path = self.output_folder.clone().join(filename);
|
let res_path = self.output_folder.clone().join(filename);
|
||||||
let res_dir = res_path.parent().context("Path has no parent!")?;
|
let res_dir = res_path.parent().context("Path has no parent!")?;
|
||||||
|
log::debug!("Writing to file {:?}", res_path);
|
||||||
std::fs::create_dir_all(res_dir)?;
|
std::fs::create_dir_all(res_dir)?;
|
||||||
std::fs::write(res_path, content)?;
|
std::fs::write(res_path, content)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{HashMap, HashSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
error::Error,
|
error::Error,
|
||||||
fmt::{Debug, Display},
|
fmt::{Debug, Display},
|
||||||
hash::{Hash, Hasher},
|
hash::{Hash, Hasher},
|
||||||
@ -20,7 +20,7 @@ pub trait Definition: Debug {
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct IR {
|
pub struct IR {
|
||||||
pub options: HashMap<String, String>,
|
pub options: BTreeMap<String, String>,
|
||||||
pub steps: Vec<Step>,
|
pub steps: Vec<Step>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,7 +58,12 @@ impl ToString for BaseType {
|
|||||||
|
|
||||||
impl Hash for BaseType {
|
impl Hash for BaseType {
|
||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
self.to_string().hash(state);
|
// Hash the enum variant itself
|
||||||
|
std::mem::discriminant(self).hash(state);
|
||||||
|
// If the variant has data, hash that too
|
||||||
|
if let BaseType::Custom(name) = self {
|
||||||
|
name.hash(state);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -178,7 +183,7 @@ impl Type {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct TypeDefinition {
|
pub struct TypeDefinition {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub depends: HashSet<BaseType>,
|
pub depends: BTreeSet<BaseType>,
|
||||||
pub fields: Vec<Field>,
|
pub fields: Vec<Field>,
|
||||||
pub position: ParserPosition,
|
pub position: ParserPosition,
|
||||||
}
|
}
|
||||||
@ -223,7 +228,7 @@ pub struct EnumField {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ServiceDefinition {
|
pub struct ServiceDefinition {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub depends: HashSet<BaseType>,
|
pub depends: BTreeSet<BaseType>,
|
||||||
pub methods: Vec<Method>,
|
pub methods: Vec<Method>,
|
||||||
pub position: ParserPosition,
|
pub position: ParserPosition,
|
||||||
}
|
}
|
||||||
@ -259,7 +264,7 @@ pub struct MethodOutput {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct MethodDecorators {
|
pub struct MethodDecorators {
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
pub parameter_descriptions: HashMap<String, String>,
|
pub parameter_descriptions: BTreeMap<String, String>,
|
||||||
pub return_description: Option<String>,
|
pub return_description: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -267,7 +272,7 @@ fn build_type(stmt: &TypeStatement) -> Result<TypeDefinition> {
|
|||||||
let mut typedef = TypeDefinition {
|
let mut typedef = TypeDefinition {
|
||||||
position: stmt.position.clone(),
|
position: stmt.position.clone(),
|
||||||
name: stmt.name.clone(),
|
name: stmt.name.clone(),
|
||||||
depends: HashSet::new(),
|
depends: BTreeSet::new(),
|
||||||
fields: Vec::new(),
|
fields: Vec::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -332,7 +337,7 @@ fn build_service(stmt: &ServiceStatement) -> Result<ServiceDefinition> {
|
|||||||
let mut servdef = ServiceDefinition {
|
let mut servdef = ServiceDefinition {
|
||||||
position: stmt.position.clone(),
|
position: stmt.position.clone(),
|
||||||
name: stmt.name.clone(),
|
name: stmt.name.clone(),
|
||||||
depends: HashSet::new(),
|
depends: BTreeSet::new(),
|
||||||
methods: Vec::new(),
|
methods: Vec::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -349,7 +354,7 @@ fn build_service(stmt: &ServiceStatement) -> Result<ServiceDefinition> {
|
|||||||
}),
|
}),
|
||||||
decorators: MethodDecorators {
|
decorators: MethodDecorators {
|
||||||
description: None,
|
description: None,
|
||||||
parameter_descriptions: HashMap::new(),
|
parameter_descriptions: BTreeMap::new(),
|
||||||
return_description: None,
|
return_description: None,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@ -450,7 +455,7 @@ fn build_service(stmt: &ServiceStatement) -> Result<ServiceDefinition> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_ir(root: &Vec<RootNode>) -> Result<IR> {
|
pub fn build_ir(root: &Vec<RootNode>) -> Result<IR> {
|
||||||
let mut options = HashMap::<String, String>::new();
|
let mut options = BTreeMap::<String, String>::new();
|
||||||
let mut steps = Vec::new();
|
let mut steps = Vec::new();
|
||||||
|
|
||||||
for node in root {
|
for node in root {
|
||||||
@ -476,8 +481,8 @@ pub fn build_ir(root: &Vec<RootNode>) -> Result<IR> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut all_types = HashSet::<String>::new();
|
let mut all_types = BTreeSet::<String>::new();
|
||||||
let mut serv_types = HashSet::<String>::new();
|
let mut serv_types = BTreeSet::<String>::new();
|
||||||
|
|
||||||
for bi in &BUILT_INS {
|
for bi in &BUILT_INS {
|
||||||
all_types.insert(bi.to_string());
|
all_types.insert(bi.to_string());
|
||||||
@ -577,3 +582,36 @@ impl Display for IRError {
|
|||||||
write!(f, "ParserError: {} at {:?}", self.message, self.position)
|
write!(f, "ParserError: {} at {:?}", self.message, self.position)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn btreeset_order_is_consistent() {
|
||||||
|
let mut set1 = BTreeSet::new();
|
||||||
|
let mut set2 = BTreeSet::new();
|
||||||
|
|
||||||
|
let elements = vec![
|
||||||
|
BaseType::Custom("CustomType".to_string()),
|
||||||
|
BaseType::Void,
|
||||||
|
BaseType::Bytes,
|
||||||
|
BaseType::Float,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Insert in normal order
|
||||||
|
for elem in &elements {
|
||||||
|
set1.insert(elem.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert in reverse order
|
||||||
|
for elem in elements.iter().rev() {
|
||||||
|
set2.insert(elem.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
let iter1: Vec<_> = set1.iter().cloned().collect();
|
||||||
|
let iter2: Vec<_> = set2.iter().cloned().collect();
|
||||||
|
|
||||||
|
assert_eq!(iter1, iter2); // Order must be the same
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
404
libjrpc/src/targets/csharp.rs
Normal file
404
libjrpc/src/targets/csharp.rs
Normal file
@ -0,0 +1,404 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use log::warn;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::fmt::format;
|
||||||
|
|
||||||
|
use crate::compile::{Compile, CompileContext, FileGenerator};
|
||||||
|
use crate::ir::{BaseType, EnumDefinition, ServiceDefinition, Step, Type, TypeDefinition};
|
||||||
|
use crate::shared::Keywords;
|
||||||
|
use crate::IR;
|
||||||
|
|
||||||
|
pub struct CSharpCompiler {
|
||||||
|
namespace: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
static CSHARP_KEYWORDS: [&'static str; 5] = ["event", "internal", "public", "private", "static"];
|
||||||
|
|
||||||
|
impl CSharpCompiler {
|
||||||
|
fn type_to_csharp(typ: &BaseType) -> String {
|
||||||
|
match typ {
|
||||||
|
BaseType::String => "string".to_string(),
|
||||||
|
BaseType::Int => "long".to_string(),
|
||||||
|
BaseType::Float => "double".to_string(),
|
||||||
|
BaseType::Bool => "bool".to_string(),
|
||||||
|
BaseType::Bytes => todo!("Bytes are not implemented for C#"),
|
||||||
|
BaseType::Void => "void".to_string(),
|
||||||
|
BaseType::Custom(name) => name.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_to_csharp_ext(typ: &Type) -> String {
|
||||||
|
let mut result = Self::type_to_csharp(&typ.0);
|
||||||
|
|
||||||
|
let (optional, array, map) = typ.1.get_flags();
|
||||||
|
|
||||||
|
if array {
|
||||||
|
result = format!("IList<{}>", result);
|
||||||
|
}
|
||||||
|
if let Some(map) = &map {
|
||||||
|
result = format!("Dictionary<{}, {}>", Self::type_to_csharp(&map), result);
|
||||||
|
}
|
||||||
|
if optional {
|
||||||
|
result = format!("{}?", result);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fix_keyword_name(name: &str) -> String {
|
||||||
|
if CSHARP_KEYWORDS.contains(&name) {
|
||||||
|
format!("{}_", name)
|
||||||
|
} else {
|
||||||
|
name.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_service_server(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut CompileContext,
|
||||||
|
definition: &ServiceDefinition,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let mut f = FileGenerator::new();
|
||||||
|
|
||||||
|
f.a0("using System;");
|
||||||
|
f.a0("using System.Text.Json;");
|
||||||
|
f.a0("using System.Text.Json.Serialization;");
|
||||||
|
f.a0("using System.Text.Json.Nodes;");
|
||||||
|
f.a0("using System.Threading.Tasks;");
|
||||||
|
f.a0("using System.Collections.Generic;");
|
||||||
|
|
||||||
|
f.a0("");
|
||||||
|
f.a0(format!("namespace {};", self.namespace));
|
||||||
|
f.a0("");
|
||||||
|
|
||||||
|
f.a0(format!(
|
||||||
|
"public abstract class {}Server<TContext> : JRpcService<TContext> {{",
|
||||||
|
definition.name
|
||||||
|
));
|
||||||
|
f.a1("public override string Name {");
|
||||||
|
f.a2("get {");
|
||||||
|
f.a3(format!("return \"{}\";", definition.name));
|
||||||
|
f.a2("}");
|
||||||
|
f.a1("}");
|
||||||
|
|
||||||
|
f.a1(format!("public {}Server() {{", definition.name));
|
||||||
|
for method in &definition.methods {
|
||||||
|
f.a2(format!("this.RegisterFunction(\"{}\");", method.name));
|
||||||
|
}
|
||||||
|
f.a1("}");
|
||||||
|
f.a0("");
|
||||||
|
|
||||||
|
for fnc in &definition.methods {
|
||||||
|
let mut args = fnc
|
||||||
|
.inputs
|
||||||
|
.iter()
|
||||||
|
.map(|inp| {
|
||||||
|
format!(
|
||||||
|
"{} {}",
|
||||||
|
Self::type_to_csharp_ext(&inp.typ),
|
||||||
|
Self::fix_keyword_name(&inp.name)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<String>>();
|
||||||
|
args.push("TContext ctx".to_string());
|
||||||
|
let args = args.join(",");
|
||||||
|
|
||||||
|
if let Some(output) = &fnc.output {
|
||||||
|
if output.typ.0 == BaseType::Void {
|
||||||
|
f.a1(format!("public abstract Task {}({});", fnc.name, args));
|
||||||
|
} else {
|
||||||
|
f.a1(format!(
|
||||||
|
"public abstract Task<{}> {}({});",
|
||||||
|
Self::type_to_csharp_ext(&output.typ),
|
||||||
|
fnc.name,
|
||||||
|
args
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
f.a1(format!("public abstract void {}({});", fnc.name, args));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.a0("");
|
||||||
|
f.a1("public async override Task<JsonNode?> HandleRequest(string func, JsonNode param, TContext context) {");
|
||||||
|
f.a2("switch(func) {");
|
||||||
|
for fnc in &definition.methods {
|
||||||
|
f.a3(format!("case \"{}\": {{", fnc.name));
|
||||||
|
f.a4("if(param is JsonObject) {");
|
||||||
|
let args_array = fnc
|
||||||
|
.inputs
|
||||||
|
.iter()
|
||||||
|
.map(|inp| format!("param[\"{}\"]", inp.name))
|
||||||
|
.collect::<Vec<String>>();
|
||||||
|
f.a5(format!(
|
||||||
|
"var ja = new JsonArray({});",
|
||||||
|
args_array.join(", ")
|
||||||
|
));
|
||||||
|
f.a5("param = ja;");
|
||||||
|
f.a4("}");
|
||||||
|
|
||||||
|
let pref = if let Some(output) = &fnc.output {
|
||||||
|
if output.typ.0 == BaseType::Void {
|
||||||
|
"await"
|
||||||
|
} else {
|
||||||
|
"var result = await"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut args_array = fnc
|
||||||
|
.inputs
|
||||||
|
.iter()
|
||||||
|
.map(|inp| {
|
||||||
|
format!(
|
||||||
|
"param[\"{}\"]!.Deserialize<{}>()",
|
||||||
|
inp.name,
|
||||||
|
Self::type_to_csharp_ext(&inp.typ)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<String>>();
|
||||||
|
args_array.push("context".to_string());
|
||||||
|
let args_array = args_array.join(", ");
|
||||||
|
f.a4(format!("{} this.{}({});", pref, fnc.name, args_array));
|
||||||
|
if let Some(output) = &fnc.output {
|
||||||
|
if output.typ.0 == BaseType::Void {
|
||||||
|
f.a4("return null;");
|
||||||
|
} else {
|
||||||
|
f.a4("return JsonSerializer.SerializeToNode(result);");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
f.a4("return null;");
|
||||||
|
};
|
||||||
|
f.a3("}");
|
||||||
|
}
|
||||||
|
f.a3("default: {");
|
||||||
|
f.a4("throw new Exception(\"Invalid Method!\");");
|
||||||
|
f.a3("}");
|
||||||
|
f.a2("}");
|
||||||
|
f.a1("}");
|
||||||
|
|
||||||
|
f.a0("}");
|
||||||
|
|
||||||
|
ctx.write_file(&format!("{}Server.cs", &definition.name), &f.into_content())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_service_client(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut CompileContext,
|
||||||
|
definition: &ServiceDefinition,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let mut f = FileGenerator::new();
|
||||||
|
|
||||||
|
f.a0("using System;");
|
||||||
|
f.a0("using System.Text.Json;");
|
||||||
|
f.a0("using System.Text.Json.Serialization;");
|
||||||
|
f.a0("using System.Text.Json.Nodes;");
|
||||||
|
f.a0("using System.Threading.Tasks;");
|
||||||
|
f.a0("using System.Collections.Generic;");
|
||||||
|
|
||||||
|
f.a0("");
|
||||||
|
f.a0(format!("namespace {};", self.namespace));
|
||||||
|
f.a0("");
|
||||||
|
|
||||||
|
f.a0(format!("public class {}Client {{", definition.name));
|
||||||
|
f.a1("private JRpcClient Client;");
|
||||||
|
f.a1(format!(
|
||||||
|
"public {}Client(JRpcClient client) {{",
|
||||||
|
definition.name
|
||||||
|
));
|
||||||
|
f.a2("this.Client = client;");
|
||||||
|
f.a1("}");
|
||||||
|
f.a0("");
|
||||||
|
for fnc in &definition.methods {
|
||||||
|
let args = fnc
|
||||||
|
.inputs
|
||||||
|
.iter()
|
||||||
|
.map(|inp| {
|
||||||
|
format!(
|
||||||
|
"{} {}",
|
||||||
|
Self::type_to_csharp_ext(&inp.typ),
|
||||||
|
Self::fix_keyword_name(&inp.name)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(", ");
|
||||||
|
|
||||||
|
let args_code = format!(
|
||||||
|
"var param = new JsonArray({});",
|
||||||
|
fnc.inputs
|
||||||
|
.iter()
|
||||||
|
.map(|inp| {
|
||||||
|
format!(
|
||||||
|
"JsonSerializer.SerializeToNode({})",
|
||||||
|
Self::fix_keyword_name(&inp.name)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(", ")
|
||||||
|
);
|
||||||
|
|
||||||
|
if let Some(output) = &fnc.output {
|
||||||
|
if output.typ.0 == BaseType::Void {
|
||||||
|
f.a1(format!("public async Task {}({}) {{", fnc.name, args));
|
||||||
|
f.a2(args_code);
|
||||||
|
f.a2(format!(
|
||||||
|
"await Client.SendRequestRaw(\"{}.{}\", param);",
|
||||||
|
definition.name, fnc.name,
|
||||||
|
));
|
||||||
|
f.a1("}");
|
||||||
|
} else {
|
||||||
|
f.a1(format!(
|
||||||
|
"public async Task<{}> {}({}) {{",
|
||||||
|
Self::type_to_csharp_ext(&output.typ),
|
||||||
|
fnc.name,
|
||||||
|
args
|
||||||
|
));
|
||||||
|
f.a2(args_code);
|
||||||
|
f.a2(format!(
|
||||||
|
"return await Client.SendRequest<{}>(\"{}.{}\", param);",
|
||||||
|
Self::type_to_csharp_ext(&output.typ),
|
||||||
|
definition.name,
|
||||||
|
fnc.name,
|
||||||
|
));
|
||||||
|
f.a1("}");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
f.a1(format!("public void {}({}) {{", fnc.name, args));
|
||||||
|
f.a2(args_code);
|
||||||
|
f.a2(format!(
|
||||||
|
"Client.SendNotification(\"{}.{}\", param);",
|
||||||
|
definition.name, fnc.name,
|
||||||
|
));
|
||||||
|
f.a1("}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
f.a0("}");
|
||||||
|
|
||||||
|
ctx.write_file(&format!("{}Client.cs", &definition.name), &f.into_content())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Compile for CSharpCompiler {
|
||||||
|
fn new(options: &BTreeMap<String, String>) -> anyhow::Result<Self> {
|
||||||
|
let namespace = if let Some(namespace) = options.get("csharp_namespace") {
|
||||||
|
namespace.to_string()
|
||||||
|
} else {
|
||||||
|
"JRPC".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(allow_bytes) = options.get("allow_bytes") {
|
||||||
|
if allow_bytes == "true" {
|
||||||
|
anyhow::bail!("allow_bytes option is not supported for csharp compiler");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CSharpCompiler { namespace })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&self) -> String {
|
||||||
|
"csharp".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(&mut self, ctx: &mut CompileContext) -> anyhow::Result<()> {
|
||||||
|
let fix_ns = |input: &str| input.replace("__NAMESPACE__", &self.namespace);
|
||||||
|
|
||||||
|
ctx.write_file(
|
||||||
|
&format!("{}.csproj", self.namespace),
|
||||||
|
&fix_ns(include_str!("../../templates/CSharp/CSharp.csproj")),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
ctx.write_file(
|
||||||
|
"JRpcClient.cs",
|
||||||
|
&fix_ns(include_str!("../../templates/CSharp/JRpcClient.cs")),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
ctx.write_file(
|
||||||
|
"JRpcServer.cs",
|
||||||
|
&fix_ns(include_str!("../../templates/CSharp/JRpcServer.cs")),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
ctx.write_file(
|
||||||
|
"JRpcTransport.cs",
|
||||||
|
&fix_ns(include_str!("../../templates/CSharp/JRpcTransport.cs")),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_type(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut CompileContext,
|
||||||
|
definition: &TypeDefinition,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let mut f = FileGenerator::new();
|
||||||
|
|
||||||
|
f.a0("using System.Text.Json;");
|
||||||
|
f.a0("using System.Text.Json.Serialization;");
|
||||||
|
f.a0("using System.Collections.Generic;");
|
||||||
|
f.a0("");
|
||||||
|
f.a0(format!("namespace {};", self.namespace));
|
||||||
|
f.a0("");
|
||||||
|
f.a0(format!("public class {} {{", definition.name));
|
||||||
|
|
||||||
|
for field in &definition.fields {
|
||||||
|
f.a1(format!("[JsonPropertyName(\"{}\")]", field.name));
|
||||||
|
|
||||||
|
f.a1(format!(
|
||||||
|
"public {} {} {{ get; set; }}",
|
||||||
|
Self::type_to_csharp_ext(&field.typ),
|
||||||
|
Self::fix_keyword_name(&field.name)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
f.a0("}");
|
||||||
|
|
||||||
|
ctx.write_file(&format!("{}.cs", &definition.name), &f.into_content())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_enum(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut CompileContext,
|
||||||
|
definition: &EnumDefinition,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let mut f = FileGenerator::new();
|
||||||
|
|
||||||
|
f.a0("using System.Text.Json;");
|
||||||
|
f.a0("using System.Text.Json.Serialization;");
|
||||||
|
f.a0("");
|
||||||
|
f.a0(format!("namespace {};", self.namespace));
|
||||||
|
f.a0("");
|
||||||
|
|
||||||
|
f.a0(format!("public enum {} {{", definition.name));
|
||||||
|
|
||||||
|
for variant in &definition.values {
|
||||||
|
f.a1(format!("{} = {},", variant.name, variant.value));
|
||||||
|
}
|
||||||
|
|
||||||
|
f.a0("}");
|
||||||
|
|
||||||
|
ctx.write_file(&format!("{}.cs", &definition.name), &f.into_content())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_service(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut CompileContext,
|
||||||
|
definition: &ServiceDefinition,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
self.generate_service_client(ctx, definition)?;
|
||||||
|
self.generate_service_server(ctx, definition)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finalize(&mut self, ctx: &mut CompileContext, ir: &IR) -> anyhow::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -4,6 +4,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use log::debug;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
compile::{Compile, CompileContext},
|
compile::{Compile, CompileContext},
|
||||||
@ -11,6 +12,7 @@ use crate::{
|
|||||||
IR,
|
IR,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub mod csharp;
|
||||||
pub mod rust;
|
pub mod rust;
|
||||||
pub mod typescript;
|
pub mod typescript;
|
||||||
|
|
||||||
@ -50,6 +52,7 @@ pub fn compile<T: Compile>(ir: IR, output: &str) -> Result<()> {
|
|||||||
for step in ir.steps.iter() {
|
for step in ir.steps.iter() {
|
||||||
match step {
|
match step {
|
||||||
crate::ir::Step::Type(definition) => {
|
crate::ir::Step::Type(definition) => {
|
||||||
|
debug!("Generating type {}", definition.name);
|
||||||
match compiler.generate_type(&mut ctx, &definition) {
|
match compiler.generate_type(&mut ctx, &definition) {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@ -58,6 +61,7 @@ pub fn compile<T: Compile>(ir: IR, output: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
crate::ir::Step::Enum(definition) => {
|
crate::ir::Step::Enum(definition) => {
|
||||||
|
debug!("Generating enum {}", definition.name);
|
||||||
match compiler.generate_enum(&mut ctx, &definition) {
|
match compiler.generate_enum(&mut ctx, &definition) {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@ -66,6 +70,7 @@ pub fn compile<T: Compile>(ir: IR, output: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
crate::ir::Step::Service(definition) => {
|
crate::ir::Step::Service(definition) => {
|
||||||
|
debug!("Generating service {}", definition.name);
|
||||||
match compiler.generate_service(&mut ctx, &definition) {
|
match compiler.generate_service(&mut ctx, &definition) {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use log::warn;
|
use log::warn;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use crate::compile::{Compile, CompileContext, FileGenerator};
|
use crate::compile::{Compile, CompileContext, FileGenerator};
|
||||||
use crate::ir::{BaseType, EnumDefinition, ServiceDefinition, Step, Type, TypeDefinition};
|
use crate::ir::{BaseType, EnumDefinition, ServiceDefinition, Step, Type, TypeDefinition};
|
||||||
@ -46,7 +46,7 @@ impl RustCompiler {
|
|||||||
fn add_dependencies(
|
fn add_dependencies(
|
||||||
&mut self,
|
&mut self,
|
||||||
file: &mut FileGenerator,
|
file: &mut FileGenerator,
|
||||||
depends: &HashSet<BaseType>,
|
depends: &BTreeSet<BaseType>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
for dep in depends {
|
for dep in depends {
|
||||||
match dep {
|
match dep {
|
||||||
@ -409,7 +409,7 @@ impl RustCompiler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Compile for RustCompiler {
|
impl Compile for RustCompiler {
|
||||||
fn new(options: &HashMap<String, String>) -> anyhow::Result<Self> {
|
fn new(options: &BTreeMap<String, String>) -> anyhow::Result<Self> {
|
||||||
let crate_name = if let Some(crate_name) = options.get("rust_crate") {
|
let crate_name = if let Some(crate_name) = options.get("rust_crate") {
|
||||||
crate_name.to_string()
|
crate_name.to_string()
|
||||||
} else {
|
} else {
|
||||||
@ -463,7 +463,17 @@ impl Compile for RustCompiler {
|
|||||||
|
|
||||||
self.add_dependencies(&mut f, &definition.depends)?;
|
self.add_dependencies(&mut f, &definition.depends)?;
|
||||||
|
|
||||||
f.a0("#[derive(Clone, Debug, Serialize, Deserialize)]");
|
let only_optional = definition
|
||||||
|
.fields
|
||||||
|
.iter()
|
||||||
|
.find(|f| !f.typ.is_optional())
|
||||||
|
.is_none();
|
||||||
|
|
||||||
|
let derive_default_none = if only_optional { ", Default" } else { "" };
|
||||||
|
f.a0(format!(
|
||||||
|
"#[derive(Clone, Debug, Serialize, Deserialize{})]",
|
||||||
|
derive_default_none
|
||||||
|
));
|
||||||
f.a0(format!("pub struct {} {{", definition.name));
|
f.a0(format!("pub struct {} {{", definition.name));
|
||||||
for field in definition.fields.iter() {
|
for field in definition.fields.iter() {
|
||||||
f.a(1, "#[allow(non_snake_case)]");
|
f.a(1, "#[allow(non_snake_case)]");
|
||||||
|
|||||||
@ -1,18 +1,13 @@
|
|||||||
use anyhow::{anyhow, Result};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
use log::info;
|
use log::info;
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use crate::compile::{Compile, CompileContext, FileGenerator};
|
use crate::compile::{Compile, CompileContext, FileGenerator};
|
||||||
use crate::ir::{BaseType, EnumDefinition, ServiceDefinition, Step, Type, TypeDefinition};
|
use crate::ir::{BaseType, EnumDefinition, ServiceDefinition, Step, Type, TypeDefinition};
|
||||||
|
|
||||||
use crate::IR;
|
use crate::IR;
|
||||||
|
|
||||||
// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
|
||||||
// pub enum Flavour {
|
|
||||||
// ESM,
|
|
||||||
// Node,
|
|
||||||
// }
|
|
||||||
|
|
||||||
pub trait Flavour {
|
pub trait Flavour {
|
||||||
fn ext() -> &'static str;
|
fn ext() -> &'static str;
|
||||||
fn name() -> &'static str;
|
fn name() -> &'static str;
|
||||||
@ -115,9 +110,6 @@ impl<F: Flavour> TypeScriptCompiler<F> {
|
|||||||
fn type_to_typescript_ext(typ: &Type) -> String {
|
fn type_to_typescript_ext(typ: &Type) -> String {
|
||||||
let mut result = Self::type_to_typescript(&typ.0);
|
let mut result = Self::type_to_typescript(&typ.0);
|
||||||
let (optional, array, map) = typ.1.get_flags();
|
let (optional, array, map) = typ.1.get_flags();
|
||||||
if optional {
|
|
||||||
result = format!("({} | undefined)", result);
|
|
||||||
}
|
|
||||||
if array {
|
if array {
|
||||||
result = format!("({})[]", result);
|
result = format!("({})[]", result);
|
||||||
}
|
}
|
||||||
@ -128,13 +120,17 @@ impl<F: Flavour> TypeScriptCompiler<F> {
|
|||||||
result
|
result
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if optional {
|
||||||
|
// Optional should be the last modifier
|
||||||
|
result = format!("({} | undefined)", result);
|
||||||
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_dependencies(
|
fn add_dependencies(
|
||||||
&mut self,
|
&mut self,
|
||||||
file: &mut FileGenerator,
|
file: &mut FileGenerator,
|
||||||
depends: &HashSet<BaseType>,
|
depends: &BTreeSet<BaseType>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let esm = F::ext();
|
let esm = F::ext();
|
||||||
file.a0(format!(
|
file.a0(format!(
|
||||||
@ -439,12 +435,8 @@ import {{ VerificationError }} from \"./ts_base{esm}\";
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<F: Flavour> Compile for TypeScriptCompiler<F> {
|
impl<F: Flavour> Compile for TypeScriptCompiler<F> {
|
||||||
fn new(options: &HashMap<String, String>) -> Result<Self> {
|
fn new(_options: &BTreeMap<String, String>) -> Result<Self> {
|
||||||
let flavour = options
|
info!("TypeScript target initialized with flavour: {}", F::name());
|
||||||
.get("flavour")
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or_else(|| "node".to_string());
|
|
||||||
info!("TypeScript target initialized with flavour: {}", flavour);
|
|
||||||
Ok(TypeScriptCompiler {
|
Ok(TypeScriptCompiler {
|
||||||
flavour: std::marker::PhantomData,
|
flavour: std::marker::PhantomData,
|
||||||
})
|
})
|
||||||
@ -544,7 +536,7 @@ impl<F: Flavour> Compile for TypeScriptCompiler<F> {
|
|||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let mut f = FileGenerator::new();
|
let mut f = FileGenerator::new();
|
||||||
|
|
||||||
self.add_dependencies(&mut f, &HashSet::new())?;
|
self.add_dependencies(&mut f, &BTreeSet::new())?;
|
||||||
|
|
||||||
f.a0(format!("enum {} {{", definition.name));
|
f.a0(format!("enum {} {{", definition.name));
|
||||||
for value in &definition.values {
|
for value in &definition.values {
|
||||||
|
|||||||
2
libjrpc/templates/CSharp/.gitignore
vendored
Normal file
2
libjrpc/templates/CSharp/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
bin/
|
||||||
|
obj/
|
||||||
@ -2,127 +2,142 @@
|
|||||||
import { VerificationError } from "./ts_base";
|
import { VerificationError } from "./ts_base";
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
import {
|
import {
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
type RequestObject,
|
type RequestObject,
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
type ResponseObject,
|
type ResponseObject,
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
Logging,
|
Logging,
|
||||||
//@template-ignore
|
//@template-ignore
|
||||||
} from "./ts_service_base";
|
} from "./ts_service_base";
|
||||||
|
|
||||||
export type IMessageCallback = (data: any) => void;
|
export type IMessageCallback = (data: any) => void;
|
||||||
|
|
||||||
export type ResponseListener = {
|
export type ResponseListener = {
|
||||||
ok: (response: any) => void;
|
ok: (response: any) => void;
|
||||||
err: (error: Error) => void;
|
err: (error: Error) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class Service {
|
export class Service {
|
||||||
public _name: string = null as any;
|
public _name: string = null as any;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
protected _provider: ServiceProvider,
|
protected _provider: ServiceProvider,
|
||||||
name: string,
|
name: string,
|
||||||
) {
|
) {
|
||||||
this._name = name;
|
this._name = name;
|
||||||
this._provider.services.set(name, this);
|
this._provider.services.set(name, this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ServiceProvider {
|
export class ServiceProvider {
|
||||||
services = new Map<string, Service>();
|
services = new Map<string, Service>();
|
||||||
requests = new Map<string, ResponseListener | undefined>();
|
requests = new Map<string, ResponseListener | undefined>();
|
||||||
|
|
||||||
constructor(private sendPacket: IMessageCallback) {}
|
constructor(private sendPacket: IMessageCallback) {}
|
||||||
|
|
||||||
onPacket(msg: RequestObject | ResponseObject) {
|
onPacket(msg: RequestObject | ResponseObject) {
|
||||||
Logging.log("CLIENT: Received message:", msg);
|
Logging.log("CLIENT: Received message:", msg);
|
||||||
if ("method" in msg) {
|
if ("method" in msg) {
|
||||||
if (msg.id) {
|
if (msg.id) {
|
||||||
Logging.log("CLIENT: Determined type is Request");
|
Logging.log("CLIENT: Determined type is Request");
|
||||||
// Request, which are not supported by client, so ignore
|
// Request, which are not supported by client, so ignore
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
Logging.log("CLIENT: Determined type is Notification");
|
Logging.log("CLIENT: Determined type is Notification");
|
||||||
//Notification. Send to Notification handler
|
//Notification. Send to Notification handler
|
||||||
const [srvName, fncName] = msg.method.split(".");
|
const [srvName, fncName] = msg.method.split(".");
|
||||||
let service = this.services.get(srvName);
|
let service = this.services.get(srvName);
|
||||||
if (!service) {
|
if (!service) {
|
||||||
Logging.log(
|
Logging.log(
|
||||||
"CLIENT: Did not find Service wanted by Notification!",
|
"CLIENT: Did not find Service wanted by Notification!",
|
||||||
srvName,
|
srvName,
|
||||||
);
|
);
|
||||||
|
} else {
|
||||||
|
//TODO: Implement Event thingy (or so :))
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
//TODO: Implement Event thingy (or so :))
|
Logging.log("CLIENT: Determined type is Response");
|
||||||
|
// Response
|
||||||
|
let resListener = this.requests.get(msg.id);
|
||||||
|
if (!resListener) return; // Ignore wrong responses
|
||||||
|
if (msg.error) {
|
||||||
|
if (
|
||||||
|
msg.error.data &&
|
||||||
|
msg.error.data.$ == "verification_error"
|
||||||
|
) {
|
||||||
|
resListener.err(
|
||||||
|
new VerificationError(
|
||||||
|
msg.error.data.type,
|
||||||
|
msg.error.data.field,
|
||||||
|
msg.error.data.value,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
resListener.err(new Error(msg.error.message));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
resListener.ok(msg.result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Logging.log("CLIENT: Determined type is Response");
|
|
||||||
// Response
|
|
||||||
let resListener = this.requests.get(msg.id);
|
|
||||||
if (!resListener) return; // Ignore wrong responses
|
|
||||||
if (msg.error) {
|
|
||||||
if (msg.error.data && msg.error.data.$ == "verification_error") {
|
|
||||||
resListener.err(
|
|
||||||
new VerificationError(
|
|
||||||
msg.error.data.type,
|
|
||||||
msg.error.data.field,
|
|
||||||
msg.error.data.value,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
resListener.err(new Error(msg.error.message));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
resListener.ok(msg.result);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
sendNotification(method: string, params: any[]) {
|
sendNotification(method: string, params: any[]) {
|
||||||
Logging.log("CLIENT: Sending Notification", method, params);
|
Logging.log("CLIENT: Sending Notification", method, params);
|
||||||
this.sendPacket({
|
this.sendPacket({
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
method,
|
method,
|
||||||
params,
|
params,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
sendRequest(method: string, params: any[], res?: ResponseListener) {
|
sendRequest(method: string, params: any[], res?: ResponseListener) {
|
||||||
Logging.log("CLIENT: Sending Request", method, params);
|
Logging.log("CLIENT: Sending Request", method, params);
|
||||||
const id = getRandomID(16);
|
const id = getRandomID(16);
|
||||||
this.requests.set(id, res);
|
this.requests.set(id, res);
|
||||||
this.sendPacket({
|
this.sendPacket({
|
||||||
jsonrpc: "2.0",
|
jsonrpc: "2.0",
|
||||||
method,
|
method,
|
||||||
params,
|
params,
|
||||||
id,
|
id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
declare var require: any;
|
declare var require: any;
|
||||||
export const getRandomBytes = (
|
export const getRandomBytes = (
|
||||||
typeof self !== "undefined" && (self.crypto || (self as any).msCrypto)
|
typeof self !== "undefined" && (self.crypto || (self as any).msCrypto)
|
||||||
? function () {
|
? function () {
|
||||||
// Browsers
|
// Browsers
|
||||||
var crypto = self.crypto || (self as any).msCrypto;
|
var crypto = self.crypto || (self as any).msCrypto;
|
||||||
var QUOTA = 65536;
|
var QUOTA = 65536;
|
||||||
return function (n: number) {
|
return function (n: number) {
|
||||||
var a = new Uint8Array(n);
|
var a = new Uint8Array(n);
|
||||||
for (var i = 0; i < n; i += QUOTA) {
|
for (var i = 0; i < n; i += QUOTA) {
|
||||||
crypto.getRandomValues(a.subarray(i, i + Math.min(n - i, QUOTA)));
|
crypto.getRandomValues(
|
||||||
|
a.subarray(i, i + Math.min(n - i, QUOTA)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
: function () {
|
||||||
|
// Node
|
||||||
|
if (typeof require !== "undefined") {
|
||||||
|
return require("crypto").randomBytes;
|
||||||
|
} else {
|
||||||
|
return (n: number) => {
|
||||||
|
let a = new Uint8Array(n);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
a[i] = Math.floor(Math.random() * 256);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return a;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
: function () {
|
|
||||||
// Node
|
|
||||||
return require("crypto").randomBytes;
|
|
||||||
}
|
|
||||||
)() as (cnt: number) => Uint8Array;
|
)() as (cnt: number) => Uint8Array;
|
||||||
|
|
||||||
export const getRandomID = (length: number) => {
|
export const getRandomID = (length: number) => {
|
||||||
return btoa(String.fromCharCode.apply(null, getRandomBytes(length) as any));
|
return btoa(String.fromCharCode.apply(null, getRandomBytes(length) as any));
|
||||||
};
|
};
|
||||||
|
|||||||
@ -2,8 +2,9 @@ use anyhow::Result;
|
|||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use libjrpc::{
|
use libjrpc::{
|
||||||
targets::{
|
targets::{
|
||||||
|
csharp::CSharpCompiler,
|
||||||
rust::RustCompiler,
|
rust::RustCompiler,
|
||||||
typescript::{Node, TypeScriptCompiler},
|
typescript::{Node, TypeScriptCompiler, ESM},
|
||||||
},
|
},
|
||||||
FileProcessor,
|
FileProcessor,
|
||||||
};
|
};
|
||||||
@ -65,8 +66,9 @@ pub fn main() -> Result<()> {
|
|||||||
libjrpc::targets::compile::<TypeScriptCompiler<Node>>(ir, output_dir)?
|
libjrpc::targets::compile::<TypeScriptCompiler<Node>>(ir, output_dir)?
|
||||||
}
|
}
|
||||||
"ts-esm" => {
|
"ts-esm" => {
|
||||||
libjrpc::targets::compile::<TypeScriptCompiler<Node>>(ir, output_dir)?
|
libjrpc::targets::compile::<TypeScriptCompiler<ESM>>(ir, output_dir)?
|
||||||
}
|
}
|
||||||
|
"csharp" => libjrpc::targets::compile::<CSharpCompiler>(ir, output_dir)?,
|
||||||
_ => {
|
_ => {
|
||||||
println!("Unsupported target: {}", output_target);
|
println!("Unsupported target: {}", output_target);
|
||||||
}
|
}
|
||||||
@ -83,6 +85,7 @@ pub fn main() -> Result<()> {
|
|||||||
println!("rust");
|
println!("rust");
|
||||||
println!("ts-node");
|
println!("ts-node");
|
||||||
println!("ts-esm");
|
println!("ts-esm");
|
||||||
|
println!("csharp")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
14
src/test.rs
14
src/test.rs
@ -6,12 +6,12 @@ use std::{
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn compare_tools() {
|
fn compare_tools() {
|
||||||
let targets = vec!["rust"];
|
let targets = vec!["js-esm"];
|
||||||
for target in targets {
|
for target in targets {
|
||||||
std::fs::remove_dir_all("./tests").unwrap();
|
std::fs::remove_dir_all("./tests").unwrap();
|
||||||
std::fs::create_dir_all("./tests").unwrap();
|
std::fs::create_dir_all("./tests").unwrap();
|
||||||
|
|
||||||
Command::new("cargo")
|
let result1 = Command::new("cargo")
|
||||||
.arg("run")
|
.arg("run")
|
||||||
.arg("--")
|
.arg("--")
|
||||||
.arg("compile")
|
.arg("compile")
|
||||||
@ -26,7 +26,11 @@ fn compare_tools() {
|
|||||||
.wait()
|
.wait()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
Command::new("node")
|
if !result1.success() {
|
||||||
|
panic!("Failed to generate Rust code");
|
||||||
|
}
|
||||||
|
|
||||||
|
let result2 = Command::new("node")
|
||||||
.arg("JsonRPC/lib/jrpc.js")
|
.arg("JsonRPC/lib/jrpc.js")
|
||||||
.arg("compile")
|
.arg("compile")
|
||||||
.arg("--verbose")
|
.arg("--verbose")
|
||||||
@ -40,6 +44,10 @@ fn compare_tools() {
|
|||||||
.wait()
|
.wait()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
if !result2.success() {
|
||||||
|
panic!("Failed to generate JavaScript code");
|
||||||
|
}
|
||||||
|
|
||||||
let rust_files = walkdir::WalkDir::new("tests/rust")
|
let rust_files = walkdir::WalkDir::new("tests/rust")
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|e| e.unwrap())
|
.map(|e| e.unwrap())
|
||||||
|
|||||||
Reference in New Issue
Block a user