Compare commits
No commits in common. "c6af431292f1407951ae814dc015319ac6664ec5" and "58e00a9ca3f47556a443266e751baf772da9d547" have entirely different histories.
c6af431292
...
58e00a9ca3
@ -9,5 +9,3 @@ insert_final_newline = true
|
||||
indent_size = 2
|
||||
[*.md]
|
||||
indent_size = 2
|
||||
[*.zig]
|
||||
indent_size = 4
|
||||
|
7
.gitignore
vendored
7
.gitignore
vendored
@ -6,12 +6,5 @@ examples/CSharp/Generated
|
||||
examples/CSharp/Example/bin
|
||||
examples/CSharp/Example/obj
|
||||
examples/definition.json
|
||||
examples/Rust/Gen
|
||||
examples/Rust/Impl/target
|
||||
examples/Dart/out
|
||||
templates/CSharp/bin
|
||||
templates/CSharp/obj
|
||||
lib/
|
||||
templates/Dart/.dart_tool
|
||||
templates/Dart/.packages
|
||||
templates/Dart/pubspec.lock
|
42
.vscode/tasks.json
vendored
42
.vscode/tasks.json
vendored
@ -1,42 +0,0 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"build",
|
||||
"${workspaceFolder}/examples/CSharp/Example/CSharp_Example.csproj",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "publish",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/examples/CSharp/Example/CSharp_Example.csproj",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "watch",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"watch",
|
||||
"run",
|
||||
"${workspaceFolder}/examples/CSharp/Example/CSharp_Example.csproj",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
}
|
||||
]
|
||||
}
|
@ -1,5 +1,4 @@
|
||||
nodeLinker: node-modules
|
||||
npmRegistryServer: https://npm.hibas123.de
|
||||
|
||||
plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
|
||||
|
@ -4,57 +4,47 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
class TestSrvimpl : Example.TestServiceServer<int>
|
||||
{
|
||||
public TestSrvimpl() : base() { }
|
||||
public override async Task<Example.AddValueResponse> AddValuesSingleParam(AddValueRequest request, int ctx)
|
||||
{
|
||||
class TestSrvimpl : Example.TestServiceServer<int> {
|
||||
public TestSrvimpl(): base() {}
|
||||
public override async Task<Example.AddValueResponse> AddValuesSingleParam(AddValueRequest request, int ctx) {
|
||||
var res = new Example.AddValueResponse();
|
||||
res.value = 1;
|
||||
return res;
|
||||
}
|
||||
|
||||
public override async Task<double> AddValuesMultipleParams(double value1, double value2, int ctx)
|
||||
{
|
||||
public override async Task<double> AddValuesMultipleParams(double value1,double value2,int ctx) {
|
||||
return value1 + value2;
|
||||
}
|
||||
|
||||
public override async Task ReturningVoid(double param1, int ctx)
|
||||
{
|
||||
public override async Task ReturningVoid(double param1,int ctx) {
|
||||
|
||||
}
|
||||
|
||||
public override void OnEvent(string param1, int ctx)
|
||||
{
|
||||
public override void OnEvent(string param1,int ctx) {
|
||||
Console.WriteLine($"OnEvent {param1}");
|
||||
}
|
||||
|
||||
public override async Task<IList<double>> FunctionWithArrayAsParamAndReturn(List<double> values1, List<double> values2, int ctx)
|
||||
{
|
||||
public override async Task<IList<double>> FunctionWithArrayAsParamAndReturn(List<double> values1,List<double> values2, int ctx) {
|
||||
var l = new List<double>();
|
||||
l.Append(1);
|
||||
return l;
|
||||
}
|
||||
|
||||
public override async Task ThrowingError(int ctx)
|
||||
{
|
||||
public override async Task ThrowingError(int ctx) {
|
||||
throw new Exception("This is a remote error :)");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CopyTransportS2 : Example.JRpcTransport
|
||||
{
|
||||
class CopyTransportS2 : Example.JRpcTransport {
|
||||
CopyTransportS1 tr1;
|
||||
public Queue<string> backlog = new Queue<string>();
|
||||
|
||||
public CopyTransportS2(CopyTransportS1 tr1)
|
||||
{
|
||||
public CopyTransportS2(CopyTransportS1 tr1) {
|
||||
this.tr1 = tr1;
|
||||
}
|
||||
|
||||
public override Task Write(string data)
|
||||
{
|
||||
public override Task Write(string data) {
|
||||
Console.WriteLine("--> " + data);
|
||||
this.tr1.SendPacketEvent(data);
|
||||
|
||||
@ -62,34 +52,28 @@ class CopyTransportS2 : Example.JRpcTransport
|
||||
}
|
||||
}
|
||||
|
||||
class CopyTransportS1 : Example.JRpcTransport
|
||||
{
|
||||
class CopyTransportS1 : Example.JRpcTransport {
|
||||
public Queue<string> backlog = new Queue<string>();
|
||||
|
||||
public CopyTransportS2 tr2;
|
||||
|
||||
public CopyTransportS1()
|
||||
{
|
||||
public CopyTransportS1() {
|
||||
this.tr2 = new CopyTransportS2(this);
|
||||
}
|
||||
|
||||
public override Task Write(string data)
|
||||
{
|
||||
public override Task Write(string data) {
|
||||
Console.WriteLine("<-- " + data);
|
||||
this.tr2.SendPacketEvent(data);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
public static void Main()
|
||||
{
|
||||
class Program {
|
||||
public static void Main() {
|
||||
Program.Start().Wait();
|
||||
}
|
||||
|
||||
public static async Task Start()
|
||||
{
|
||||
public static async Task Start() {
|
||||
var server = new Example.JRpcServer<int>();
|
||||
server.AddService(new TestSrvimpl());
|
||||
var transport = new CopyTransportS1();
|
||||
@ -98,19 +82,11 @@ class Program
|
||||
var client = new Example.JRpcClient(transport.tr2);
|
||||
var testService = new Example.TestServiceClient(client);
|
||||
|
||||
var result = await testService.AddValuesMultipleParams(1, 2);
|
||||
var result = await testService.AddValuesMultipleParams(1,2);
|
||||
|
||||
Console.WriteLine($"Add 1 + 2 = {result}");
|
||||
|
||||
try
|
||||
{
|
||||
await testService.ThrowingError();
|
||||
throw new Exception("No error was issued, even though it was expected!");
|
||||
}
|
||||
catch (JRpcException err)
|
||||
{
|
||||
Console.WriteLine("Error successfully catched: ", err.Message);
|
||||
}
|
||||
await testService.ThrowingError();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,42 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import "./out/lib/example.dart";
|
||||
import "dart:convert";
|
||||
|
||||
void main() async {
|
||||
var str = StreamController<Map<String, dynamic>>();
|
||||
|
||||
var provider = ServiceProvider(str.stream);
|
||||
var sock = await Socket.connect("127.0.0.1", 8859);
|
||||
|
||||
utf8.decoder.bind(sock).transform(new LineSplitter()).listen((line) {
|
||||
str.add(jsonDecode(line));
|
||||
});
|
||||
|
||||
provider.output.stream.listen((event) {
|
||||
sock.writeln(jsonEncode(event));
|
||||
});
|
||||
|
||||
var s = new TestServiceClient(provider);
|
||||
|
||||
var r = await s.AddValuesMultipleParams(10, 15);
|
||||
print(r);
|
||||
|
||||
var r2 =
|
||||
await s.AddValuesSingleParam(AddValueRequest(value1: 10, value2: 15));
|
||||
print(r2?.value);
|
||||
|
||||
var catched = false;
|
||||
await s.ThrowingError().catchError((err) {
|
||||
catched = true;
|
||||
print("Expected error was catched: " + err.toString());
|
||||
});
|
||||
|
||||
if (!catched) {
|
||||
throw Error();
|
||||
}
|
||||
|
||||
await sock.close();
|
||||
// exit(0);
|
||||
}
|
2
examples/Rust/.gitignore
vendored
2
examples/Rust/.gitignore
vendored
@ -1,2 +0,0 @@
|
||||
Generated/
|
||||
Impl/target
|
248
examples/Rust/Impl/Cargo.lock
generated
248
examples/Rust/Impl/Cargo.lock
generated
@ -1,248 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "0.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.0",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.1.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "int-enum"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b1428b2b1abe959e6eedb0a17d0ab12f6ba20e1106cc29fc4874e3ba393c177"
|
||||
dependencies = [
|
||||
"cfg-if 0.1.10",
|
||||
"int-enum-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "int-enum-impl"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c3cecaad8ca1a5020843500c696de2b9a07b63b624ddeef91f85f9bafb3671"
|
||||
dependencies = [
|
||||
"cfg-if 0.1.10",
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.123"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb691a747a7ab48abc15c5b42066eaafde10dc427e3b6ee2a1cf43db04c763bd"
|
||||
|
||||
[[package]]
|
||||
name = "nanoid"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
|
||||
dependencies = [
|
||||
"rand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_cpus"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785"
|
||||
dependencies = [
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1"
|
||||
dependencies = [
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.136"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.136"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.91"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "test"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"int-enum",
|
||||
"nanoid",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"threadpool",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "test-impl"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"test",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "threadpool"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa"
|
||||
dependencies = [
|
||||
"num_cpus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.0+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
@ -1,7 +0,0 @@
|
||||
[package]
|
||||
name = "test-impl"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
test = { path = "../Generated/" }
|
@ -1,52 +0,0 @@
|
||||
use test::{JRPCServer,Result,Test};
|
||||
use test::server::{TestService,TestServiceHandler};
|
||||
use std::io::{BufReader,BufRead,Write};
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct MyCtx {}
|
||||
|
||||
struct TestServiceImplementation {}
|
||||
|
||||
impl TestService<MyCtx> for TestServiceImplementation {
|
||||
fn GetTest(&self, name: String, age: i64, _context: &MyCtx) -> Result<Test> {
|
||||
return Ok(Test { name, age });
|
||||
}
|
||||
|
||||
fn TestNot(&self, _: &MyCtx) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main() {
|
||||
let mut srv = JRPCServer::<MyCtx>::new();
|
||||
srv.add_service(TestServiceHandler::new(Box::from(TestServiceImplementation {})));
|
||||
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:4321").expect("Could not start listener!");
|
||||
|
||||
for stream in listener.incoming() {
|
||||
println!("Got Connection!");
|
||||
let (stx, srx) = channel::<String>();
|
||||
let (rtx, rrx) = channel::<String>();
|
||||
|
||||
let mut stream = stream.expect("Bad stream");
|
||||
let mut r = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
|
||||
srv.start_session(srx, rtx, MyCtx {});
|
||||
|
||||
|
||||
r.read_line(&mut line).expect("Could not read line!");
|
||||
println!("Got line: {}", line);
|
||||
stx.send(line).expect("Could not send packet to handler!");
|
||||
println!("Sending to handler succeeded");
|
||||
let response = rrx.recv().expect("Could not get reponse from handler!");
|
||||
println!("Prepared response {}", response);
|
||||
|
||||
stream.write((response + "\n").as_bytes()).expect("Could not send reponse!");
|
||||
}
|
||||
|
||||
println!("Hello World");
|
||||
|
||||
// return Ok(());
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
|
||||
import * as net from "net";
|
||||
import { Server, AddValueRequest, AddValueResponse } from "./out";
|
||||
import * as readline from 'node:readline';
|
||||
|
||||
|
||||
const server = new Server.ServiceProvider();
|
||||
|
||||
class TestService extends Server.TestService<undefined> {
|
||||
async AddValuesSingleParam(
|
||||
request: AddValueRequest,
|
||||
ctx: undefined
|
||||
): Promise<AddValueResponse> {
|
||||
return {
|
||||
value: request.value1 + request!.value2,
|
||||
};
|
||||
}
|
||||
async AddValuesMultipleParams(
|
||||
value1: number,
|
||||
value2: number,
|
||||
ctx: undefined
|
||||
): Promise<number> {
|
||||
return value1 + value2;
|
||||
}
|
||||
|
||||
async ReturningVoid(param1) {
|
||||
console.log("Calling Returning Void");
|
||||
}
|
||||
|
||||
OnEvent(param1: string, ctx: undefined): void {
|
||||
console.log("Received notification", param1);
|
||||
}
|
||||
|
||||
async FunctionWithArrayAsParamAndReturn(vals1, vals2) {
|
||||
return [...vals1, ...vals2];
|
||||
}
|
||||
|
||||
async ThrowingError(ctx: undefined): Promise<void> {
|
||||
throw new Error("Remote error!");
|
||||
}
|
||||
}
|
||||
|
||||
server.addService(new TestService());
|
||||
|
||||
net.createServer((socket) => {
|
||||
socket.on("error", console.error);
|
||||
|
||||
console.log("Connection from:", socket.remoteAddress);
|
||||
const sess = server.getSession(msg => {
|
||||
const s = JSON.stringify(msg);
|
||||
console.log("Sending:", s);
|
||||
socket.write(s + "\n");
|
||||
});
|
||||
const rl = readline.createInterface(socket);
|
||||
rl.on("line", line => {
|
||||
console.log("Receiving:", line);
|
||||
sess.onMessage(JSON.parse(line));
|
||||
})
|
||||
rl.on("error", console.error);
|
||||
}).listen(8859).on("listening", () => {
|
||||
console.log("Is listening on :8859");
|
||||
}).on("error", console.error)
|
@ -22,7 +22,7 @@ class TestService extends Server.TestService<undefined> {
|
||||
ctx: undefined
|
||||
): Promise<AddValueResponse> {
|
||||
return {
|
||||
value: request.value1 + request!.value2,
|
||||
value: request.value1 + request.value2,
|
||||
};
|
||||
}
|
||||
async AddValuesMultipleParams(
|
||||
|
2
examples/Zig/.gitignore
vendored
2
examples/Zig/.gitignore
vendored
@ -1,2 +0,0 @@
|
||||
zig-cache/
|
||||
generated/
|
@ -1,34 +0,0 @@
|
||||
const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.build.Builder) void {
|
||||
// Standard target options allows the person running `zig build` to choose
|
||||
// what target to build for. Here we do not override the defaults, which
|
||||
// means any target is allowed, and the default is native. Other options
|
||||
// for restricting supported target set are available.
|
||||
const target = b.standardTargetOptions(.{});
|
||||
|
||||
// Standard release options allow the person running `zig build` to select
|
||||
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
|
||||
const mode = b.standardReleaseOptions();
|
||||
|
||||
const exe = b.addExecutable("ZigTests", "src/main.zig");
|
||||
exe.setTarget(target);
|
||||
exe.setBuildMode(mode);
|
||||
exe.install();
|
||||
|
||||
const run_cmd = exe.run();
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
if (b.args) |args| {
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
|
||||
const exe_tests = b.addTest("src/main.zig");
|
||||
exe_tests.setTarget(target);
|
||||
exe_tests.setBuildMode(mode);
|
||||
|
||||
const test_step = b.step("test", "Run unit tests");
|
||||
test_step.dependOn(&exe_tests.step);
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
const std = @import("std");
|
||||
const t = @import("./generated/mod.zig");
|
||||
|
||||
var mygpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const gpa = mygpa.allocator();
|
||||
|
||||
const payload =
|
||||
\\{
|
||||
\\ "val_number": 0.12,
|
||||
\\ "val_boolean": true,
|
||||
\\ "val_string": "Hallo Welt"
|
||||
\\}
|
||||
;
|
||||
|
||||
pub fn main() !void {
|
||||
var stream = std.json.TokenStream.init(payload);
|
||||
const res = std.json.parse(t.TestAtom, &stream, .{ .allocator = gpa }) catch unreachable;
|
||||
|
||||
std.log.info("{} {s}", .{ res, res.val_string });
|
||||
}
|
@ -1,8 +1,6 @@
|
||||
import "./import";
|
||||
|
||||
define csharp_namespace Example;
|
||||
define rust_crate example;
|
||||
define dart_library_name example;
|
||||
|
||||
enum TestEnum {
|
||||
VAL1,
|
||||
@ -16,17 +14,17 @@ type Test {
|
||||
atom: TestAtom;
|
||||
array: TestAtom[];
|
||||
enumValue: TestEnum;
|
||||
map: {int, TestAtom};
|
||||
map: {number, TestAtom};
|
||||
}
|
||||
|
||||
|
||||
type AddValueRequest {
|
||||
value1: float;
|
||||
value2: float;
|
||||
value1: number;
|
||||
value2: number;
|
||||
}
|
||||
|
||||
type AddValueResponse {
|
||||
value: float;
|
||||
value: number;
|
||||
}
|
||||
|
||||
service TestService {
|
||||
@ -38,11 +36,11 @@ service TestService {
|
||||
@Description("Add two numbers")
|
||||
@Param("value1", "The first value")
|
||||
@Param("value2", "The second value")
|
||||
AddValuesMultipleParams(value1: float, value2: float): float;
|
||||
AddValuesMultipleParams(value1: number, value2: number): number;
|
||||
|
||||
@Description("Does literaly nothing")
|
||||
@Param("param1", "Some number")
|
||||
ReturningVoid(param1: float): void;
|
||||
ReturningVoid(param1: number): void;
|
||||
|
||||
@Description("Just sends an Event with a String")
|
||||
@Param("param1", "Parameter with some string for event")
|
||||
@ -51,5 +49,5 @@ service TestService {
|
||||
ThrowingError(): void;
|
||||
|
||||
|
||||
FunctionWithArrayAsParamAndReturn(values1: float[], values2: float[]): float[];
|
||||
FunctionWithArrayAsParamAndReturn(values1: number[], values2: number[]): number[];
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
type TestAtom {
|
||||
val_number: float;
|
||||
val_number: number;
|
||||
val_boolean: boolean;
|
||||
val_string: string;
|
||||
}
|
||||
|
@ -1,14 +0,0 @@
|
||||
define rust_crate test;
|
||||
|
||||
type Test {
|
||||
name: string;
|
||||
age: int;
|
||||
}
|
||||
|
||||
service TestService {
|
||||
@Description("asdasdasd")
|
||||
GetTest(name: string, age: int): Test;
|
||||
notification TestNot();
|
||||
}
|
||||
|
||||
// { "jsonrpc": "2.0", "method": "TestService.GetTest", "params": [ "SomeName", 25 ], "id": "someid" }
|
10866
lib/jrpc.js
Executable file
10866
lib/jrpc.js
Executable file
File diff suppressed because it is too large
Load Diff
12
meta.json
12
meta.json
@ -1,12 +0,0 @@
|
||||
{
|
||||
"name": "jsonrpc",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "Fabian Stamm <dev@fabianstamm.de>",
|
||||
"contributors": [],
|
||||
"files": [
|
||||
"**/*.ts",
|
||||
"**/*.js",
|
||||
"README.md"
|
||||
]
|
||||
}
|
20
package.json
20
package.json
@ -1,17 +1,16 @@
|
||||
{
|
||||
"name": "@hibas123/jrpcgen",
|
||||
"version": "1.1.6",
|
||||
"version": "1.0.29",
|
||||
"main": "lib/index.js",
|
||||
"license": "MIT",
|
||||
"packageManager": "yarn@3.1.1",
|
||||
"scripts": {
|
||||
"start": "ts-node src/index.ts",
|
||||
"test-start": "npm run start -- compile examples/example.jrpc --definition=examples/definition.json -o=ts-node:examples/Typescript/out -o=c#:examples/CSharp/Generated -o=rust:examples/Rust/Generated -o=zig:examples/Zig/generated",
|
||||
"test-start": "npm run start -- compile examples/example.jrpc --definition=examples/definition.json -o=ts-node:examples/Typescript/out -o=c#:examples/CSharp/Generated",
|
||||
"test-csharp": "cd examples/CSharp/Example/ && dotnet run",
|
||||
"test-typescript": "cd examples/Typescript && ts-node test.ts",
|
||||
"test-rust": "cd examples/Rust/Generated/ && cargo build",
|
||||
"test-typescript": "ts-node examples/test.ts",
|
||||
"test": "npm run test-start && npm run test-csharp && npm run test-typescript",
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --target=node16 --outfile=lib/jrpc.js",
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --target=node14 --outfile=lib/jrpc.js",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"bin": {
|
||||
@ -19,15 +18,8 @@
|
||||
},
|
||||
"files": [
|
||||
"lib/jrpc.js",
|
||||
"templates/*.ts",
|
||||
"templates/CSharp/*.cs",
|
||||
"templates/CSharp/*.csproj",
|
||||
"templates/Rust/Cargo.toml",
|
||||
"templates/Rust/src/lib.rs",
|
||||
"templates/Dart/service_client.dart",
|
||||
"templates/Dart/base.dart",
|
||||
"templates/Dart/pubspec.yaml",
|
||||
"examples/*.jrpcproj",
|
||||
"templates/**",
|
||||
"examples/**",
|
||||
"src/**",
|
||||
"tsconfig.json"
|
||||
],
|
||||
|
@ -1,5 +1,5 @@
|
||||
import * as FS from "fs";
|
||||
import * as FSE from "fs-extra";
|
||||
import * as FSE from "fs-extra"
|
||||
import * as Path from "path";
|
||||
import {
|
||||
EnumDefinition,
|
||||
@ -11,10 +11,7 @@ import {
|
||||
|
||||
export abstract class CompileTarget<T = any> {
|
||||
abstract name: string;
|
||||
constructor(
|
||||
private outputFolder: string,
|
||||
protected options: T & { allow_bytes: boolean }
|
||||
) {
|
||||
constructor(private outputFolder: string, protected options: T & { use_messagepack: boolean }) {
|
||||
if (!FS.existsSync(outputFolder)) {
|
||||
FS.mkdirSync(outputFolder, {
|
||||
recursive: true,
|
||||
@ -33,13 +30,12 @@ export abstract class CompileTarget<T = any> {
|
||||
abstract finalize(steps: Step[]): void;
|
||||
|
||||
protected writeFile(name: string, content: string | Promise<string>) {
|
||||
let resPath = Path.join(this.outputFolder, name);
|
||||
let resDir = Path.dirname(resPath);
|
||||
if (!FS.existsSync(resDir)) FS.mkdirSync(resDir, { recursive: true });
|
||||
if (content instanceof Promise) {
|
||||
content.then((res) => FS.writeFileSync(resPath, res));
|
||||
content.then((res) =>
|
||||
FS.writeFileSync(Path.join(this.outputFolder, name), res)
|
||||
);
|
||||
} else {
|
||||
FS.writeFileSync(resPath, content);
|
||||
FS.writeFileSync(Path.join(this.outputFolder, name), content);
|
||||
}
|
||||
}
|
||||
|
||||
@ -63,10 +59,12 @@ export abstract class CompileTarget<T = any> {
|
||||
return res.join("\n");
|
||||
}
|
||||
|
||||
protected loadTemplateFolder(name: string) {
|
||||
protected loadTemplateFolder(name:string) {
|
||||
let root = Path.join(__dirname, "../templates/", name);
|
||||
|
||||
FSE.copySync(root, this.outputFolder, {});
|
||||
FSE.copySync(root, this.outputFolder, {
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
25
src/index.ts
25
src/index.ts
@ -44,29 +44,22 @@ yargs(hideBin(process.argv))
|
||||
});
|
||||
},
|
||||
(argv) => {
|
||||
if (argv.verbose) {
|
||||
dbg.enable("app");
|
||||
}
|
||||
if (argv.verbose) {dbg.enable("app");}
|
||||
log("Received compile command with args", argv);
|
||||
|
||||
startCompile({
|
||||
input: argv.input,
|
||||
targets: argv.output as any,
|
||||
emitDefinitions: argv.definition,
|
||||
});
|
||||
}
|
||||
)
|
||||
.command(
|
||||
"targets",
|
||||
"List all targets",
|
||||
(yargs) => yargs,
|
||||
() => {
|
||||
console.log("Targets:");
|
||||
Targets.forEach((__dirname, target) => {
|
||||
console.log(" " + target);
|
||||
});
|
||||
emitDefinitions: argv.definition
|
||||
})
|
||||
}
|
||||
)
|
||||
.command("targets", "List all targets", (yargs)=>yargs, ()=>{
|
||||
console.log("Targets:")
|
||||
Targets.forEach((__dirname, target) => {
|
||||
console.log(" " + target);
|
||||
})
|
||||
})
|
||||
.option("verbose", {
|
||||
alias: "v",
|
||||
type: "boolean",
|
||||
|
122
src/ir.ts
122
src/ir.ts
@ -2,7 +2,7 @@ import type { Parsed, StatementNode } from "./parser";
|
||||
import dbg from "debug";
|
||||
const log = dbg("app");
|
||||
|
||||
export const BUILTIN = ["float", "int", "string", "boolean"];
|
||||
const BUILTIN = ["number", "string", "boolean"];
|
||||
|
||||
export class IRError extends Error {
|
||||
constructor(public statement: StatementNode, message: string) {
|
||||
@ -36,17 +36,17 @@ export interface EnumDefinition {
|
||||
export type ServiceFunctionDecorators = {
|
||||
description: string;
|
||||
parameters: {
|
||||
name: string;
|
||||
name:string;
|
||||
description: string;
|
||||
}[];
|
||||
returns: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ServiceFunctionParamsDefinition {
|
||||
name: string;
|
||||
inputs: { type: string; name: string; array: boolean }[];
|
||||
return: { type: string; array: boolean } | undefined;
|
||||
decorators: ServiceFunctionDecorators;
|
||||
inputs: { type: string; name: string, array: boolean }[];
|
||||
return: { type: string, array: boolean } | undefined;
|
||||
decorators: ServiceFunctionDecorators
|
||||
}
|
||||
export type ServiceFunctionDefinition = ServiceFunctionParamsDefinition;
|
||||
|
||||
@ -62,8 +62,8 @@ export type Step = [
|
||||
];
|
||||
|
||||
export type IR = {
|
||||
options: { [key: string]: string };
|
||||
steps: Step[];
|
||||
options: { [key:string]: string},
|
||||
steps: Step[]
|
||||
};
|
||||
|
||||
export default function get_ir(parsed: Parsed): IR {
|
||||
@ -101,10 +101,7 @@ export default function get_ir(parsed: Parsed): IR {
|
||||
}
|
||||
|
||||
if (defined.indexOf(field.fieldtype) < 0) {
|
||||
if (
|
||||
builtin.indexOf(field.fieldtype) < 0 &&
|
||||
field.fieldtype !== statement.name
|
||||
) {
|
||||
if (builtin.indexOf(field.fieldtype) < 0 && field.fieldtype !== statement.name) {
|
||||
throw new IRError(
|
||||
field,
|
||||
`Type ${field.fieldtype} is not defined!`
|
||||
@ -115,7 +112,11 @@ export default function get_ir(parsed: Parsed): IR {
|
||||
depends.push(field.fieldtype);
|
||||
}
|
||||
|
||||
if (field.map && field.map !== "int" && field.map !== "string") {
|
||||
if (
|
||||
field.map &&
|
||||
field.map !== "number" &&
|
||||
field.map !== "string"
|
||||
) {
|
||||
throw new IRError(
|
||||
field,
|
||||
`Type ${field.map} is not valid as map key!`
|
||||
@ -199,10 +200,7 @@ export default function get_ir(parsed: Parsed): IR {
|
||||
if (!depends.some((a) => a === fnc.return_type.type))
|
||||
depends.push(fnc.return_type.type);
|
||||
} else {
|
||||
if (
|
||||
fnc.return_type.type !== "void" &&
|
||||
builtin.indexOf(fnc.return_type.type) < 0
|
||||
) {
|
||||
if (fnc.return_type.type !== "void" && builtin.indexOf(fnc.return_type.type) < 0) {
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Type ${fnc.return_type.type} is not defined`
|
||||
@ -227,73 +225,51 @@ export default function get_ir(parsed: Parsed): IR {
|
||||
|
||||
let decorators = {} as ServiceFunctionDecorators;
|
||||
|
||||
fnc.decorators.forEach((values, key) => {
|
||||
for (const val of values) {
|
||||
switch (key) {
|
||||
fnc.decorators.forEach((values, key)=>{
|
||||
for(const val of values) {
|
||||
switch(key) {
|
||||
case "Description":
|
||||
if (decorators.description)
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Description' can only be used once!`
|
||||
);
|
||||
if (val.length != 1)
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Description' requires exactly one parameter!`
|
||||
);
|
||||
if(decorators.description)
|
||||
throw new IRError(fnc, `Decorator 'Description' can only be used once!`);
|
||||
if(val.length != 1)
|
||||
throw new IRError(fnc, `Decorator 'Description' requires exactly one parameter!`);
|
||||
decorators.description = val[0];
|
||||
break;
|
||||
case "Returns":
|
||||
if (decorators.returns)
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Returns' can only be used once!`
|
||||
);
|
||||
if (val.length != 1)
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Returns' requires exactly one parameter!`
|
||||
);
|
||||
decorators.returns = val[0];
|
||||
break;
|
||||
if(decorators.returns)
|
||||
throw new IRError(fnc, `Decorator 'Returns' can only be used once!`);
|
||||
if(val.length != 1)
|
||||
throw new IRError(fnc, `Decorator 'Returns' requires exactly one parameter!`);
|
||||
decorators.returns = val[0];
|
||||
break;
|
||||
case "Param":
|
||||
if (!decorators.parameters) decorators.parameters = [];
|
||||
if (val.length != 2)
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Param' requires exactly two parameters!`
|
||||
);
|
||||
if(!decorators.parameters)
|
||||
decorators.parameters = [];
|
||||
if(val.length != 2)
|
||||
throw new IRError(fnc, `Decorator 'Param' requires exactly two parameters!`);
|
||||
const [name, description] = val;
|
||||
if (!fnc.inputs.find((e) => e.name == name))
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Param' requires the first param to equal the name of a function parameter!`
|
||||
);
|
||||
if (decorators.parameters.find((e) => e.name == name))
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator 'Param' has already been set for the parameter ${name}!`
|
||||
);
|
||||
if(!fnc.inputs.find(e=>e.name == name))
|
||||
throw new IRError(fnc, `Decorator 'Param' requires the first param to equal the name of a function parameter!`);
|
||||
if(decorators.parameters.find(e=>e.name == name))
|
||||
throw new IRError(fnc, `Decorator 'Param' has already been set for the parameter ${name}!`);
|
||||
|
||||
decorators.parameters.push({
|
||||
name,
|
||||
description,
|
||||
});
|
||||
})
|
||||
break;
|
||||
default:
|
||||
throw new IRError(
|
||||
fnc,
|
||||
`Decorator ${key} is not a valid decorator!`
|
||||
);
|
||||
throw new IRError(fnc, `Decorator ${key} is not a valid decorator!`);
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
|
||||
return {
|
||||
name: fnc.name,
|
||||
inputs: fnc.inputs,
|
||||
return: fnc.return_type,
|
||||
decorators,
|
||||
decorators
|
||||
} as ServiceFunctionDefinition;
|
||||
});
|
||||
|
||||
@ -305,26 +281,18 @@ export default function get_ir(parsed: Parsed): IR {
|
||||
functions,
|
||||
} as ServiceDefinition,
|
||||
]);
|
||||
} else if (statement.type == "define") {
|
||||
} else if(statement.type == "define") {
|
||||
options[statement.key] = statement.value;
|
||||
if (
|
||||
(statement.key == "use_messagepack" ||
|
||||
statement.key == "allow_bytes") &&
|
||||
statement.value == "true"
|
||||
) {
|
||||
options["allow_bytes"] = true;
|
||||
if(statement.key == "use_messagepack" && statement.value == "true") {
|
||||
builtin.push("bytes");
|
||||
}
|
||||
} else {
|
||||
throw new IRError(
|
||||
statement,
|
||||
"Invalid statement: " + (statement as any).type
|
||||
);
|
||||
throw new IRError(statement, "Invalid statement!");
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
options,
|
||||
steps,
|
||||
steps
|
||||
};
|
||||
}
|
||||
|
111
src/process.ts
111
src/process.ts
@ -2,8 +2,6 @@ import dbg from "debug";
|
||||
import * as FS from "fs";
|
||||
import Color from "chalk";
|
||||
import * as Path from "path";
|
||||
import * as Https from "https";
|
||||
import * as Http from "http";
|
||||
import tokenize, { TokenizerError } from "./tokenizer";
|
||||
import parse, { Parsed, ParserError } from "./parser";
|
||||
import get_ir, { IR, IRError } from "./ir";
|
||||
@ -13,10 +11,6 @@ import {
|
||||
NodeJSTypescriptTarget,
|
||||
} from "./targets/typescript";
|
||||
import { CSharpTarget } from "./targets/csharp";
|
||||
import { RustTarget } from "./targets/rust";
|
||||
import { ZIGTarget } from "./targets/zig";
|
||||
import { DartTarget } from "./targets/dart";
|
||||
import { URL } from "url";
|
||||
|
||||
class CatchedError extends Error {}
|
||||
|
||||
@ -27,9 +21,7 @@ export const Targets = new Map<string, typeof CompileTarget>();
|
||||
Targets.set("ts-esm", ESMTypescriptTarget);
|
||||
Targets.set("ts-node", NodeJSTypescriptTarget);
|
||||
Targets.set("c#", CSharpTarget as typeof CompileTarget);
|
||||
Targets.set("rust", RustTarget as typeof CompileTarget);
|
||||
Targets.set("zig", ZIGTarget as typeof CompileTarget);
|
||||
Targets.set("dart", DartTarget as typeof CompileTarget);
|
||||
|
||||
|
||||
function indexToLineAndCol(src: string, index: number) {
|
||||
let line = 1;
|
||||
@ -46,63 +38,26 @@ function indexToLineAndCol(src: string, index: number) {
|
||||
return { line, col };
|
||||
}
|
||||
|
||||
function resolve(base: string, ...parts: string[]) {
|
||||
if (base.startsWith("http://") || base.startsWith("https://")) {
|
||||
let u = new URL(base);
|
||||
for (const part of parts) {
|
||||
u = new URL(part, u);
|
||||
}
|
||||
return u.href;
|
||||
} else {
|
||||
return Path.resolve(base, ...parts);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchFileFromURL(url: string) {
|
||||
return new Promise<string>((yes, no) => {
|
||||
const makeReq = url.startsWith("https://") ? Https.request : Http.request;
|
||||
const req = makeReq(url, (res) => {
|
||||
let chunks: Buffer[] = [];
|
||||
res.on("data", (chunk) => {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
});
|
||||
res.on("error", no);
|
||||
res.on("end", () => yes(Buffer.concat(chunks).toString("utf-8")));
|
||||
});
|
||||
|
||||
req.on("error", no);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
const fileCache = new Map<string, string>();
|
||||
|
||||
async function getFile(name: string) {
|
||||
function getFile(name: string) {
|
||||
if (fileCache.has(name)) return fileCache.get(name);
|
||||
else {
|
||||
try {
|
||||
if (name.startsWith("http://") || name.startsWith("https://")) {
|
||||
const data = await fetchFileFromURL(name);
|
||||
fileCache.set(name, data);
|
||||
return data;
|
||||
} else {
|
||||
const data = FS.readFileSync(name, "utf-8");
|
||||
fileCache.set(name, data);
|
||||
return data;
|
||||
}
|
||||
const data = FS.readFileSync(name, "utf-8");
|
||||
fileCache.set(name, data);
|
||||
return data;
|
||||
} catch (err) {
|
||||
log(err);
|
||||
await printError(new Error(`Cannot open file ${name};`), null, 0);
|
||||
printError(new Error(`Cannot open file ${name};`), null, 0);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function printError(err: Error, file: string | null, idx: number) {
|
||||
function printError(err: Error, file: string | null, idx: number) {
|
||||
let loc = { line: 0, col: 0 };
|
||||
if (file != null) {
|
||||
const data = getFile(file);
|
||||
if (data) loc = indexToLineAndCol(await data, idx);
|
||||
if (data) loc = indexToLineAndCol(data, idx);
|
||||
}
|
||||
|
||||
console.error(`${Color.red("ERROR: at")} ${file}:${loc.line}:${loc.col}`);
|
||||
@ -126,21 +81,21 @@ type ProcessContext = {
|
||||
processedFiles: Set<string>;
|
||||
};
|
||||
|
||||
async function processFile(
|
||||
function processFile(
|
||||
ctx: ProcessContext,
|
||||
file: string,
|
||||
root = false
|
||||
): Promise<Parsed | null> {
|
||||
file = resolve(file);
|
||||
): Parsed | null {
|
||||
file = Path.resolve(file);
|
||||
if (ctx.processedFiles.has(file)) {
|
||||
log("Skipping file %s since it has already been processed", file);
|
||||
log("Skipping file %s since it has already be processed", file);
|
||||
return null;
|
||||
}
|
||||
ctx.processedFiles.add(file);
|
||||
log("Processing file %s", file);
|
||||
|
||||
const content = await getFile(file);
|
||||
if (content == undefined) throw new Error("Could not open file " + file);
|
||||
const content = getFile(file);
|
||||
if (!content) throw new Error("Could not open file " + file);
|
||||
try {
|
||||
log("Tokenizing %s", file);
|
||||
const tokens = tokenize(content);
|
||||
@ -148,29 +103,27 @@ async function processFile(
|
||||
const parsed = parse(tokens, file);
|
||||
|
||||
log("Resolving imports of %s", file);
|
||||
let resolved: Parsed = [];
|
||||
for (const statement of parsed) {
|
||||
if (statement.type == "import") {
|
||||
let res: string;
|
||||
if (file.startsWith("http://") || file.startsWith("https://")) {
|
||||
res = resolve(file, statement.path + ".jrpc");
|
||||
} else {
|
||||
let resolved = parsed
|
||||
.map((statement) => {
|
||||
if (statement.type == "import") {
|
||||
const base = Path.dirname(file);
|
||||
res = resolve(base, statement.path + ".jrpc");
|
||||
const resolved = Path.resolve(
|
||||
Path.join(base, statement.path + ".jrpc")
|
||||
);
|
||||
return processFile(ctx, resolved);
|
||||
} else {
|
||||
return statement;
|
||||
}
|
||||
resolved.push(...((await processFile(ctx, res)) || []));
|
||||
} else {
|
||||
resolved.push(statement);
|
||||
}
|
||||
}
|
||||
|
||||
return resolved.filter((e) => !!e).flat(1) as Parsed;
|
||||
})
|
||||
.filter((e) => !!e)
|
||||
.flat(1) as Parsed;
|
||||
return resolved;
|
||||
} catch (err) {
|
||||
if (err instanceof TokenizerError) {
|
||||
await printError(err, file, err.index);
|
||||
printError(err, file, err.index);
|
||||
if (!root) throw new CatchedError();
|
||||
} else if (err instanceof ParserError) {
|
||||
await printError(err, file, err.token.startIdx);
|
||||
printError(err, file, err.token.startIdx);
|
||||
if (!root) throw new CatchedError();
|
||||
} else if (root && err instanceof CatchedError) {
|
||||
return null;
|
||||
@ -180,7 +133,7 @@ async function processFile(
|
||||
}
|
||||
}
|
||||
|
||||
export default async function startCompile(options: CompileOptions) {
|
||||
export default function startCompile(options: CompileOptions) {
|
||||
const ctx = {
|
||||
options,
|
||||
processedFiles: new Set(),
|
||||
@ -190,14 +143,14 @@ export default async function startCompile(options: CompileOptions) {
|
||||
if (options.input.endsWith(".json")) {
|
||||
ir = JSON.parse(FS.readFileSync(options.input, "utf-8"));
|
||||
} else {
|
||||
const parsed = await processFile(ctx, options.input, true);
|
||||
const parsed = processFile(ctx, options.input, true);
|
||||
|
||||
if (!parsed) process.exit(1); // Errors should have already been emitted
|
||||
try {
|
||||
ir = get_ir(parsed);
|
||||
} catch (err) {
|
||||
if (err instanceof IRError) {
|
||||
await printError(
|
||||
printError(
|
||||
err,
|
||||
err.statement.location.file,
|
||||
err.statement.location.idx
|
||||
|
@ -7,15 +7,15 @@ import {
|
||||
} from "../ir";
|
||||
|
||||
import { CompileTarget } from "../compile";
|
||||
import { LineAppender } from "../utils";
|
||||
|
||||
type lineAppender = (ind: number, line: string | string[]) => void;
|
||||
|
||||
const conversion = {
|
||||
boolean: "bool",
|
||||
int: "long",
|
||||
float: "double",
|
||||
number: "double",
|
||||
string: "string",
|
||||
void: "void",
|
||||
bytes: "",
|
||||
bytes: ""
|
||||
};
|
||||
|
||||
function toCSharpType(type: string): string {
|
||||
@ -30,8 +30,8 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.options.allow_bytes == true) {
|
||||
throw new Error("C# has no support for 'bytes' yet!");
|
||||
if(this.options.use_messagepack == true) {
|
||||
throw new Error("C# has no support for MessagePack yet!");
|
||||
}
|
||||
this.writeFile(
|
||||
this.namespace + ".csproj",
|
||||
@ -51,7 +51,13 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
}
|
||||
|
||||
generateType(definition: TypeDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
a(0, `using System.Text.Json;`);
|
||||
a(0, `using System.Text.Json.Serialization;`);
|
||||
@ -84,11 +90,17 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
}
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`${definition.name}.cs`, getResult());
|
||||
this.writeFile(`${definition.name}.cs`, lines.join("\n"));
|
||||
}
|
||||
|
||||
generateEnum(definition: EnumDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
a(0, `using System.Text.Json;`);
|
||||
a(0, `using System.Text.Json.Serialization;`);
|
||||
@ -101,11 +113,17 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
}
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`${definition.name}.cs`, getResult());
|
||||
this.writeFile(`${definition.name}.cs`, lines.join("\n"));
|
||||
}
|
||||
|
||||
generateServiceClient(definition: ServiceDefinition) {
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
a(0, `using System;`);
|
||||
a(0, `using System.Text.Json;`);
|
||||
@ -183,11 +201,17 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
// a(0, ``);
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`${definition.name}Client.cs`, getResult());
|
||||
this.writeFile(`${definition.name}Client.cs`, lines.join("\n"));
|
||||
}
|
||||
|
||||
generateServiceServer(definition: ServiceDefinition) {
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
a(0, `using System;`);
|
||||
a(0, `using System.Text.Json;`);
|
||||
@ -306,7 +330,7 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
a(1, `}`);
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`${definition.name}Server.cs`, getResult());
|
||||
this.writeFile(`${definition.name}Server.cs`, lines.join("\n"));
|
||||
}
|
||||
|
||||
generateService(definition: ServiceDefinition): void {
|
||||
|
@ -1,279 +0,0 @@
|
||||
import { TypeDefinition, ServiceDefinition, EnumDefinition, Step } from "../ir";
|
||||
|
||||
import { CompileTarget } from "../compile";
|
||||
import { LineAppender, lineAppender } from "../utils";
|
||||
import chalk from "chalk";
|
||||
|
||||
const conversion = {
|
||||
boolean: "bool",
|
||||
int: "int",
|
||||
float: "double",
|
||||
string: "String",
|
||||
void: "void",
|
||||
// bytes: "Uint8List", //TODO: Check this
|
||||
};
|
||||
|
||||
function toDartType(type: string): string {
|
||||
return (conversion as any)[type] || type;
|
||||
}
|
||||
|
||||
export class DartTarget extends CompileTarget<{ dart_library_name: string }> {
|
||||
name: string = "dart";
|
||||
|
||||
start(): void {
|
||||
if (this.options.allow_bytes == true) {
|
||||
throw new Error("Dart has no support for 'bytes' yet!");
|
||||
}
|
||||
|
||||
if (!this.options.dart_library_name) {
|
||||
throw new Error("Setting dart_library_name is required for DART target!");
|
||||
}
|
||||
}
|
||||
|
||||
getImport(name: string) {
|
||||
return `import "./${name}.dart";`;
|
||||
}
|
||||
|
||||
generateImports(a: lineAppender, def: TypeDefinition | ServiceDefinition) {
|
||||
a(0, `import "./base.dart";`)
|
||||
def.depends.forEach((dep) => {
|
||||
a(0, this.getImport(dep));
|
||||
});
|
||||
}
|
||||
|
||||
getTypeParse(type: string, value: string) {
|
||||
if (conversion[type]) {
|
||||
return `${toDartType(type)}_fromJson(${value})`;
|
||||
} else {
|
||||
return `${toDartType(type)}.fromJson(${value})`;
|
||||
}
|
||||
}
|
||||
|
||||
generateType(definition: TypeDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
this.generateImports(a, definition);
|
||||
|
||||
a(0, ``);
|
||||
a(0, `class ${definition.name} {`);
|
||||
for (const field of definition.fields) {
|
||||
if (field.array) {
|
||||
a(1, `List<${toDartType(field.type)}>? ${field.name};`);
|
||||
} else if (field.map) {
|
||||
a(
|
||||
1,
|
||||
`Map<${toDartType(field.map)},${toDartType(field.type)}>? ${field.name
|
||||
};`
|
||||
);
|
||||
} else {
|
||||
a(1, `${toDartType(field.type)}? ${field.name};`);
|
||||
}
|
||||
}
|
||||
|
||||
a(0, ``);
|
||||
a(
|
||||
1,
|
||||
`${definition.name}({${definition.fields
|
||||
.map((e) => `this.${e.name}`)
|
||||
.join(", ")}});`
|
||||
);
|
||||
a(0, ``);
|
||||
a(1, `${definition.name}.fromJson(Map<String, dynamic> json) {`);
|
||||
for (const field of definition.fields) {
|
||||
a(2, `if(json.containsKey("${field.name}")) {`);
|
||||
|
||||
if (field.array) {
|
||||
a(3, `this.${field.name} = [];`);
|
||||
a(3, `(json["${field.name}"] as List<dynamic>).forEach((e) => {`);
|
||||
a(4, `this.${field.name}!.add(${this.getTypeParse(field.type, "e")})`);
|
||||
a(3, `});`);
|
||||
} else if (field.map) {
|
||||
a(3, `this.${field.name} = {};`);
|
||||
a(
|
||||
3,
|
||||
`(json["${field.name}"] as Map<${toDartType(
|
||||
field.map
|
||||
)},dynamic>).forEach((key, value) => {`
|
||||
);
|
||||
a(4, `this.${field.name}![key] = ${this.getTypeParse(field.type, "value")}`);
|
||||
a(3, `});`);
|
||||
} else {
|
||||
a(
|
||||
3,
|
||||
`this.${field.name} = ${this.getTypeParse(field.type, `json["${field.name}"]`)};`
|
||||
);
|
||||
}
|
||||
a(2, `} else {`);
|
||||
a(3, `this.${field.name} = null;`);
|
||||
a(2, `}`);
|
||||
a(0, ``);
|
||||
}
|
||||
|
||||
a(1, `}`);
|
||||
|
||||
a(1, `Map<String, dynamic> toJson() {`);
|
||||
a(2, `Map<String, dynamic> res = {};`);
|
||||
for (const field of definition.fields) {
|
||||
if (conversion[field.type]) {
|
||||
a(2, `res["${field.name}"] = this.${field.name};`);
|
||||
} else {
|
||||
if (field.array) {
|
||||
a(
|
||||
2,
|
||||
`res["${field.name}"] = this.${field.name}?.map((entry) => entry.toJson()).toList();`
|
||||
);
|
||||
} else if (field.map) {
|
||||
// dict.map((key, value) => MapEntry(key, value.toString()));
|
||||
a(
|
||||
2,
|
||||
`res["${field.name}"] = this.${field.name}?.map((key, value) => MapEntry(key, value.toJson()));`
|
||||
);
|
||||
} else {
|
||||
a(2, `res["${field.name}"] = this.${field.name};`);
|
||||
}
|
||||
}
|
||||
}
|
||||
a(2, `return res;`);
|
||||
a(1, `}`);
|
||||
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`lib/src/${definition.name}.dart`, getResult());
|
||||
}
|
||||
|
||||
generateEnum(definition: EnumDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
a(0, `enum ${definition.name} {`);
|
||||
for (const entry of definition.values) {
|
||||
const isLast =
|
||||
definition.values[definition.values.length - 1] == entry;
|
||||
a(1, `${entry.name}(${entry.value})${isLast ? ";" : ","}`);
|
||||
}
|
||||
a(0, ``);
|
||||
a(1, `final int val;`);
|
||||
a(1, `const ${definition.name}(int valT) : val= valT;`);
|
||||
a(1, `static ${definition.name}? fromJson(int val) {`);
|
||||
a(2, `switch(val){`);
|
||||
for (const entry of definition.values) {
|
||||
a(3, `case ${entry.value}:`);
|
||||
a(4, `return ${definition.name}.${entry.name};`);
|
||||
}
|
||||
a(3, `default:`);
|
||||
a(4, `return null;`);
|
||||
a(2, `}`);
|
||||
a(1, `}`);
|
||||
|
||||
a(0, ``);
|
||||
|
||||
a(1, `int toJson() {`);
|
||||
a(2, `return this.val;`);
|
||||
a(1, `}`);
|
||||
|
||||
a(0, ``);
|
||||
a(0, `}`);
|
||||
|
||||
a(0, ``);
|
||||
|
||||
this.writeFile(`lib/src/${definition.name}.dart`, getResult());
|
||||
}
|
||||
|
||||
generateServiceClient(definition: ServiceDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
this.generateImports(a, definition);
|
||||
a(0, `import "./service_client.dart";`);
|
||||
a(0, ``);
|
||||
a(0, `class ${definition.name}Client extends Service {`);
|
||||
a(0, ``);
|
||||
|
||||
a(1, `${definition.name}Client(ServiceProvider provider):super(provider, "${definition.name}");`);
|
||||
|
||||
a(0, ``);
|
||||
|
||||
for (const func of definition.functions) {
|
||||
const args = func.inputs.map(inp =>
|
||||
(inp.array ? `List<${toDartType(inp.type)}>` : toDartType(inp.type)) + " " + inp.name
|
||||
).join(", ");
|
||||
|
||||
const asParams = func.inputs.map(e => e.name).join(", ");
|
||||
|
||||
if (!func.return) {
|
||||
a(1, `void ${func.name}(${args}) {`)
|
||||
a(2, `provider.sendNotification("${definition.name}.${func.name}", [${asParams}]);`);
|
||||
a(1, `}`);
|
||||
} else {
|
||||
const baseReturnType = func.return.type != "void" ? (toDartType(func.return.type) + "?") : toDartType(func.return.type);
|
||||
const returnType = func.return.array ? `List<${baseReturnType}>` : baseReturnType;
|
||||
|
||||
a(1, `Future<${returnType}> ${func.name}(${args}) async {`);
|
||||
a(2, `var res = await this.provider.sendRequest("${definition.name}.${func.name}", [${asParams}]);`);
|
||||
if (func.return.type !== "void") {
|
||||
if(func.return.array) {
|
||||
a(2, `return res.map((entry) =>${this.getTypeParse(func.return.type, "entry")}).toList();`);
|
||||
} else {
|
||||
a(2, `return ${this.getTypeParse(func.return.type, "res")};`);
|
||||
}
|
||||
}
|
||||
a(1, `}`);
|
||||
}
|
||||
a(0, ``);
|
||||
}
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
|
||||
this.writeFile(`lib/src/${definition.name}Client.dart`, getResult());
|
||||
}
|
||||
|
||||
generateServiceServer(definition: ServiceDefinition): void {
|
||||
console.log(
|
||||
chalk.yellow("[DART] WARNING:"),
|
||||
"DART support for services is not yet there. Service generation is currently limited to clients!"
|
||||
);
|
||||
}
|
||||
|
||||
generateService(definition: ServiceDefinition): void {
|
||||
this.generateServiceClient(definition);
|
||||
this.writeFile("lib/src/service_client.dart", this.getTemplate("Dart/service_client.dart"))
|
||||
}
|
||||
|
||||
finalize(steps: Step[]): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
a(0, `library ${this.options.dart_library_name};`)
|
||||
a(0, ``);
|
||||
|
||||
|
||||
let hasService = false;
|
||||
|
||||
|
||||
steps.forEach(([type, def]) => {
|
||||
switch (type) {
|
||||
case "type":
|
||||
a(0, `export 'src/${def.name}.dart';`);
|
||||
break;
|
||||
case "enum":
|
||||
a(0, `export 'src/${def.name}.dart';`);
|
||||
break;
|
||||
case "service":
|
||||
a(0, `export 'src/${def.name}Client.dart';`);
|
||||
hasService = true;
|
||||
break;
|
||||
default:
|
||||
console.warn(
|
||||
chalk.yellow("[DART] WARNING:"),
|
||||
"unimplemented step found:",
|
||||
type
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (hasService) {
|
||||
a(0, `export 'src/service_client.dart';`)
|
||||
}
|
||||
|
||||
this.writeFile(`lib/${this.options.dart_library_name}.dart`, getResult());
|
||||
this.writeFile(`pubspec.yaml`, this.getTemplate("Dart/pubspec.yaml").replace("__NAME__", this.options.dart_library_name));
|
||||
this.writeFile(`lib/src/base.dart`, this.getTemplate("Dart/base.dart"));
|
||||
}
|
||||
}
|
@ -1,331 +0,0 @@
|
||||
import chalk from "chalk";
|
||||
import { CompileTarget } from "../compile";
|
||||
import { TypeDefinition, EnumDefinition, ServiceDefinition, Step } from "../ir";
|
||||
import { lineAppender, LineAppender } from "../utils";
|
||||
|
||||
const conversion = {
|
||||
boolean: "bool",
|
||||
float: "f64",
|
||||
int: "i64",
|
||||
string: "String",
|
||||
void: "()",
|
||||
bytes: "Vec<u8>",
|
||||
};
|
||||
|
||||
function toRustType(type: string): string {
|
||||
return (conversion as any)[type] || type;
|
||||
}
|
||||
|
||||
function toSnake(input: string) {
|
||||
return (
|
||||
input[0].toLowerCase() +
|
||||
input.slice(1).replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
|
||||
);
|
||||
}
|
||||
|
||||
export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
name: string = "rust";
|
||||
|
||||
get crate() {
|
||||
return this.options.rust_crate;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (!this.crate)
|
||||
throw new Error(
|
||||
"Setting a crate name is required. Add the following to your jrpc file: 'define rust_crate <name>'"
|
||||
);
|
||||
|
||||
if (this.options.allow_bytes == true) {
|
||||
throw new Error("Rust has no support for 'bytes' yet!");
|
||||
}
|
||||
|
||||
this.writeFile(
|
||||
"Cargo.toml",
|
||||
this.getTemplate("Rust/Cargo.toml").replace("__name__", this.crate)
|
||||
);
|
||||
|
||||
this.writeFile("src/base_lib.rs", this.getTemplate("Rust/src/lib.rs"));
|
||||
}
|
||||
|
||||
private addDependencies(
|
||||
a: lineAppender,
|
||||
def: TypeDefinition | ServiceDefinition
|
||||
) {
|
||||
for (const dep of def.depends) {
|
||||
a(0, `use crate::${dep};`);
|
||||
}
|
||||
|
||||
a(0, ``);
|
||||
a(0, ``);
|
||||
}
|
||||
|
||||
generateType(definition: TypeDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
if (definition.fields.find((e) => e.map))
|
||||
a(0, `use std::collections::hash_map::HashMap;`);
|
||||
a(0, `use serde::{Deserialize, Serialize};`);
|
||||
this.addDependencies(a, definition);
|
||||
|
||||
a(0, `#[derive(Clone, Debug, Serialize, Deserialize)]`);
|
||||
a(0, `pub struct ${definition.name} {`);
|
||||
for (const field of definition.fields) {
|
||||
if (field.array) {
|
||||
a(1, `pub ${field.name}: Vec<${toRustType(field.type)}>,`);
|
||||
} else if (field.map) {
|
||||
a(
|
||||
1,
|
||||
`pub ${field.name}: HashMap<${toRustType(
|
||||
field.map
|
||||
)}, ${toRustType(field.type)}>,`
|
||||
);
|
||||
} else {
|
||||
a(1, `pub ${field.name}: ${toRustType(field.type)},`);
|
||||
}
|
||||
}
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`src/${toSnake(definition.name)}.rs`, getResult());
|
||||
}
|
||||
|
||||
generateEnum(definition: EnumDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
a(0, `use int_enum::IntEnum;`);
|
||||
a(0, `use serde::{Deserialize, Serialize};`);
|
||||
|
||||
a(0, ``);
|
||||
a(0, ``);
|
||||
|
||||
a(0, `#[repr(i64)]`);
|
||||
a(
|
||||
0,
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum, Deserialize, Serialize)]"
|
||||
);
|
||||
a(0, `pub enum ${definition.name} {`);
|
||||
for (const field of definition.values) {
|
||||
a(1, `${field.name} = ${field.value},`);
|
||||
}
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFile(`src/${toSnake(definition.name)}.rs`, getResult());
|
||||
}
|
||||
|
||||
private generateServiceClient(definition: ServiceDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
const typeToRust = (type: string, array: boolean) => {
|
||||
let rt = toRustType(type);
|
||||
return array ? `Vec<${rt}>` : rt;
|
||||
};
|
||||
|
||||
this.addDependencies(a, definition);
|
||||
|
||||
a(0, `use crate::base_lib::{JRPCClient,JRPCRequest,Result};`);
|
||||
a(0, `use serde_json::{json};`);
|
||||
a(0, ``);
|
||||
a(0, `pub struct ${definition.name}{`);
|
||||
a(1, `client: JRPCClient,`);
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
|
||||
a(0, `impl ${definition.name} {`);
|
||||
a(1, `pub fn new(client: JRPCClient) -> Self {`);
|
||||
a(2, `return Self { client };`);
|
||||
a(1, `}`);
|
||||
a(0, ``);
|
||||
for (const fnc of definition.functions) {
|
||||
let params = fnc.inputs
|
||||
.map((i) => i.name + ": " + typeToRust(i.type, i.array))
|
||||
.join(", ");
|
||||
let ret = fnc.return
|
||||
? typeToRust(fnc.return.type, fnc.return.array)
|
||||
: "()";
|
||||
a(1, `pub fn ${fnc.name}(&self, ${params}) -> Result<${ret}> {`);
|
||||
a(2, `let l_req = JRPCRequest {`);
|
||||
a(3, `jsonrpc: "2.0".to_owned(),`);
|
||||
a(3, `id: None, // 'id' will be set by the send_request function`);
|
||||
a(3, `method: "${definition.name}.${fnc.name}".to_owned(),`);
|
||||
a(3, `params: json!([${fnc.inputs.map((e) => e.name)}])`);
|
||||
a(2, `};`);
|
||||
a(2, ``);
|
||||
if (fnc.return) {
|
||||
a(2, `let l_res = self.client.send_request(l_req);`);
|
||||
a(2, `if let Err(e) = l_res {`);
|
||||
a(3, `return Err(e);`);
|
||||
a(2, `} else if let Ok(o) = l_res {`);
|
||||
if (fnc.return.type == "void") {
|
||||
a(3, `return ();`);
|
||||
} else {
|
||||
a(
|
||||
3,
|
||||
`return serde_json::from_value(o).map_err(|e| Box::from(e));`
|
||||
);
|
||||
}
|
||||
a(2, `} else { panic!("What else cases could there be?"); }`);
|
||||
} else {
|
||||
a(2, `self.client.send_notification(l_req);`);
|
||||
a(2, `return Ok(());`);
|
||||
}
|
||||
a(1, `}`);
|
||||
}
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
|
||||
this.writeFile(`src/client/${toSnake(definition.name)}.rs`, getResult());
|
||||
}
|
||||
|
||||
private generateServiceServer(definition: ServiceDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
this.addDependencies(a, definition);
|
||||
a(0, `use crate::base_lib::{JRPCServiceHandler,JRPCRequest,Result};`);
|
||||
a(0, `use serde_json::{Value};`);
|
||||
|
||||
const typeToRust = (type: string, array: boolean) => {
|
||||
let rt = toRustType(type);
|
||||
return array ? `Vec<${rt}>` : rt;
|
||||
};
|
||||
|
||||
const CTX_TYPE = "'static + Sync + Send + Copy";
|
||||
|
||||
a(0, ``);
|
||||
a(0, `pub trait ${definition.name}<C: ${CTX_TYPE}> {`);
|
||||
for (const fnc of definition.functions) {
|
||||
let params =
|
||||
fnc.inputs.length > 0
|
||||
? fnc.inputs
|
||||
.map((i) => i.name + ": " + typeToRust(i.type, i.array))
|
||||
.join(", ") + ", "
|
||||
: "";
|
||||
let ret = fnc.return
|
||||
? typeToRust(fnc.return.type, fnc.return.array)
|
||||
: "()";
|
||||
a(1, `fn ${fnc.name}(&self, ${params}context: &C) -> Result<${ret}>;`);
|
||||
}
|
||||
a(0, `}`);
|
||||
|
||||
a(0, ``);
|
||||
a(0, `pub struct ${definition.name}Handler<C: ${CTX_TYPE}> {`);
|
||||
a(1, `implementation: Box<dyn ${definition.name}<C> + Sync + Send>,`);
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
a(0, `impl<C: ${CTX_TYPE}> ${definition.name}Handler<C> {`);
|
||||
a(
|
||||
1,
|
||||
`pub fn new(implementation: Box<dyn ${definition.name}<C> + Sync + Send>) -> Box<Self> {`
|
||||
);
|
||||
a(2, `return Box::from(Self { implementation });`);
|
||||
a(1, `}`);
|
||||
a(0, `}`);
|
||||
|
||||
a(0, ``);
|
||||
|
||||
a(
|
||||
0,
|
||||
`impl<C: ${CTX_TYPE}> JRPCServiceHandler<C> for ${definition.name}Handler<C> {`
|
||||
);
|
||||
|
||||
a(1, `fn get_name(&self) -> String { "${definition.name}".to_owned() }`);
|
||||
a(0, ``);
|
||||
|
||||
a(
|
||||
1,
|
||||
`fn on_message(&self, msg: JRPCRequest, function: String, ctx: &C) -> Result<(bool, Value)> {`
|
||||
);
|
||||
a(2, `match function.as_str() {`);
|
||||
for (const fnc of definition.functions) {
|
||||
a(3, `"${fnc.name}" => {`);
|
||||
a(4, `if msg.params.is_array() {`);
|
||||
if (fnc.inputs.length > 0) {
|
||||
a(
|
||||
5,
|
||||
`let arr = msg.params.as_array().unwrap(); //TODO: Check if this can fail.`
|
||||
);
|
||||
}
|
||||
a(5, `let res = self.implementation.${fnc.name}(`);
|
||||
for (let i = 0; i < fnc.inputs.length; i++) {
|
||||
const inp = fnc.inputs[i];
|
||||
a(6, `serde_json::from_value(arr[${i}].clone())`);
|
||||
a(
|
||||
7,
|
||||
`.map_err(|_| "Parameter for field '${inp.name}' should be of type '${inp.type}'!")?,` //TODO: Array
|
||||
);
|
||||
}
|
||||
a(5, `ctx)?;`);
|
||||
if (fnc.return) {
|
||||
a(5, `return Ok((true, serde_json::to_value(res)?));`);
|
||||
} else {
|
||||
a(5, `_ = res;`);
|
||||
a(5, `return Ok((false, Value::Null))`);
|
||||
}
|
||||
a(4, `} else if msg.params.is_object() {`);
|
||||
a(5, `return Err(Box::from("Not implemented yet".to_owned()));`);
|
||||
a(4, `} else {`);
|
||||
a(5, `return Err(Box::from("Invalid parameters??".to_owned()));`);
|
||||
a(4, `}`);
|
||||
a(3, `},`);
|
||||
}
|
||||
a(
|
||||
3,
|
||||
`_ => { return Err(Box::from(format!("Invalid function {}", function).to_owned())) ;},`
|
||||
);
|
||||
a(2, `}`);
|
||||
a(1, `}`);
|
||||
a(0, `}`);
|
||||
this.writeFile(`src/server/${toSnake(definition.name)}.rs`, getResult());
|
||||
}
|
||||
|
||||
generateService(definition: ServiceDefinition): void {
|
||||
console.log(
|
||||
chalk.yellow("[RUST] WARNING:"),
|
||||
"Rust support for services is WIP. Use with care!"
|
||||
);
|
||||
this.generateServiceServer(definition);
|
||||
this.generateServiceClient(definition);
|
||||
}
|
||||
|
||||
private generateLib(steps: Step[]) {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
const lc = LineAppender();
|
||||
const ls = LineAppender();
|
||||
|
||||
const ac = lc.a;
|
||||
const as = ls.a;
|
||||
|
||||
a(0, `pub mod base_lib;`);
|
||||
a(0, `pub use base_lib::{JRPCServer,Result};`);
|
||||
|
||||
for (const [typ, def] of steps) {
|
||||
if (typ == "type" || typ == "enum") {
|
||||
a(0, `mod ${toSnake(def.name)};`);
|
||||
a(0, `pub use ${toSnake(def.name)}::${def.name};`);
|
||||
} else if (typ == "service") {
|
||||
as(0, `mod ${toSnake(def.name)};`);
|
||||
as(
|
||||
0,
|
||||
`pub use ${toSnake(def.name)}::{${def.name}, ${
|
||||
def.name
|
||||
}Handler};`
|
||||
);
|
||||
|
||||
ac(0, `mod ${toSnake(def.name)};`);
|
||||
ac(0, `pub use ${toSnake(def.name)}::${def.name};`);
|
||||
|
||||
a(0, `pub mod server;`);
|
||||
a(0, `pub mod client;`);
|
||||
}
|
||||
}
|
||||
|
||||
this.writeFile(`src/lib.rs`, getResult());
|
||||
this.writeFile(`src/server/mod.rs`, ls.getResult());
|
||||
this.writeFile(`src/client/mod.rs`, lc.getResult());
|
||||
}
|
||||
|
||||
finalize(steps: Step[]): void {
|
||||
this.generateLib(steps);
|
||||
// throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
@ -7,16 +7,16 @@ import {
|
||||
} from "../ir";
|
||||
|
||||
import { CompileTarget } from "../compile";
|
||||
import { LineAppender, lineAppender } from "../utils";
|
||||
// import * as prettier from "prettier";
|
||||
|
||||
type lineAppender = (ind: number, line: string | string[]) => void;
|
||||
|
||||
const conversion = {
|
||||
boolean: "boolean",
|
||||
int: "number",
|
||||
float: "number",
|
||||
number: "number",
|
||||
string: "string",
|
||||
void: "void",
|
||||
bytes: "Uint8Array",
|
||||
bytes: "Uint8Array"
|
||||
};
|
||||
|
||||
function toJSType(type: string): string {
|
||||
@ -45,14 +45,17 @@ export class TypescriptTarget extends CompileTarget {
|
||||
a(
|
||||
0,
|
||||
this.generateImport(
|
||||
`{ VerificationError, apply_int, apply_float, apply_string, apply_boolean, apply_void }`,
|
||||
`{ VerificationError, apply_number, apply_string, apply_boolean, apply_void }`,
|
||||
`./ts_base`
|
||||
)
|
||||
);
|
||||
a(
|
||||
0,
|
||||
def.depends.map((dep) =>
|
||||
this.generateImport(`${dep}, { apply_${dep} }`, "./" + dep)
|
||||
this.generateImport(
|
||||
`${dep}, { apply_${dep} }`,
|
||||
"./" + dep
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
@ -72,7 +75,13 @@ export class TypescriptTarget extends CompileTarget {
|
||||
}
|
||||
|
||||
generateType(def: TypeDefinition) {
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
this.generateImports(a, def);
|
||||
a(0, `export default class ${def.name} {`);
|
||||
@ -119,29 +128,17 @@ export class TypescriptTarget extends CompileTarget {
|
||||
`export function apply_${def.name}(data: ${def.name}): ${def.name} {`
|
||||
);
|
||||
{
|
||||
a(
|
||||
1,
|
||||
`if(typeof data !== "object") throw new VerificationError("${def.name}", undefined, data);`
|
||||
);
|
||||
a(1, `if(typeof data !== "object") throw new VerificationError("${def.name}", undefined, data);`)
|
||||
a(1, `let res = new ${def.name}() as any;`);
|
||||
def.fields.forEach((field) => {
|
||||
a(
|
||||
1,
|
||||
`if(data["${field.name}"] !== null && data["${field.name}"] !== undefined) {`
|
||||
);
|
||||
a(1, `if(data["${field.name}"] !== null && data["${field.name}"] !== undefined) {`)
|
||||
if (field.array) {
|
||||
a(
|
||||
2,
|
||||
`if(!Array.isArray(data["${field.name}"])) throw new VerificationError("array", "${field.name}", data["${field.name}"]);`
|
||||
);
|
||||
a(2, `if(!Array.isArray(data["${field.name}"])) throw new VerificationError("array", "${field.name}", data["${field.name}"]);`)
|
||||
a(2, `res["${field.name}"] = data["${field.name}"].map(elm=>`);
|
||||
a(3, `apply_${field.type}(elm)`);
|
||||
a(2, `)`);
|
||||
} else if (field.map) {
|
||||
a(
|
||||
2,
|
||||
`if(typeof data["${field.name}"] !== "object") throw new VerificationError("map", "${field.name}", data["${field.name}"]);`
|
||||
);
|
||||
a(2, `if(typeof data["${field.name}"] !== "object") throw new VerificationError("map", "${field.name}", data["${field.name}"]);`)
|
||||
a(2, `res["${field.name}"] = {}`);
|
||||
a(
|
||||
2,
|
||||
@ -161,12 +158,17 @@ export class TypescriptTarget extends CompileTarget {
|
||||
|
||||
a(0, ``);
|
||||
|
||||
this.writeFormattedFile(this.getFileName(def.name), getResult());
|
||||
this.writeFormattedFile(this.getFileName(def.name), lines.join("\n"));
|
||||
}
|
||||
|
||||
generateEnum(def: EnumDefinition) {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
a(0, this.generateImport("{ VerificationError }", "./ts_base"));
|
||||
|
||||
a(0, `enum ${def.name} {`);
|
||||
@ -193,7 +195,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
a(1, `return data;`);
|
||||
a(0, `}`);
|
||||
|
||||
this.writeFormattedFile(this.getFileName(def.name), getResult());
|
||||
this.writeFormattedFile(this.getFileName(def.name), lines.join("\n"));
|
||||
}
|
||||
|
||||
generateServiceClient(def: ServiceDefinition) {
|
||||
@ -208,7 +210,13 @@ export class TypescriptTarget extends CompileTarget {
|
||||
this.getTemplate("ts_service_client.ts")
|
||||
);
|
||||
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
this.generateImports(a, def);
|
||||
|
||||
@ -247,7 +255,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
// }
|
||||
|
||||
if (!fnc.return) {
|
||||
a(1, `${fnc.name}(${params}): void {`);
|
||||
a(1, `${fnc.name}(${params}): void {`);1
|
||||
a(2, `this._provider.sendMessage({`);
|
||||
a(3, `jsonrpc: "2.0",`);
|
||||
a(3, `method: "${def.name}.${fnc.name}",`);
|
||||
@ -287,12 +295,18 @@ export class TypescriptTarget extends CompileTarget {
|
||||
|
||||
this.writeFormattedFile(
|
||||
this.getFileName(def.name + "_client"),
|
||||
getResult()
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
generateServiceServer(def: ServiceDefinition) {
|
||||
const { a, getResult } = LineAppender();
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
this.writeFormattedFile(
|
||||
"service_server.ts",
|
||||
@ -347,10 +361,6 @@ export class TypescriptTarget extends CompileTarget {
|
||||
a(2, `let p: any[] = [];`);
|
||||
a(2, `if(Array.isArray(params)){`);
|
||||
a(3, `p = params;`);
|
||||
a(3, `while(p.length < ${fnc.inputs.length})`);
|
||||
a(4, `p.push(undefined);`);
|
||||
a(3, `if(p.length > ${fnc.inputs.length})`);
|
||||
a(4, `throw new Error("Too many parameters!");`);
|
||||
a(2, `} else {`);
|
||||
for (const param of fnc.inputs) {
|
||||
a(3, `p.push(params["${param.name}"])`);
|
||||
@ -373,10 +383,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
a(2, ``);
|
||||
a(2, `p.push(ctx);`);
|
||||
|
||||
a(
|
||||
2,
|
||||
`//@ts-ignore This will cause a typescript error when strict checking, since p is not a tuple`
|
||||
);
|
||||
a(2, `//@ts-ignore This will cause a typescript error when strict checking, since p is not a tuple`)
|
||||
a(
|
||||
2,
|
||||
`return this.${fnc.name}.call(this, ...p)` + //TODO: Refactor. This line is way to compicated for anyone to understand, including me
|
||||
@ -396,7 +403,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
|
||||
this.writeFormattedFile(
|
||||
this.getFileName(def.name + "_server"),
|
||||
getResult()
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
@ -410,13 +417,30 @@ export class TypescriptTarget extends CompileTarget {
|
||||
}
|
||||
|
||||
finalize(steps: Step[]) {
|
||||
const lc = LineAppender();
|
||||
const ls = LineAppender();
|
||||
let linesClient: string[] = [];
|
||||
let linesServer: string[] = [];
|
||||
|
||||
const ac = lc.a;
|
||||
const as = ls.a;
|
||||
const ac: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => linesClient.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
const { a, getResult } = LineAppender();
|
||||
const as: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => linesServer.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
let hasService = false;
|
||||
steps.forEach(([type, def]) => {
|
||||
@ -442,7 +466,10 @@ export class TypescriptTarget extends CompileTarget {
|
||||
"./" + def.name
|
||||
)
|
||||
);
|
||||
a(0, `export { ${def.name}, apply_${def.name} }`);
|
||||
a(
|
||||
0,
|
||||
`export { ${def.name}, apply_${def.name} }`
|
||||
);
|
||||
a(0, ``);
|
||||
break;
|
||||
|
||||
@ -476,9 +503,17 @@ export class TypescriptTarget extends CompileTarget {
|
||||
}
|
||||
});
|
||||
|
||||
this.writeFormattedFile(this.getFileName("index"), getResult());
|
||||
this.writeFormattedFile(this.getFileName("index_client"), lc.getResult());
|
||||
this.writeFormattedFile(this.getFileName("index_server"), ls.getResult());
|
||||
this.writeFormattedFile(this.getFileName("index"), lines.join("\n"));
|
||||
|
||||
this.writeFormattedFile(
|
||||
this.getFileName("index_client"),
|
||||
linesClient.join("\n")
|
||||
);
|
||||
|
||||
this.writeFormattedFile(
|
||||
this.getFileName("index_server"),
|
||||
linesServer.join("\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,110 +0,0 @@
|
||||
import { TypeDefinition, ServiceDefinition, EnumDefinition, Step } from "../ir";
|
||||
|
||||
import { CompileTarget } from "../compile";
|
||||
import { LineAppender, lineAppender } from "../utils";
|
||||
import chalk from "chalk";
|
||||
|
||||
const conversion = {
|
||||
boolean: "bool",
|
||||
int: "i64",
|
||||
float: "f64",
|
||||
string: "[]u8",
|
||||
void: "void",
|
||||
bytes: "[]u8",
|
||||
};
|
||||
|
||||
function toZigType(type: string): string {
|
||||
return (conversion as any)[type] || type;
|
||||
}
|
||||
|
||||
export class ZIGTarget extends CompileTarget<{ }> {
|
||||
name: string = "zig";
|
||||
|
||||
start(): void {
|
||||
if (this.options.allow_bytes == true) {
|
||||
throw new Error("Zig has no support for 'bytes' yet!");
|
||||
}
|
||||
}
|
||||
|
||||
getImport(name: string) {
|
||||
return `const ${name} = @import("./${name}.zig").${name};`;
|
||||
}
|
||||
|
||||
generateImports(a: lineAppender, def: TypeDefinition | ServiceDefinition) {
|
||||
a(0, `const std = @import("std");`);
|
||||
def.depends.forEach((dep) => {
|
||||
a(0, this.getImport(dep));
|
||||
});
|
||||
}
|
||||
|
||||
generateType(definition: TypeDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
this.generateImports(a, definition);
|
||||
|
||||
a(0, ``);
|
||||
|
||||
a(0, `pub const ${definition.name} = struct {`);
|
||||
for (const field of definition.fields) {
|
||||
if (field.array) {
|
||||
a(1, `${field.name}: std.ArrayList(${toZigType(field.type)}),`);
|
||||
} else if (field.map) {
|
||||
a(
|
||||
1,
|
||||
`${field.name}: std.AutoHashMap(${toZigType(
|
||||
field.map
|
||||
)}, ${toZigType(field.type)}),`
|
||||
);
|
||||
} else {
|
||||
a(1, `${field.name}: ${toZigType(field.type)},`);
|
||||
}
|
||||
}
|
||||
|
||||
a(0, `};`);
|
||||
|
||||
this.writeFile(`${definition.name}.zig`, getResult());
|
||||
}
|
||||
|
||||
generateEnum(definition: EnumDefinition): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
a(0, `pub const ${definition.name} = enum(i32) {`);
|
||||
for (const entry of definition.values) {
|
||||
a(1, `${entry.name} = ${entry.value},`);
|
||||
}
|
||||
a(0, `};`);
|
||||
|
||||
this.writeFile(`${definition.name}.zig`, getResult());
|
||||
}
|
||||
|
||||
generateService(definition: ServiceDefinition): void {
|
||||
console.log(
|
||||
chalk.yellow("[ZIG] WARNING:"),
|
||||
"ZIG support for services is not yet there. Service generation is skipped!"
|
||||
);
|
||||
}
|
||||
|
||||
finalize(steps: Step[]): void {
|
||||
const { a, getResult } = LineAppender();
|
||||
|
||||
steps.forEach(([type, def]) => {
|
||||
switch (type) {
|
||||
case "type":
|
||||
a(0, `pub ${this.getImport(def.name)}`);
|
||||
break;
|
||||
case "enum":
|
||||
a(0, `pub ${this.getImport(def.name)}`);
|
||||
break;
|
||||
default:
|
||||
console.warn(
|
||||
chalk.yellow("[ZIG] WARNING:"),
|
||||
"unimplemented step found:",
|
||||
type
|
||||
);
|
||||
// case "service":
|
||||
}
|
||||
});
|
||||
|
||||
this.writeFile(`mod.zig`, getResult());
|
||||
}
|
||||
}
|
20
src/utils.ts
20
src/utils.ts
@ -1,20 +0,0 @@
|
||||
export type lineAppender = (ind: number, line: string | string[]) => void;
|
||||
|
||||
export function LineAppender(indentSize = 3): {
|
||||
a: lineAppender;
|
||||
getResult: () => string;
|
||||
} {
|
||||
const lines: string[] = [];
|
||||
|
||||
return {
|
||||
a: (indentation: number, line: string | string[]) => {
|
||||
if (!Array.isArray(line)) {
|
||||
line = [line];
|
||||
}
|
||||
line.forEach((l) =>
|
||||
lines.push(" ".repeat(indentation * indentSize) + l.trim())
|
||||
);
|
||||
},
|
||||
getResult: () => lines.join("\n"),
|
||||
};
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
@ -1,52 +0,0 @@
|
||||
class JRPCError extends Error {
|
||||
String message;
|
||||
JRPCError(this.message);
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
int? int_fromJson(dynamic val) {
|
||||
if (val == null) {
|
||||
return null;
|
||||
} else if (val is int) {
|
||||
return val;
|
||||
} else if (val is double) {
|
||||
return val.toInt();
|
||||
} else {
|
||||
throw JRPCError("Not a number!");
|
||||
}
|
||||
}
|
||||
|
||||
double? double_fromJson(dynamic val) {
|
||||
if (val == null) {
|
||||
return null;
|
||||
} else if (val is int) {
|
||||
return val.toDouble();
|
||||
} else if (val is double) {
|
||||
return val;
|
||||
} else {
|
||||
throw JRPCError("Not a number!");
|
||||
}
|
||||
}
|
||||
|
||||
bool? bool_fromJson(dynamic val) {
|
||||
if (val == null) {
|
||||
return null;
|
||||
} else if (val is bool) {
|
||||
return val;
|
||||
} else {
|
||||
throw JRPCError("Not a bool!");
|
||||
}
|
||||
}
|
||||
|
||||
String? String_fromJson(dynamic val) {
|
||||
if (val == null) {
|
||||
return null;
|
||||
} else if (val is String) {
|
||||
return val;
|
||||
} else {
|
||||
return val.toString(); // TODO: Either this or error
|
||||
// throw JRPCError("Not a string!");
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
name: __NAME__
|
||||
description: JRPC
|
||||
version: 1.0.0
|
||||
|
||||
environment:
|
||||
sdk: ">=2.17.6 <3.0.0"
|
||||
|
||||
dependencies: {}
|
||||
dev_dependencies:
|
||||
lints: ^2.0.0
|
@ -1,86 +0,0 @@
|
||||
import "dart:async";
|
||||
import 'dart:math';
|
||||
|
||||
import "./base.dart";
|
||||
|
||||
abstract class Service {
|
||||
String name;
|
||||
ServiceProvider provider;
|
||||
|
||||
Service(this.provider, this.name) {
|
||||
provider._services[name] = this;
|
||||
}
|
||||
}
|
||||
|
||||
class ServiceProvider {
|
||||
final Map<String, Service> _services = {};
|
||||
final Map<String, Completer<dynamic>> _requests = {};
|
||||
|
||||
StreamController<Map<String, dynamic>> output = StreamController();
|
||||
late StreamSubscription s;
|
||||
|
||||
ServiceProvider(Stream<Map<String, dynamic>> input) {
|
||||
s = input.listen(onMessage);
|
||||
}
|
||||
|
||||
void onMessage(Map<String, dynamic> msg) {
|
||||
// print("Working on message");
|
||||
if (msg.containsKey("method")) {
|
||||
if (msg.containsKey("id")) {
|
||||
print("Message is request");
|
||||
// Request, not supported!
|
||||
return;
|
||||
} else {
|
||||
// print("Message is notification");
|
||||
// Notification
|
||||
// TODO: Implement
|
||||
}
|
||||
} else {
|
||||
// print("Message is response");
|
||||
// Response
|
||||
var req = _requests[msg["id"]];
|
||||
|
||||
if (req == null) {
|
||||
// print("Could not find related request. Ignoring");
|
||||
return; // Irrelevant response
|
||||
}
|
||||
if (msg.containsKey("error")) {
|
||||
//TODO:
|
||||
req.completeError(JRPCError(msg["error"]["message"]));
|
||||
} else {
|
||||
req.complete(msg["result"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> sendRequest(String method, dynamic params) {
|
||||
var id = nanoid(10);
|
||||
var req = {"jsonrpc": "2.0", "id": id, "method": method, "params": params};
|
||||
|
||||
var completer = Completer<dynamic>();
|
||||
|
||||
output.add(req);
|
||||
_requests[id] = completer;
|
||||
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
void sendNotification(String method, dynamic params) {
|
||||
var req = {"jsonrpc": "2.0", "method": method, "params": params};
|
||||
output.add(req);
|
||||
}
|
||||
}
|
||||
|
||||
// Copied from: https://github.com/pd4d10/nanoid-dart (MIT License)
|
||||
final _random = Random.secure();
|
||||
const urlAlphabet =
|
||||
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';
|
||||
|
||||
String nanoid([int size = 21]) {
|
||||
final len = urlAlphabet.length;
|
||||
String id = '';
|
||||
while (0 < size--) {
|
||||
id += urlAlphabet[_random.nextInt(len)];
|
||||
}
|
||||
return id;
|
||||
}
|
2
templates/Rust/.gitignore
vendored
2
templates/Rust/.gitignore
vendored
@ -1,2 +0,0 @@
|
||||
target
|
||||
Cargo.lock
|
@ -1,15 +0,0 @@
|
||||
[package]
|
||||
name = "__name__"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
int-enum = "0.4.0"
|
||||
serde = { version = "1.0.136", features = ["derive"] }
|
||||
serde_json = "1.0.79"
|
||||
threadpool = "1.8.1"
|
||||
nanoid = "0.4.0"
|
||||
|
||||
|
@ -1,286 +0,0 @@
|
||||
use nanoid::nanoid;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::boxed::Box;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::marker::PhantomData;
|
||||
use std::marker::Send;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use threadpool::ThreadPool;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
|
||||
|
||||
// TODO: Check what happens when error code is not included
|
||||
// #[repr(i64)]
|
||||
// #[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum, Deserialize, Serialize)]
|
||||
// pub enum ErrorCodes {
|
||||
// ParseError = -32700,
|
||||
// InvalidRequest = -32600,
|
||||
// MethodNotFound = -32601,
|
||||
// InvalidParams = -32602,
|
||||
// InternalError = -32603,
|
||||
// }
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct JRPCRequest {
|
||||
pub jsonrpc: String,
|
||||
pub id: Option<String>,
|
||||
pub method: String,
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct JRPCError {
|
||||
pub code: i64,
|
||||
pub message: String,
|
||||
pub data: Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct JRPCResult {
|
||||
pub jsonrpc: String,
|
||||
pub id: String,
|
||||
pub result: Value,
|
||||
pub error: Option<JRPCError>,
|
||||
}
|
||||
|
||||
// ******************************************************************************
|
||||
// * SERVER
|
||||
// ******************************************************************************
|
||||
|
||||
pub trait JRPCServiceHandler<C: Sync>: Send {
|
||||
fn get_name(&self) -> String;
|
||||
fn on_message(&self, msg: JRPCRequest, function: String, ctx: &C) -> Result<(bool, Value)>;
|
||||
}
|
||||
|
||||
type Shared<T> = Arc<Mutex<T>>;
|
||||
type SharedHM<K, V> = Shared<HashMap<K, V>>;
|
||||
type ServiceSharedHM<C> = SharedHM<String, Box<dyn JRPCServiceHandler<C>>>;
|
||||
|
||||
type SharedThreadPool = Shared<ThreadPool>;
|
||||
|
||||
pub struct JRPCServer<CTX: 'static + Sync + Send + Copy> {
|
||||
services: ServiceSharedHM<CTX>,
|
||||
pool: SharedThreadPool,
|
||||
}
|
||||
|
||||
impl<CTX: 'static + Sync + Send + Copy> JRPCServer<CTX> {
|
||||
pub fn new() -> Self {
|
||||
return Self {
|
||||
services: Arc::new(Mutex::new(HashMap::new())),
|
||||
pool: Arc::new(Mutex::new(ThreadPool::new(32))),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn add_service(&mut self, service: Box<dyn JRPCServiceHandler<CTX>>) {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
services.insert(service.get_name(), service);
|
||||
}
|
||||
|
||||
pub fn start_session(
|
||||
&mut self,
|
||||
read_ch: Receiver<String>,
|
||||
write_ch: Sender<String>,
|
||||
context: CTX,
|
||||
) {
|
||||
let services = self.services.clone();
|
||||
let p = self.pool.lock().unwrap();
|
||||
let pool = self.pool.clone();
|
||||
p.execute(move || {
|
||||
JRPCSession::start(read_ch, write_ch, context, services, pool);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub struct JRPCSession<CTX: 'static + Sync + Send + Copy> {
|
||||
_ctx: PhantomData<CTX>,
|
||||
}
|
||||
|
||||
unsafe impl<CTX: 'static + Sync + Send + Copy> Sync for JRPCSession<CTX> {}
|
||||
|
||||
impl<CTX: 'static + Sync + Send + Copy> JRPCSession<CTX> {
|
||||
fn start(
|
||||
read_ch: Receiver<String>,
|
||||
write_ch: Sender<String>,
|
||||
context: CTX,
|
||||
services: ServiceSharedHM<CTX>,
|
||||
pool: SharedThreadPool,
|
||||
) {
|
||||
loop {
|
||||
let pkg = read_ch.recv();
|
||||
let data = match pkg {
|
||||
Err(_) => return,
|
||||
Ok(res) => res,
|
||||
};
|
||||
if data.len() == 0 {
|
||||
//TODO: This can be done better
|
||||
return;
|
||||
}
|
||||
let ctx = context.clone();
|
||||
let svs = services.clone();
|
||||
let wc = write_ch.clone();
|
||||
pool.lock().unwrap().execute(move || {
|
||||
JRPCSession::handle_packet(data, wc, ctx, svs);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_packet(
|
||||
data: String,
|
||||
write_ch: Sender<String>,
|
||||
context: CTX,
|
||||
services: ServiceSharedHM<CTX>,
|
||||
) {
|
||||
let req: Result<JRPCRequest> =
|
||||
serde_json::from_str(data.as_str()).map_err(|err| Box::from(err));
|
||||
|
||||
let req = match req {
|
||||
Err(_) => {
|
||||
return;
|
||||
}
|
||||
Ok(parsed) => parsed,
|
||||
};
|
||||
|
||||
let req_id = req.id.clone();
|
||||
|
||||
let mut parts: Vec<String> = req.method.splitn(2, '.').map(|e| e.to_owned()).collect();
|
||||
if parts.len() != 2 {
|
||||
return Self::send_err_res(req_id, write_ch, Box::from("Error".to_owned()));
|
||||
}
|
||||
|
||||
let service = parts.remove(0);
|
||||
let function = parts.remove(0);
|
||||
|
||||
let svs = services.lock().unwrap();
|
||||
let srv = svs.get(&service);
|
||||
|
||||
if let Some(srv) = srv {
|
||||
match srv.on_message(req, function, &context) {
|
||||
Ok((is_send, value)) => {
|
||||
if is_send {
|
||||
if let Some(id) = req_id {
|
||||
let r = JRPCResult {
|
||||
jsonrpc: "2.0".to_owned(),
|
||||
id,
|
||||
result: value,
|
||||
error: None,
|
||||
};
|
||||
let s = serde_json::to_string(&r);
|
||||
if s.is_ok() {
|
||||
write_ch
|
||||
.send(s.unwrap())
|
||||
.expect("Sending data into channel failed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => return Self::send_err_res(req_id, write_ch, err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_err_res(id: Option<String>, write_ch: Sender<String>, err: Box<dyn Error>) {
|
||||
if let Some(id) = id {
|
||||
let error = JRPCError {
|
||||
code: 0, //TODO: Make this better?
|
||||
message: err.to_string(),
|
||||
data: Value::Null,
|
||||
};
|
||||
|
||||
let r = JRPCResult {
|
||||
jsonrpc: "2.0".to_owned(),
|
||||
id: id.clone(),
|
||||
result: Value::Null,
|
||||
error: Option::from(error),
|
||||
};
|
||||
|
||||
let s = serde_json::to_string(&r);
|
||||
|
||||
if s.is_ok() {
|
||||
write_ch
|
||||
.send(s.unwrap())
|
||||
.expect("Sending data into channel failed!");
|
||||
}
|
||||
}
|
||||
|
||||
return ();
|
||||
}
|
||||
}
|
||||
|
||||
// ******************************************************************************
|
||||
// * CLIENT
|
||||
// ******************************************************************************
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct JRPCClient {
|
||||
write_ch: Sender<String>,
|
||||
requests: SharedHM<String, Sender<Result<Value>>>,
|
||||
}
|
||||
|
||||
unsafe impl Send for JRPCClient {} //TODO: Is this a problem
|
||||
|
||||
impl JRPCClient {
|
||||
pub fn new(write_ch: Sender<String>, read_ch: Receiver<String>) -> Self {
|
||||
let n = Self {
|
||||
write_ch,
|
||||
requests: Arc::new(Mutex::new(HashMap::new())),
|
||||
};
|
||||
|
||||
n.start(read_ch);
|
||||
return n;
|
||||
}
|
||||
|
||||
pub fn start(&self, read_ch: Receiver<String>) {
|
||||
let s = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
s.start_reader(read_ch);
|
||||
});
|
||||
}
|
||||
|
||||
fn start_reader(&self, read_ch: Receiver<String>) {
|
||||
loop {
|
||||
let data = read_ch.recv().expect("Error receiving packet!");
|
||||
let response: JRPCResult =
|
||||
serde_json::from_str(data.as_str()).expect("Error decoding response!");
|
||||
let id = response.id;
|
||||
|
||||
let reqs = self.requests.lock().expect("Error locking requests map!");
|
||||
let req = reqs.get(&id);
|
||||
if let Some(req) = req {
|
||||
let res = if let Some(err) = response.error {
|
||||
Err(Box::from(err.message))
|
||||
} else {
|
||||
Ok(response.result)
|
||||
};
|
||||
|
||||
req.send(res).expect("Error sending reponse!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_request(&self, mut req: JRPCRequest) -> Result<Value> {
|
||||
let mut reqs = self.requests.lock().expect("Error locking requests map!");
|
||||
let id = nanoid!();
|
||||
req.id = Some(id.clone());
|
||||
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
|
||||
reqs.insert(id, tx);
|
||||
self
|
||||
.write_ch
|
||||
.send(serde_json::to_string(&req).expect("Error converting Request to JSON!"))
|
||||
.expect("Error Sending to Channel!");
|
||||
return rx.recv().expect("Error getting response!");
|
||||
}
|
||||
|
||||
pub fn send_notification(&self, mut req: JRPCRequest) {
|
||||
req.id = None;
|
||||
|
||||
self
|
||||
.write_ch
|
||||
.send(serde_json::to_string(&req).expect("Error converting Request to JSON!"))
|
||||
.expect("Error Sending to Channel!");
|
||||
}
|
||||
}
|
@ -4,24 +4,13 @@ export class VerificationError extends Error {
|
||||
public readonly field?: string,
|
||||
public readonly value?: any
|
||||
) {
|
||||
super(
|
||||
"Parameter verification failed! " +
|
||||
(type ? "Expected " + type + "! " : "") +
|
||||
(field ? "At: " + field + "! " : "")
|
||||
);
|
||||
super("Parameter verification failed! " +(type ? "Expected " + type + "! " :"") + (field ? "At: " + field + "! " : ""));
|
||||
}
|
||||
}
|
||||
|
||||
export function apply_int(data: any) {
|
||||
data = Math.floor(Number(data));
|
||||
if (Number.isNaN(data)) throw new VerificationError("int", undefined, data);
|
||||
return data;
|
||||
}
|
||||
|
||||
export function apply_float(data: any) {
|
||||
export function apply_number(data: any) {
|
||||
data = Number(data);
|
||||
if (Number.isNaN(data))
|
||||
throw new VerificationError("float", undefined, data);
|
||||
if(Number.isNaN(data)) throw new VerificationError("number", undefined, data);
|
||||
return data;
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user