-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
lib.rs
52 lines (48 loc) · 1.99 KB
/
lib.rs
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
use swc_plugin::{ast::*, errors::HANDLER, plugin_transform, syntax_pos::DUMMY_SP};
struct ConsoleOutputReplacer;
/// An example plugin replaces any `console.log(${text})` into
/// `console.log('changed_via_plugin')`.
impl VisitMut for ConsoleOutputReplacer {
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
if let Callee::Expr(expr) = &call.callee {
if let Expr::Member(MemberExpr { obj, .. }) = &**expr {
if let Expr::Ident(ident) = &**obj {
if ident.sym == *"console" {
call.args[0].expr = Box::new(Expr::Lit(Lit::Str(Str {
span: DUMMY_SP,
has_escape: false,
kind: StrKind::default(),
value: JsWord::from("changed_via_plugin"),
})));
}
}
}
}
}
}
/// An example plugin function with macro support.
/// `plugin_transform` macro interop pointers into deserialized structs, as well
/// as returning ptr back to host.
///
/// It is possible to opt out from macro by writing transform fn manually via
/// `__plugin_process_impl(
/// ast_ptr: *const u8,
/// ast_ptr_len: i32,
/// config_str_ptr: *const u8,
/// config_str_ptr_len: i32) ->
/// i32 /* 0 for success, fail otherwise.
/// Note this is only for internal pointer interop result,
/// not actual transform result */
///
/// if plugin need to handle low-level ptr directly. However, there are
/// important steps manually need to be performed like sending transformed
/// results back to host. Refer swc_plugin_macro how does it work internally.
#[plugin_transform]
pub fn process(program: Program, _plugin_config: String) -> Program {
HANDLER.with(|handler| {
handler
.struct_span_err(DUMMY_SP, "Test diagnostics from plugin")
.emit();
});
program.fold_with(&mut as_folder(ConsoleOutputReplacer))
}