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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
authors = ["ImJeremyHe<yiliang.he@qq.com>"]
edition = "2018"
name = "gents"
version = "1.1.0"
version = "1.2.0"
license = "MIT"
description = "generate Typescript interfaces from Rust code"
repository = "https://github.com/ImJeremyHe/gents"
Expand Down
2 changes: 1 addition & 1 deletion derives/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "gents_derives"
version = "1.1.0"
version = "1.2.0"
description = "provides some macros for gents"
authors = ["ImJeremyHe<yiliang.he@qq.com>"]
license = "MIT"
Expand Down
45 changes: 31 additions & 14 deletions derives/src/ts_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ pub fn ts_interface(attr: TokenStream, item: TokenStream) -> TokenStream {
struct TsInterfaceArgs {
file_name: String,
ident: Option<String>,
async_func: bool,
}

impl Parse for TsInterfaceArgs {
fn parse(input: ParseStream) -> Result<Self> {
let mut file_name: Option<String> = None;
let mut ident_val: Option<String> = None;
let mut async_func: bool = false;

while !input.is_empty() {
let ident: Ident = input.parse()?;
Expand All @@ -37,10 +39,12 @@ impl Parse for TsInterfaceArgs {
file_name = Some(lit.value());
} else if ident == "ident" {
ident_val = Some(lit.value());
} else if ident == "async" {
async_func = lit.value() == "true";
} else {
return Err(Error::new_spanned(
ident,
"expected `file_name = \"...\"` or `ident = \"...\"`",
"expected `file_name = \"...\"` or `ident = \"...\"` or `async = \"true|false\"`",
));
}

Expand All @@ -56,6 +60,7 @@ impl Parse for TsInterfaceArgs {
Ok(Self {
file_name,
ident: ident_val,
async_func,
})
}
}
Expand All @@ -78,16 +83,10 @@ fn expand_ts_interface(
// prefer user-specified ident if provided, otherwise fall back to Rust type name
let type_name = args.ident.unwrap_or_else(|| self_ty_ident.to_string());
let file_name = args.file_name;
let async_func = args.async_func;

// Collect impl-level doc comments
let mut impl_comments = Vec::new();
for attr in &impl_block.attrs {
if attr.path().is_ident("doc") {
if let Ok(lit) = attr.parse_args::<LitStr>() {
impl_comments.push(lit.value());
}
}
}
let impl_comments = Vec::<String>::new();
// TODO: collect impl-level doc comments

// Collect public methods
let mut method_tokens = Vec::new();
Expand All @@ -113,6 +112,7 @@ fn expand_ts_interface(
file_name: #file_name.to_string(),
methods: vec![ #(#method_tokens),* ],
comment: vec![ #( #impl_comments.to_string() ),* ],
async_func: #async_func,
}
}
}
Expand All @@ -136,16 +136,33 @@ fn extract_self_type_ident(ty: &Type) -> Result<&Ident> {
}
}

fn extract_doc(attr: &syn::Attribute) -> Option<String> {
if !attr.path().is_ident("doc") {
return None;
}

match &attr.meta {
syn::Meta::NameValue(nv) => {
if let syn::Expr::Lit(expr_lit) = &nv.value {
if let syn::Lit::Str(lit_str) = &expr_lit.lit {
return Some(lit_str.value());
}
}
None
}
_ => None,
}
}

fn expand_method(func: &ImplItemFn) -> Result<proc_macro2::TokenStream> {
let name = convert_camel_from_snake(func.sig.ident.to_string());

// Collect method-level doc comments
let mut comments = Vec::new();
for attr in &func.attrs {
if attr.path().is_ident("doc") {
if let Ok(lit) = attr.parse_args::<LitStr>() {
comments.push(lit.value());
}
if let Some(doc) = extract_doc(attr) {
let d = doc.trim_start().to_string();
comments.push(d);
}
}

Expand Down
9 changes: 8 additions & 1 deletion src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub struct ApiDescriptor {
pub file_name: String,
pub methods: Vec<MethodDescriptor>,
pub comment: Vec<String>,
pub async_func: bool,
}

pub struct MethodDescriptor {
Expand Down Expand Up @@ -203,6 +204,7 @@ impl DescriptorManager {
let (ts_name, file_name) = get_import_deps(&descriptors, idx);
fmt.add_import(&ts_name, &file_name);
});
let async_func = api.async_func;

// For API files we currently do not emit comments into the generated TS,
// so that the output matches the expected test fixtures exactly.
Expand All @@ -223,7 +225,12 @@ impl DescriptorManager {
let desc = descriptors.get(*idx).unwrap();
desc.ts_name().to_string()
});
fmt.add_method(&m.name, params, ret);
fmt.add_comment(&m.comment);
if async_func {
fmt.add_async_method(&m.name, params, ret);
} else {
fmt.add_method(&m.name, params, ret);
}
});
fmt.end_interface();
result.push((api.file_name.to_string(), fmt.end_file()));
Expand Down
18 changes: 18 additions & 0 deletions src/ts_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@ impl TsFormatter {
self.write_line(&format!("{}({}): {};", name, param_str, ret_str));
}

pub fn add_async_method(
&mut self,
name: &str,
params: Vec<(String, String)>,
ret: Option<String>,
) {
let param_str = params
.iter()
.map(|(n, t)| format!("{}: {}", n, t))
.collect::<Vec<_>>()
.join(", ");
let ret_str = ret.map_or("void".to_string(), |r| r);
self.write_line(&format!(
"async {}({}): Promise<{}>;",
name, param_str, ret_str
));
}

pub fn end_interface(&mut self) {
if self.indent > 0 {
self.indent -= 1;
Expand Down
2 changes: 1 addition & 1 deletion tests/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ mod test_api {

assert_eq!(
files.get("v1_api.ts").unwrap(),
&"export interface V1Api {\n f1(): number;\n f2(): string;\n setF1(f1: number): void;\n setF2(f2: string): void;\n}\n"
&"export interface V1Api {\n f1(): number;\n f2(): string;\n // set f1\n setF1(f1: number): void;\n setF2(f2: string): void;\n}\n"
);
}
}