forked from wasm-bindgen/ts-gen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
406 lines (375 loc) · 13.4 KB
/
mod.rs
File metadata and controls
406 lines (375 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Code generation: IR → Rust source code.
//!
//! The main entry point is [`generate`], which takes a parsed IR [`Module`]
//! and produces formatted Rust source code as a string.
pub mod classes;
pub mod enums;
pub mod functions;
pub mod signatures;
pub mod subtyping;
pub mod typemap;
use proc_macro2::TokenStream;
use quote::quote;
use crate::ir::{InterfaceClassification, Module, TypeDeclaration, TypeKind};
use crate::parse::scope::ScopeId;
use typemap::CodegenContext;
/// Convert an optional doc string into `/// ...` doc-comment attributes.
///
/// Returns an empty `TokenStream` if `doc` is `None`.
pub(crate) fn doc_tokens(doc: &Option<String>) -> TokenStream {
match doc {
Some(text) => {
let lines: Vec<TokenStream> = text
.lines()
.map(|line| {
// Non-empty lines get a leading space so the rendered
// doc reads `/// foo` rather than `///foo`. Empty
// lines stay bare so blank-line separators don't
// emit as a stray `#[doc = " "]`.
let line = if line.is_empty() {
String::new()
} else {
format!(" {line}")
};
quote! { #[doc = #line] }
})
.collect();
quote! { #(#lines)* }
}
None => quote! {},
}
}
/// Options for controlling code generation output.
///
/// Currently empty — kept as the carrier for future per-invocation flags so
/// the `generate` / `generate_with_options` split doesn't have to be
/// reintroduced when one is added.
#[derive(Debug, Clone, Default)]
pub struct GenerateOptions {}
/// Generate Rust source code from a parsed IR module + global context.
///
/// Returns the formatted source as a string, ready to be written to a file.
pub fn generate(module: &Module, gctx: &crate::context::GlobalContext) -> anyhow::Result<String> {
generate_with_options(module, gctx, &GenerateOptions::default())
}
/// Generate Rust source code with explicit options.
pub fn generate_with_options(
module: &Module,
gctx: &crate::context::GlobalContext,
options: &GenerateOptions,
) -> anyhow::Result<String> {
let tokens = generate_tokens(module, gctx, options);
// Validate that the tokens are valid Rust syntax.
syn::parse2::<syn::File>(tokens.clone()).map_err(|e| {
anyhow::anyhow!("generated tokens are not valid syn:\n{e}\n\nTokens:\n{tokens}")
})?;
let formatted = rustfmt(&tokens.to_string())?;
// Prepend a header comment. Line comments don't survive `quote!` token
// generation, so they have to be emitted as plain text after formatting.
Ok(format!(
"// Generated by ts-gen. Do not edit.\n\n{formatted}"
))
}
/// Format Rust source via `rustfmt`.
///
/// Falls back to `prettyplease` if `rustfmt` is not available.
fn rustfmt(code: &str) -> anyhow::Result<String> {
use std::io::Write;
use std::process::{Command, Stdio};
let mut child = match Command::new("rustfmt")
.arg("--edition=2021")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(_) => {
let file = syn::parse_str::<syn::File>(code)?;
return Ok(prettyplease::unparse(&file));
}
};
child.stdin.take().unwrap().write_all(code.as_bytes())?;
let output = child.wait_with_output()?;
if output.status.success() {
Ok(String::from_utf8(output.stdout)?)
} else {
let file = syn::parse_str::<syn::File>(code)?;
Ok(prettyplease::unparse(&file))
}
}
/// Generate the token stream for a full module.
///
/// `Promise<T>` awaitability used to require an emitted `PromiseExt` trait
/// (orphan rule prevented an `IntoFuture` impl from generated code), but
/// upstream `js_sys` now implements `IntoFuture` for `Promise<T>` directly,
/// so callers get `.await` for free without anything generated here.
fn generate_tokens(
module: &Module,
gctx: &crate::context::GlobalContext,
_options: &GenerateOptions,
) -> TokenStream {
let cgctx = CodegenContext::from_module(module, gctx);
let preamble = quote! {
#[allow(unused_imports)]
use wasm_bindgen::prelude::*;
#[allow(unused_imports)]
use js_sys::*;
};
// Group declarations by module context.
// Global declarations go at the top level.
// Module declarations go inside `mod <name> { ... }` blocks.
let mut global_items = Vec::new();
let mut module_items: std::collections::BTreeMap<std::rc::Rc<str>, Vec<TokenStream>> =
std::collections::BTreeMap::new();
for &type_id in &module.types {
let decl = gctx.get_type(type_id);
if let Some(tokens) = generate_declaration(decl, &cgctx) {
match &decl.module_context {
crate::ir::ModuleContext::Global => {
global_items.push(tokens);
}
crate::ir::ModuleContext::Module(m) => {
module_items.entry(m.clone()).or_default().push(tokens);
}
}
}
}
// Wrap each module's items in a `mod` block
let mod_blocks: Vec<TokenStream> = module_items
.into_iter()
.map(|(mod_specifier, items)| {
let mod_name = typemap::make_ident(&crate::util::naming::module_specifier_to_ident(
&mod_specifier,
));
quote! {
pub mod #mod_name {
use wasm_bindgen::prelude::*;
use js_sys::*;
use super::*;
#(#items)*
}
}
})
.collect();
// External type use aliases (collected during codegen above)
let external_uses = cgctx.external_use_tokens();
// Emit codegen diagnostics
cgctx.take_diagnostics().emit();
quote! {
#preamble
#external_uses
#(#global_items)*
#(#mod_blocks)*
}
}
/// Generate tokens for a single declaration.
fn generate_declaration(decl: &TypeDeclaration, cgctx: &CodegenContext) -> Option<TokenStream> {
match &decl.kind {
TypeKind::Class(c) => Some(classes::generate_class(
c,
&decl.module_context,
Some(cgctx),
decl.scope_id,
)),
TypeKind::Interface(i) => match i.classification {
InterfaceClassification::ClassLike | InterfaceClassification::Unclassified => {
Some(classes::generate_class_like_interface(
i,
&decl.module_context,
Some(cgctx),
None,
decl.scope_id,
))
}
InterfaceClassification::Dictionary => Some(classes::generate_dictionary_extern(
i,
&decl.module_context,
Some(cgctx),
None,
decl.scope_id,
)),
},
TypeKind::StringEnum(e) => Some(enums::generate_string_enum(e)),
TypeKind::NumericEnum(e) => Some(enums::generate_numeric_enum(e)),
TypeKind::Function(f) => Some(functions::generate_function(
f,
&decl.module_context,
Some(cgctx),
&decl.doc,
decl.scope_id,
)),
TypeKind::Variable(v) => Some(functions::generate_variable(
v,
&decl.module_context,
Some(cgctx),
&decl.doc,
None,
decl.scope_id,
)),
TypeKind::TypeAlias(alias) => Some(generate_type_alias(
alias,
cgctx,
decl.scope_id,
&decl.module_context,
)),
TypeKind::Namespace(ns) => Some(generate_namespace(ns, &decl.module_context, cgctx)),
}
}
/// Generate output for a TypeAlias declaration.
///
/// - Local alias: `pub type WritableStream = Writable;`
/// - External re-export: `pub use external_crate::Foo;`
fn generate_type_alias(
alias: &crate::ir::TypeAliasDecl,
cgctx: &CodegenContext,
scope: ScopeId,
from_module: &crate::ir::ModuleContext,
) -> TokenStream {
if let Some(ref module) = alias.from_module {
// External re-export: resolve through external map.
let type_name = match &alias.target {
crate::ir::TypeRef::Named(n) => n.as_str(),
_ => &alias.name,
};
if let Some(rust_path) = cgctx.resolve_external(type_name, module) {
let path: syn::Path = syn::parse_str(&rust_path.path).unwrap_or_else(|_| {
syn::Path::from(syn::Ident::new("JsValue", proc_macro2::Span::call_site()))
});
let name = typemap::make_ident(&alias.name);
if alias.name == type_name {
return quote! { pub use #path; };
} else {
return quote! { pub use #path as #name; };
}
}
cgctx.warn(format!(
"No external mapping for `{}` from \"{module}\" — emitting JsValue alias",
type_name,
));
let name = typemap::make_ident(&alias.name);
return quote! {
#[allow(dead_code)]
pub type #name = JsValue;
};
}
// Local alias — only emit if the target resolves to a known type.
if let crate::ir::TypeRef::Named(ref target_name) = alias.target {
if !cgctx.local_types.contains_key(target_name)
&& !crate::codegen::typemap::JS_SYS_RESERVED.contains(&target_name.as_str())
{
cgctx.warn(format!(
"Type alias `{}` targets unknown type `{target_name}`, skipping",
alias.name
));
return quote! {};
}
}
let target = typemap::to_syn_type(
&alias.target,
typemap::TypePosition::ARGUMENT.to_inner(),
Some(cgctx),
scope,
from_module,
);
let name = typemap::make_ident(&alias.name);
// Identity — skip.
if target.to_string() == alias.name {
return quote! {};
}
// Type-parameter declaration so aliases that mention generics survive
// codegen: `type EmailExportedHandler<Env, Props> = …;` rather than the
// bare `EmailExportedHandler =` that would leave `Props` undeclared.
let generics = if alias.type_params.is_empty() {
quote! {}
} else {
let idents = alias
.type_params
.iter()
.map(|tp| typemap::make_ident(&tp.name))
.collect::<Vec<_>>();
// Type aliases use plain `<T, U>` without trait bounds; aliases
// are erased during monomorphisation by their use sites.
quote! { <#(#idents),*> }
};
quote! {
#[allow(dead_code)]
pub type #name #generics = #target;
}
}
/// Generate a Rust `mod` block for a namespace, with all nested declarations.
fn generate_namespace(
ns: &crate::ir::NamespaceDecl,
_parent_ctx: &crate::ir::ModuleContext,
cgctx: &CodegenContext,
) -> TokenStream {
let mod_name = typemap::make_ident(&crate::util::naming::to_snake_case(&ns.name));
let js_name = &ns.name;
let items: Vec<TokenStream> = ns
.declarations
.iter()
.filter_map(|decl| generate_ns_declaration(decl, js_name, cgctx))
.collect();
quote! {
pub mod #mod_name {
use wasm_bindgen::prelude::*;
#(#items)*
}
}
}
/// Generate tokens for a declaration inside a namespace.
/// Adds `js_namespace` attribute to extern blocks so wasm_bindgen emits
/// the correct JS access (e.g., `WebAssembly.Module`).
fn generate_ns_declaration(
decl: &TypeDeclaration,
ns_js_name: &str,
cgctx: &CodegenContext,
) -> Option<TokenStream> {
match &decl.kind {
TypeKind::Class(c) => Some(classes::generate_class_with_js_namespace(
c,
&decl.module_context,
ns_js_name,
Some(cgctx),
decl.scope_id,
)),
TypeKind::Interface(i) => match i.classification {
InterfaceClassification::ClassLike | InterfaceClassification::Unclassified => {
Some(classes::generate_class_like_interface(
i,
&decl.module_context,
Some(cgctx),
Some(ns_js_name),
decl.scope_id,
))
}
InterfaceClassification::Dictionary => Some(classes::generate_dictionary_extern(
i,
&decl.module_context,
Some(cgctx),
Some(ns_js_name),
decl.scope_id,
)),
},
TypeKind::Function(f) => Some(functions::generate_function_with_js_namespace(
f,
&decl.module_context,
ns_js_name,
Some(cgctx),
&decl.doc,
decl.scope_id,
)),
TypeKind::StringEnum(e) => Some(enums::generate_string_enum(e)),
TypeKind::NumericEnum(e) => Some(enums::generate_numeric_enum(e)),
TypeKind::Variable(v) => Some(functions::generate_variable(
v,
&decl.module_context,
Some(cgctx),
&decl.doc,
Some(ns_js_name),
decl.scope_id,
)),
TypeKind::TypeAlias(_) => None,
TypeKind::Namespace(ns) => Some(generate_namespace(ns, &decl.module_context, cgctx)),
}
}