Skip to content

Commit 48b0645

Browse files
authored
Allow arrow functions in JS libraries. NFC (#19539)
This saves a few bytes of code size. I only changes the most commonly used library functions but we could potentially do the rest too.
1 parent 38ca4f8 commit 48b0645

File tree

63 files changed

+357
-432
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+357
-432
lines changed

ChangeLog.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ See docs/process.md for more on how version tagging works.
3232
`modifyJSFunction` and its callback function no longer takes the name of the
3333
function being modified. The name is not relevant for JS library functions
3434
and can be safely ignored.
35+
- JS library functions can now be implemented using ES6 arrow notation, which
36+
can save to a few bytes on JS code size. (#19539)
3537

3638
3.1.41 - 06/06/23
3739
-----------------

src/jsifier.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -434,20 +434,21 @@ function(${args}) {
434434
if (isFunction) {
435435
// Emit the body of a JS library function.
436436
if ((USE_ASAN || USE_LSAN || UBSAN_RUNTIME) && LibraryManager.library[symbol + '__noleakcheck']) {
437-
contentText = modifyJSFunction(snippet, (args, body) => `
438-
function(${args}) {
439-
return withBuiltinMalloc(function() {
440-
${body}
441-
});
442-
}\n`);
437+
contentText = modifyJSFunction(snippet, (args, body) => `(${args}) => withBuiltinMalloc(() => {${body}})`);
443438
deps.push('$withBuiltinMalloc');
444439
} else {
445440
contentText = snippet; // Regular JS function that will be executed in the context of the calling thread.
446441
}
447442
// Give the function the correct (mangled) name. Overwrite it if it's
448443
// already named. This must happen after the last call to
449444
// modifyJSFunction which could have changed or removed the name.
450-
contentText = contentText.replace(/function(?:\s+([^(]+))?\s*\(/, `function ${mangled}(`);
445+
if (contentText.match(/^\s*([^}]*)\s*=>/s)) {
446+
// Handle arrow functions
447+
contentText = `var ${mangled} = ` + contentText + ';';
448+
} else {
449+
// Handle regular (non-arrow) functions
450+
contentText = contentText.replace(/function(?:\s+([^(]+))?\s*\(/, `function ${mangled}(`);
451+
}
451452
} else if (typeof snippet == 'string' && snippet.startsWith(';')) {
452453
// In JS libraries
453454
// foo: ';[code here verbatim]'

0 commit comments

Comments
 (0)