Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

78 changes: 67 additions & 11 deletions yerpc-derive/src/ts.rs → yerpc-derive/src/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use crate::{util::extract_result_ty, Inputs, RpcInfo};
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::quote;
pub(crate) fn generate_typescript_generator(info: &RpcInfo) -> TokenStream {
pub(crate) fn generate_bindings_impl(info: &RpcInfo) -> TokenStream {
let mut gen_types = vec![];
let mut gen_methods = vec![];
let mut gen_methods_ts = vec![];
let mut gen_methods_qt = vec![];
for method in &info.methods {
let (is_positional, gen_args) = match &method.input {
Inputs::Positional(ref inputs) => {
Expand Down Expand Up @@ -41,23 +42,26 @@ pub(crate) fn generate_typescript_generator(info: &RpcInfo) -> TokenStream {
quote!(Some(&<#ty as TypeDef>::INFO))
}
};
let ts_name = method.name.to_case(Case::Camel);
let rpc_name_camel = method.name.to_case(Case::Camel);
let rpc_name = &method.name;
let is_notification = method.is_notification;
let docs = if let Some(docs) = &method.docs {
quote!(Some(#docs))
} else {
quote!(None)
};
gen_methods.push(quote!(
gen_methods_ts.push(quote!(
let args = vec![#(#gen_args),*];
let method = Method::new(#ts_name, #rpc_name, args, #gen_output, #is_notification, #is_positional, #docs);
out.push_str(&method.to_string(root_namespace));
let method = Method::new(#rpc_name_camel, #rpc_name, args, #gen_output, #is_notification, #is_positional, #docs);
out.push_str(&method.to_string_ts(root_namespace));
));
gen_methods_qt.push(quote!(
let args = vec![#(#gen_args),*];
let method = Method::new(#rpc_name_camel, #rpc_name, args, #gen_output, #is_notification, #is_positional, #docs);
out.push_str(&method.to_string_qt());
));
}

let ts_base = include_str!("client.ts");

let mut all_types: Vec<String> = gen_types
.clone()
.into_iter()
Expand All @@ -67,11 +71,22 @@ pub(crate) fn generate_typescript_generator(info: &RpcInfo) -> TokenStream {
all_types.dedup();
let all_types: Vec<TokenStream> = all_types.into_iter().map(|s| s.parse().unwrap()).collect();

let ts = ts_impl(&all_types, &gen_methods_ts);
let qt = qt_impl(&all_types, &gen_methods_qt);
quote! {
#ts
#qt
}
}

fn ts_impl(all_types: &[TokenStream], gen_methods: &[TokenStream]) -> TokenStream {
let ts_base = include_str!("client.ts");

quote! {
/// Write typescript bindings for the JSON-RPC API.
pub fn write_ts_bindings(outdir: &::std::path::Path) {
use ::yerpc::typescript::type_def::{TypeDef, type_expr::TypeInfo, DefinitionFileOptions};
use ::yerpc::typescript::{typedef_to_expr_string, export_types_to_file, Method};
use ::yerpc::{method::Method, typescript::{typedef_to_expr_string, export_types_to_file}};
use ::std::{fs, path::Path};
use ::std::io::Write;

Expand All @@ -84,7 +99,7 @@ pub(crate) fn generate_typescript_generator(info: &RpcInfo) -> TokenStream {
// Write typescript types to file.
export_types_to_file::<__AllTyps>(&outdir.join("types.ts"), None).expect("Failed to write TS out");
// remove __AllTyps ts type from output,
// it's only used as a woraround to export all types and is not needed anymore now
// it's only used as a workaround to export all types and is not needed anymore now
let new_content = {
let string =
::std::fs::read_to_string(&outdir.join("types.ts")).expect("Failed to find TS out");
Expand All @@ -100,7 +115,7 @@ pub(crate) fn generate_typescript_generator(info: &RpcInfo) -> TokenStream {
.expect("removing __AllTyps from TS failed");
export_types_to_file::<::yerpc::Message>(&outdir.join("jsonrpc.ts"), None).expect("Failed to write TS out");

// // Generate a raw client.
// Generate a raw client.
let root_namespace = Some("T");
let mut out = String::new();
#(#gen_methods)*
Expand All @@ -109,3 +124,44 @@ pub(crate) fn generate_typescript_generator(info: &RpcInfo) -> TokenStream {
}
}
}

fn qt_impl(all_types: &[TokenStream], gen_methods: &[TokenStream]) -> TokenStream {
let qt_base = include_str!("client.hpp");
quote! {
/// Generate qt bindings for the JSON-RPC API.
pub fn write_qt_bindings(outdir: &::std::path::Path, root_namespace: &str) {
use ::yerpc::typescript::type_def::{TypeDef, type_expr::TypeInfo, DefinitionFileOptions};
use ::yerpc::{method::Method, qt::export_types_to_file};
use ::std::{fs, path::Path};
use ::std::io::Write;

// Create helper type with all exported types.
// #(#gen_definitions)*
#[derive(TypeDef)]
struct __AllTyps(#(#all_types),*);
// Write qt types to file.
export_types_to_file::<__AllTyps>(&outdir.join("types.hpp"), root_namespace).expect("Failed to write Qt out");
// remove __AllTyps type from output,
// it's only used as a workaround to export all types and is not needed anymore now
let new_content = {
let string =
::std::fs::read_to_string(&outdir.join("types.hpp")).expect("Failed to find Qt out");
if let Some(index) = string.find("using __AllTyps = ") {
string[..index].to_string() + "\n}\n"
} else {
panic!("did not find __AllTyps in Qt out");
}
};
::std::fs::File::create(&outdir.join("types.hpp"))
.expect("failed to open Qt out")
.write_all(new_content.as_bytes())
.expect("removing __AllTyps from Qt failed");

// Generate a raw client.
let mut out = String::new();
#(#gen_methods)*
let qt_header = #qt_base.replace("#root_namespace", root_namespace).replace("#methods", &out);
fs::write(&outdir.join("client.hpp"), &qt_header).expect("Failed to write Qt bindings");
}
}
}
168 changes: 168 additions & 0 deletions yerpc-derive/src/client.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
#pragma once

#include "types.hpp"

#include <QFuture>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QString>

#include <cstdint>
#include <utility>

namespace #root_namespace {

struct ResultError {
/** Error code of the result. Equals `0` if there is no error. */
int32_t error_code = 0;

/** Error message of the result. Equals an empty string if there is no error.
*/
QString error_message{};

/** Returns `true` if the result represents an error. */
bool isError() const { return error_code != 0; }

/**
* Explicitly discards the result. Used to silence `[[nodiscard]]` warnings
*/
void ignore() const {}
};

template <typename T> struct [[nodiscard]] Result : ResultError {
/* Constructs a successful result containing the given value */
static Result<T> ok(T value) { return {{0, {}}, std::move(value)}; }

/* Constructs an error result with the given error code and message */
static Result<T> error(int32_t error_code, QString error_message) {
return {{error_code, std::move(error_message)}, {}};
}

/** Value of the result. Is a default constructed value if the result
* represents an error. */
T value{};

/**
* If the result represents an error, logs a warning with the error details
* and the caller's source location. Returns a copy of this result for
* chaining.
*/
Result<T> logError(const char *file = __builtin_FILE(),
int line = __builtin_LINE()) const {
if (error_code) {
qWarning().noquote()
<< QStringLiteral("Result::logError() from %1:%2 | Error %3: %4")
.arg(QLatin1String(file))
.arg(line)
.arg(error_code)
.arg(error_message);
}
return *this;
}

/** Return the `value` converted to json */
QJsonValue valueToJson() const { return toJson(value); }
};

template <> struct [[nodiscard]] Result<void> : ResultError {
/* Constructs a successful result */
static Result<void> ok() { return {{0, {}}}; }

/* Constructs an error result with the given error code and message */
static Result<void> error(int32_t error_code, QString error_message) {
return {{error_code, std::move(error_message)}};
}

/**
* If the result represents an error, logs a warning with the error details
* and the caller's source location. Returns a copy of this result for
* chaining.
*/
Result<void> logError(const char *file = __builtin_FILE(),
int line = __builtin_LINE()) const {
if (error_code) {
qWarning().noquote()
<< QStringLiteral("Result::logError() from %1:%2 | Error %3: %4")
.arg(QLatin1String(file))
.arg(line)
.arg(error_code)
.arg(error_message);
}
return *this;
}
};

static Result<QJsonValue> parseResult(const QJsonObject &val) {
if (val.contains("error")) {
QJsonObject err = val["error"].toObject();
QJsonValue error_message = err["message"];
int error_code = err["code"].toInt();
if (!error_message.isString() || error_code == 0)
return Result<QJsonValue>::error(
-32700, "Invalid error in response: " +
QJsonDocument(val).toJson(QJsonDocument::Compact));
return Result<QJsonValue>::error(error_code, error_message.toString());
}
if (!val.contains("result"))
return Result<QJsonValue>::error(
-32700, "Neither error nor result in response: " +
QJsonDocument(val).toJson(QJsonDocument::Compact));
return Result<QJsonValue>::ok(val["result"]);
}

class Transport {
public:
using CompletionHandler = std::function<void(const Result<QJsonValue>)>;
virtual void send(const QString method, const QJsonValue request,
Comment thread
link2xt marked this conversation as resolved.
CompletionHandler onCompleted) = 0;
virtual ~Transport() = default;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note for myself (and other reviewers) on why virtual destructors should basically always be defined on virtual classes: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#discussion-make-base-class-destructors-public-and-virtual-or-protected-and-non-virtual
The link is a discussion on how you can not do this if you keep virtual class private and make sure you never destroy it via reference to base class.

};

class RawClient {
template <typename T>
QFuture<Result<T>> request(const QString method, const QJsonArray params) {
QFutureInterface<Result<T>> interface;
interface.reportStarted();
transport_->send(method, params,
[method, interface](const Result<QJsonValue> val) mutable {
interface.reportResult(
mapToConcreteType<T>(val, method));
interface.reportFinished();
});
return interface.future();
}

template <typename T>
static Result<T> mapToConcreteType(const Result<QJsonValue> val,
const QString method) {
if constexpr (std::is_void_v<T>) {
if (val.error_code)
return Result<void>::error(val.error_code,
method + ": " + val.error_message);
return Result<void>::ok();
} else {
if (val.error_code)
return Result<T>::error(val.error_code,
method + ": " + val.error_message);
T out;
if (!tryFromJson(val.value, out)) {
return Result<T>::error(-32700,
method + ": Could not parse result " +
QJsonDocument(QJsonArray{val.value})
.toJson(QJsonDocument::Compact));
}
return Result<T>::ok(out);
}
}

public:
RawClient(std::unique_ptr<Transport> t) : transport_{std::move(t)} {}

std::unique_ptr<Transport> transport_;
Comment thread
link2xt marked this conversation as resolved.

#methods
};

}
Loading
Loading