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
use swc_common::{util::take::Take, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use super::Optimizer;
enum DropAction {
/// The call's result is `undefined` in the original program (a direct
/// `console.method(...)` call, or `console.method.call/apply(...)`), or
/// nothing better can be substituted (custom properties, deep chains).
ReplaceWithUndefined,
/// The result of e.g. `console.error.bind(console)` is not `undefined`
/// and may be held and used, so, like terser, only the console method is
/// replaced: `console.error.bind(console)` -> `(()=>{}).bind()`.
///
/// `guard` preserves the short-circuiting of a `?.` in the callee, per
/// hop; see [NoopGuard].
ReplaceCalleeObjWithNoopFn { guard: Option<NoopGuard> },
}
/// How the noop substitution keeps the short-circuiting of a `?.` in the
/// callee. Which hop is optional matters: the replacement must yield
/// `undefined` exactly when the original chain short-circuited, and still
/// throw when it did not.
#[derive(Clone, Copy)]
enum NoopGuard {
/// The final member access is optional (`console.debug?.bind(x)`, and
/// also `console?.debug?.bind(x)`): a nullish method short-circuits, so
/// the method is kept as a guard and the access stays optional:
/// `(console.debug && noop)?.bind()`.
Member,
/// Only the `console` hop is optional (`console?.error.bind(x)`): a
/// nullish `console` short-circuits, but a nullish `console.error` still
/// throws at the `.bind` access. The `console` check is hoisted and the
/// `?.` dropped: `console == null ? void 0 : (console.error &&
/// noop).bind()`.
///
/// Local invariant beyond the documented assumptions: the rewrite reads
/// the `console` binding twice (in the test and in the alternate), so the
/// global is assumed to be a stable data binding, not an accessor whose
/// reads have side effects or produce different values.
Console,
}
impl Optimizer<'_> {
pub(super) fn drop_console(&mut self, e: &mut Expr) -> bool {
if !self.options.drop_console {
return false;
}
let Some(action) = classify_console_call(e, self.ctx.expr_ctx.unresolved_ctxt) else {
return false;
};
match action {
DropAction::ReplaceWithUndefined => {
report_change!("drop_console: Removing console call");
self.changed = true;
*e = *Expr::undefined(DUMMY_SP);
true
}
DropAction::ReplaceCalleeObjWithNoopFn { guard } => {
// The `console` ident of a hoisted check; set for
// [NoopGuard::Console] once the inner borrows of `e` end.
let hoisted_console = {
// `classify_console_call` proved the shape of `e`, so
// extraction cannot fail here.
let (callee, args) = match e {
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) => (&mut **callee, args),
Expr::OptChain(opt_chain) => match &mut *opt_chain.base {
OptChainBase::Call(call) => (&mut *call.callee, &mut call.args),
_ => return false,
},
_ => return false,
};
let member = match callee {
Expr::Member(member) => member,
Expr::OptChain(opt_chain) => match &mut *opt_chain.base {
OptChainBase::Member(member) => member,
_ => return false,
},
_ => return false,
};
let hoisted_console = match guard {
Some(NoopGuard::Console) => match &*member.obj {
Expr::OptChain(first_hop) => first_hop
.base
.as_member()
.and_then(|member| member.obj.as_ident())
.cloned(),
_ => None,
},
_ => None,
};
if matches!(guard, Some(NoopGuard::Console)) && hoisted_console.is_none() {
return false;
}
report_change!("drop_console: Replacing console method with an empty function");
self.changed = true;
args.clear();
if let Expr::OptChain(first_hop) = &mut *member.obj {
if matches!(guard, Some(NoopGuard::Console)) {
// The check is hoisted into `hoisted_console`.
first_hop.optional = false;
}
}
let noop = noop_fn_expr(self.options.ecma);
*member.obj = if guard.is_some() {
Expr::Bin(BinExpr {
span: DUMMY_SP,
op: op!("&&"),
left: member.obj.take(),
right: Box::new(noop),
})
} else {
noop
};
hoisted_console
};
if let Some(console) = hoisted_console {
*e = Expr::Cond(CondExpr {
span: DUMMY_SP,
test: Box::new(Expr::Bin(BinExpr {
span: DUMMY_SP,
op: op!("=="),
left: Box::new(console.into()),
right: Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP }))),
})),
cons: Expr::undefined(DUMMY_SP),
alt: Box::new(e.take()),
});
}
true
}
}
}
}
/// Builds the noop function substituted for a console method: an arrow for
/// ES2015+, which - like the native console methods - is not a constructor,
/// and `function () {}` for ES5.
///
/// Local invariant beyond the documented assumptions: under an ES5 target,
/// where a non-constructible function cannot be expressed, constructing the
/// result of a dropped `console.method.bind(...)` succeeds instead of
/// throwing. Referencing a built-in like `Function.prototype` instead would
/// rely on the mutable global `Function`.
fn noop_fn_expr(ecma: EsVersion) -> Expr {
if ecma >= EsVersion::Es2015 {
Expr::Arrow(ArrowExpr {
span: DUMMY_SP,
ctxt: SyntaxContext::empty(),
params: Vec::new(),
body: Box::new(ArrowFunctionBody::FunctionBody(FunctionBody::default())),
is_async: false,
is_generator: false,
type_params: None,
return_type: None,
})
} else {
Expr::Fn(FnExpr {
ident: None,
function: Box::new(Function {
span: DUMMY_SP,
body: Some(FunctionBody::default()),
..Default::default()
}),
})
}
}
/// The name of a member access if it is statically known, whether written as
/// `a.b` or `a["b"]`.
fn static_prop_name(prop: &MemberProp) -> Option<&str> {
match prop {
MemberProp::Ident(prop) => Some(&*prop.sym),
MemberProp::Computed(prop) => match &*prop.expr {
Expr::Lit(Lit::Str(prop)) => prop.value.as_str(),
_ => None,
},
MemberProp::PrivateName(_) => None,
}
}
fn is_console_method(name: &str) -> bool {
matches!(
name,
"assert"
| "clear"
| "count"
| "countReset"
| "debug"
| "dir"
| "dirxml"
| "error"
| "group"
| "groupCollapsed"
| "groupEnd"
| "info"
| "log"
| "table"
| "time"
| "timeEnd"
| "timeLog"
| "trace"
| "warn"
// Non-standard, but widely implemented.
| "profile"
| "profileEnd"
| "timeStamp"
)
}
/// Checks if `e` is a call rooted at the global `console` and decides how to
/// drop it.
fn classify_console_call(e: &Expr, unresolved_ctxt: SyntaxContext) -> Option<DropAction> {
let callee = match e {
Expr::Call(call) => call.callee.as_expr()?,
Expr::OptChain(opt_chain) => match &*opt_chain.base {
OptChainBase::Call(call) => &call.callee,
_ => return None,
},
_ => return None,
};
// Whether the final member access itself is optional
// (`console.error?.bind`).
let mut member_optional = false;
let member = match &**callee {
Expr::Member(member) => member,
Expr::OptChain(opt_chain) => match &*opt_chain.base {
OptChainBase::Member(member) => {
member_optional = opt_chain.optional;
member
}
_ => return None,
},
_ => return None,
};
// Hops below the invoked property: 0 for `console.log(...)`, 1 for
// `console.log.bind(...)`, ... `first_hop` is the property accessed
// directly on `console`, `first_hop_optional` whether that access is
// optional (`console?.error`).
let mut depth = 0usize;
let mut first_hop = None;
let mut first_hop_optional = false;
let mut cur = &member.obj;
loop {
match &**cur {
Expr::Ident(obj) => {
if obj.sym != *"console" || obj.ctxt != unresolved_ctxt {
return None;
}
break;
}
Expr::Member(member) if member.prop.is_ident() => {
depth += 1;
first_hop = Some(&member.prop);
first_hop_optional = false;
cur = &member.obj;
}
Expr::OptChain(opt_chain) => match opt_chain.base.as_member() {
Some(member) => {
depth += 1;
first_hop = Some(&member.prop);
first_hop_optional = opt_chain.optional;
cur = &member.obj;
}
None => return None,
},
_ => return None,
}
}
// Only `Function.prototype`/`Object.prototype` methods whose results are
// type-preserved by an empty function are substituted, and only when they
// are reached through a known console method: a custom property on
// `console` may hold any value, so the previous behavior (`undefined`) is
// kept for those, as it is for custom properties attached to a console
// method. Per the documented assumptions, code must not depend on the
// exact contents of `Function.prototype.toString()`.
//
// Local invariant beyond the documented assumptions: the names are
// matched statically, so an own override of one of these methods on a
// console method (`console.error.bind = ...`) is not preserved and gets
// the prototype behavior instead. Terser substitutes such calls the same
// way.
let is_preservable_fn_call = matches!(
static_prop_name(&member.prop),
Some("bind" | "toString" | "valueOf")
) && first_hop
.and_then(static_prop_name)
.is_some_and(is_console_method);
if depth == 1 && is_preservable_fn_call {
// e.g. `console.error.bind(console)`: the result (a function) can
// outlive the call, unlike `.call`/`.apply`, which invoke the console
// method itself and return `undefined`.
let guard = if member_optional {
Some(NoopGuard::Member)
} else if first_hop_optional {
Some(NoopGuard::Console)
} else {
None
};
return Some(DropAction::ReplaceCalleeObjWithNoopFn { guard });
}
// Direct calls, `.call`/`.apply`, custom properties, and deeper chains
// (`console.a.b.c(...)`) collapse to `undefined`, matching terser and the
// previous behavior.
Some(DropAction::ReplaceWithUndefined)
}