Skip to content

Commit 94f726a

Browse files
authored
[embind] Simplify createNamedFunction. NFC (#20479)
Further simplification of createNamedFunction on top of #18748: we can avoid extra JS wrapper by setting `name` of the function directly. This is only supported via "configuring" it by `Object.defineProperty` rather than plain assignment, but otherwise has exactly same effect - it sets debug name of the function in-place. Also, ever since #18748 switched away from `eval`, there is no requirement for the function name to be "legal" - we can set it to the plain demangled string, making debug names even more readable.
1 parent 6870616 commit 94f726a

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/embind/embind.js

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -167,18 +167,21 @@ var LibraryEmbind = {
167167
return errorClass;
168168
},
169169

170-
171-
$createNamedFunction__deps: ['$makeLegalFunctionName'],
172-
$createNamedFunction: function(name, body) {
173-
name = makeLegalFunctionName(name);
174-
// Use an abject with a computed property name to create a new function with
175-
// a name specified at runtime, but without using `new Function` or `eval`.
176-
return {
177-
[name]: function() {
178-
return body.apply(this, arguments);
179-
}
180-
}[name];
181-
},
170+
$createNamedFunction: (name, body) => Object.defineProperty(body, 'name', {
171+
value: name
172+
}),
173+
// All browsers that support WebAssembly also support configurable function name,
174+
// but we might be building for very old browsers via WASM2JS.
175+
#if MIN_CHROME_VERSION < 43 || MIN_EDGE_VERSION < 14 || MIN_SAFARI_VERSION < 100101 || MIN_FIREFOX_VERSION < 38
176+
// In that case, check if configurable function name is supported at init time
177+
// and, if not, replace with a fallback that returns function as-is as those browsers
178+
// don't support other methods either.
179+
$createNamedFunction__postset: `
180+
if (!Object.getOwnPropertyDescriptor(Function.prototype, 'name').configurable) {
181+
createNamedFunction = (name, body) => body;
182+
}
183+
`,
184+
#endif
182185

183186
$embindRepr: (v) => {
184187
if (v === null) {

0 commit comments

Comments
 (0)