Skip to content

Commit 1201861

Browse files
authored
Run prettier on compiler-internal JS files. NFC (#21545)
This is in preparation for #21542 which converts them to `.mjs`. Since we run prettier during CI on all `.mjs` files this change this change avoid superfluous changes at the point of rename.
1 parent 745b8b7 commit 1201861

File tree

5 files changed

+227
-129
lines changed

5 files changed

+227
-129
lines changed

src/jsifier.js

Lines changed: 89 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ function mangleCSymbolName(f) {
3131
function splitter(array, filter) {
3232
const splitOut = array.filter(filter);
3333
const leftIn = array.filter((x) => !filter(x));
34-
return { leftIn, splitOut };
34+
return {leftIn, splitOut};
3535
}
3636

3737
function escapeJSONKey(x) {
@@ -54,7 +54,7 @@ function stringifyWithFunctions(obj) {
5454
// Handle JS method syntax where the function property starts with its own
5555
// name. e.g. foo(a) {},
5656
if (typeof value === 'function' && str.startsWith(key)) {
57-
rtn += str + ',\n'
57+
rtn += str + ',\n';
5858
} else {
5959
rtn += escapeJSONKey(key) + ':' + str + ',\n';
6060
}
@@ -98,7 +98,7 @@ function getTransitiveDeps(symbol) {
9898
}
9999

100100
function shouldPreprocess(fileName) {
101-
var content = read(fileName).trim()
101+
var content = read(fileName).trim();
102102
return content.startsWith('#preprocess\n') || content.startsWith('#preprocess\r\n');
103103
}
104104

@@ -157,7 +157,10 @@ function runJSify() {
157157
return modifyJSFunction(snippet, (args, body, async_, oneliner) => {
158158
let argLines = args.split('\n');
159159
argLines = argLines.map((line) => line.split('//')[0]);
160-
const argNames = argLines.join(' ').split(',').map((name) => name.trim());
160+
const argNames = argLines
161+
.join(' ')
162+
.split(',')
163+
.map((name) => name.trim());
161164
const newArgs = [];
162165
let innerArgs = [];
163166
let argConversions = '';
@@ -198,9 +201,9 @@ function runJSify() {
198201
return `${async_}(${args}) => {
199202
${argConversions}
200203
return ${makeReturn64(body)};
201-
}`
204+
}`;
202205
}
203-
return `${async_}(${args}) => ${makeReturn64(body)};`
206+
return `${async_}(${args}) => ${makeReturn64(body)};`;
204207
}
205208
return `\
206209
${async_}function(${args}) {
@@ -243,22 +246,27 @@ ${argConversions}
243246

244247
// apply LIBRARY_DEBUG if relevant
245248
if (LIBRARY_DEBUG && !isJsOnlySymbol(symbol)) {
246-
snippet = modifyJSFunction(snippet, (args, body, async) => `\
249+
snippet = modifyJSFunction(
250+
snippet,
251+
(args, body, async) => `\
247252
function(${args}) {
248253
var ret = (() => { if (runtimeDebug) err("[library call:${mangled}: " + Array.prototype.slice.call(arguments).map(prettyPrint) + "]");
249254
${body}
250255
})();
251256
if (runtimeDebug && typeof ret != "undefined") err(" [ return:" + prettyPrint(ret));
252257
return ret;
253-
}`);
258+
}`,
259+
);
254260
}
255261

256262
const sig = LibraryManager.library[symbol + '__sig'];
257263
const i53abi = LibraryManager.library[symbol + '__i53abi'];
258-
if (sig &&
259-
((i53abi && sig.includes('j')) || ((MEMORY64 || CAN_ADDRESS_2GB) && sig.includes('p')))) {
264+
if (
265+
sig &&
266+
((i53abi && sig.includes('j')) || ((MEMORY64 || CAN_ADDRESS_2GB) && sig.includes('p')))
267+
) {
260268
snippet = handleI64Signatures(symbol, snippet, sig, i53abi);
261-
i53ConversionDeps.forEach((d) => deps.push(d))
269+
i53ConversionDeps.forEach((d) => deps.push(d));
262270
}
263271

264272
const proxyingMode = LibraryManager.library[symbol + '__proxy'];
@@ -274,23 +282,27 @@ function(${args}) {
274282
body = `return ${body}`;
275283
}
276284
const rtnType = sig && sig.length ? sig[0] : null;
277-
const proxyFunc = (MEMORY64 && rtnType == 'p') ? 'proxyToMainThreadPtr' : 'proxyToMainThread';
285+
const proxyFunc =
286+
MEMORY64 && rtnType == 'p' ? 'proxyToMainThreadPtr' : 'proxyToMainThread';
278287
deps.push('$' + proxyFunc);
279288
return `
280289
function(${args}) {
281290
if (ENVIRONMENT_IS_PTHREAD)
282291
return ${proxyFunc}(${proxiedFunctionTable.length}, 0, ${+sync}${args ? ', ' : ''}${args});
283292
${body}
284-
}\n`
293+
}\n`;
285294
});
286295
} else if (WASM_WORKERS && ASSERTIONS) {
287296
// In ASSERTIONS builds add runtime checks that proxied functions are not attempted to be called in Wasm Workers
288297
// (since there is no automatic proxying architecture available)
289-
snippet = modifyJSFunction(snippet, (args, body) => `
298+
snippet = modifyJSFunction(
299+
snippet,
300+
(args, body) => `
290301
function(${args}) {
291302
assert(!ENVIRONMENT_IS_WASM_WORKER, "Attempted to call proxied function '${mangled}' in a Wasm Worker, but in Wasm Worker enabled builds, proxied function architecture is not available!");
292303
${body}
293-
}\n`);
304+
}\n`,
305+
);
294306
}
295307
proxiedFunctionTable.push(mangled);
296308
}
@@ -328,7 +340,9 @@ function(${args}) {
328340
// of argument.
329341
if (LINK_AS_CXX && !WASM_EXCEPTIONS && symbol.startsWith('__cxa_find_matching_catch_')) {
330342
if (DISABLE_EXCEPTION_THROWING) {
331-
error('DISABLE_EXCEPTION_THROWING was set (likely due to -fno-exceptions), which means no C++ exception throwing support code is linked in, but exception catching code appears. Either do not set DISABLE_EXCEPTION_THROWING (if you do want exception throwing) or compile all source files with -fno-except (so that no exceptions support code is required); also make sure DISABLE_EXCEPTION_CATCHING is set to the right value - if you want exceptions, it should be off, and vice versa.');
343+
error(
344+
'DISABLE_EXCEPTION_THROWING was set (likely due to -fno-exceptions), which means no C++ exception throwing support code is linked in, but exception catching code appears. Either do not set DISABLE_EXCEPTION_THROWING (if you do want exception throwing) or compile all source files with -fno-except (so that no exceptions support code is required); also make sure DISABLE_EXCEPTION_CATCHING is set to the right value - if you want exceptions, it should be off, and vice versa.',
345+
);
332346
return;
333347
}
334348
if (!(symbol in LibraryManager.library)) {
@@ -374,9 +388,10 @@ function(${args}) {
374388
let isAsyncFunction = false;
375389
if (ASYNCIFY) {
376390
const original = LibraryManager.library[symbol];
377-
if (typeof original == 'function' ) {
378-
isAsyncFunction = LibraryManager.library[symbol + '__async'] ||
379-
original.constructor.name == 'AsyncFunction'
391+
if (typeof original == 'function') {
392+
isAsyncFunction =
393+
LibraryManager.library[symbol + '__async'] ||
394+
original.constructor.name == 'AsyncFunction';
380395
}
381396
if (isAsyncFunction) {
382397
asyncFuncs.push(symbol);
@@ -388,11 +403,17 @@ function(${args}) {
388403
var value = LibraryManager.library[symbol];
389404
var resolvedSymbol = symbol;
390405
// Resolve aliases before looking up deps
391-
if (typeof value == 'string' && value[0] != '=' && LibraryManager.library.hasOwnProperty(value)) {
406+
if (
407+
typeof value == 'string' &&
408+
value[0] != '=' &&
409+
LibraryManager.library.hasOwnProperty(value)
410+
) {
392411
resolvedSymbol = value;
393412
}
394413
var transtiveDeps = getTransitiveDeps(resolvedSymbol);
395-
symbolDeps[symbol] = transtiveDeps.filter((d) => !isJsOnlySymbol(d) && !(d in LibraryManager.library));
414+
symbolDeps[symbol] = transtiveDeps.filter(
415+
(d) => !isJsOnlySymbol(d) && !(d in LibraryManager.library),
416+
);
396417
}
397418
return;
398419
}
@@ -419,8 +440,13 @@ function(${args}) {
419440
if (dependent) msg += ` (referenced by ${dependent})`;
420441
if (ERROR_ON_UNDEFINED_SYMBOLS) {
421442
error(msg);
422-
warnOnce('To disable errors for undefined symbols use `-sERROR_ON_UNDEFINED_SYMBOLS=0`');
423-
warnOnce(mangled + ' may need to be added to EXPORTED_FUNCTIONS if it arrives from a system library');
443+
warnOnce(
444+
'To disable errors for undefined symbols use `-sERROR_ON_UNDEFINED_SYMBOLS=0`',
445+
);
446+
warnOnce(
447+
mangled +
448+
' may need to be added to EXPORTED_FUNCTIONS if it arrives from a system library',
449+
);
424450
} else if (VERBOSE || WARN_ON_UNDEFINED_SYMBOLS) {
425451
warn(msg);
426452
}
@@ -508,7 +534,7 @@ function(${args}) {
508534
}
509535

510536
if (VERBOSE) {
511-
printErr(`adding ${symbol} (referenced by ${dependent})`)
537+
printErr(`adding ${symbol} (referenced by ${dependent})`);
512538
}
513539
const deps_list = deps.join("','");
514540
const identDependents = symbol + `__deps: ['${deps_list}']`;
@@ -521,15 +547,23 @@ function(${args}) {
521547
// in library.js and library_pthread.js. These happen before deps are
522548
// processed so depending on it via `__deps` doesn't work.
523549
if (dep === '$noExitRuntime') {
524-
error('noExitRuntime cannot be referenced via __deps mechanism. Use DEFAULT_LIBRARY_FUNCS_TO_INCLUDE or EXPORTED_RUNTIME_METHODS')
550+
error(
551+
'noExitRuntime cannot be referenced via __deps mechanism. Use DEFAULT_LIBRARY_FUNCS_TO_INCLUDE or EXPORTED_RUNTIME_METHODS',
552+
);
525553
}
526554
return addFromLibrary(dep, `${symbol}, referenced by ${dependent}`, dep === aliasTarget);
527555
}
528556
let contentText;
529557
if (isFunction) {
530558
// Emit the body of a JS library function.
531-
if ((USE_ASAN || USE_LSAN || UBSAN_RUNTIME) && LibraryManager.library[symbol + '__noleakcheck']) {
532-
contentText = modifyJSFunction(snippet, (args, body) => `(${args}) => withBuiltinMalloc(() => {${body}})`);
559+
if (
560+
(USE_ASAN || USE_LSAN || UBSAN_RUNTIME) &&
561+
LibraryManager.library[symbol + '__noleakcheck']
562+
) {
563+
contentText = modifyJSFunction(
564+
snippet,
565+
(args, body) => `(${args}) => withBuiltinMalloc(() => {${body}})`,
566+
);
533567
deps.push('$withBuiltinMalloc');
534568
} else {
535569
contentText = snippet; // Regular JS function that will be executed in the context of the calling thread.
@@ -552,7 +586,8 @@ function(${args}) {
552586
// emits
553587
// 'var foo;[code here verbatim];'
554588
contentText = 'var ' + mangled + snippet;
555-
if (snippet[snippet.length - 1] != ';' && snippet[snippet.length - 1] != '}') contentText += ';';
589+
if (snippet[snippet.length - 1] != ';' && snippet[snippet.length - 1] != '}')
590+
contentText += ';';
556591
} else if (typeof snippet == 'undefined') {
557592
contentText = `var ${mangled};`;
558593
} else {
@@ -593,13 +628,18 @@ function(${args}) {
593628

594629
let commentText = '';
595630
if (force) {
596-
commentText += '/** @suppress {duplicate } */\n'
631+
commentText += '/** @suppress {duplicate } */\n';
597632
}
598633
if (LibraryManager.library[symbol + '__docs']) {
599634
commentText += LibraryManager.library[symbol + '__docs'] + '\n';
600635
}
601636

602-
const depsText = (deps ? deps.map(addDependency).filter((x) => x != '').join('\n') + '\n' : '');
637+
const depsText = deps
638+
? deps
639+
.map(addDependency)
640+
.filter((x) => x != '')
641+
.join('\n') + '\n'
642+
: '';
603643
return depsText + commentText + contentText;
604644
}
605645

@@ -608,7 +648,7 @@ function(${args}) {
608648
}
609649

610650
function includeFile(fileName, needsPreprocess = true) {
611-
print(getIncludeFile(fileName, needsPreprocess))
651+
print(getIncludeFile(fileName, needsPreprocess));
612652
}
613653

614654
function finalCombiner() {
@@ -672,26 +712,31 @@ var proxiedFunctionTable = [
672712
includeFile(fileName, shouldPreprocess(fileName));
673713
}
674714

675-
print('//FORWARDED_DATA:' + JSON.stringify({
676-
librarySymbols,
677-
warnings,
678-
asyncFuncs,
679-
ATINITS: ATINITS.join('\n'),
680-
ATMAINS: STRICT ? '' : ATMAINS.join('\n'),
681-
ATEXITS: ATEXITS.join('\n'),
682-
}));
715+
print(
716+
'//FORWARDED_DATA:' +
717+
JSON.stringify({
718+
librarySymbols,
719+
warnings,
720+
asyncFuncs,
721+
ATINITS: ATINITS.join('\n'),
722+
ATMAINS: STRICT ? '' : ATMAINS.join('\n'),
723+
ATEXITS: ATEXITS.join('\n'),
724+
}),
725+
);
683726
}
684727

685728
for (const sym of symbolsNeeded) {
686729
symbolHandler(sym);
687730
}
688731

689732
if (symbolsOnly) {
690-
print(JSON.stringify({
691-
deps: symbolDeps,
692-
asyncFuncs,
693-
extraLibraryFuncs,
694-
}));
733+
print(
734+
JSON.stringify({
735+
deps: symbolDeps,
736+
asyncFuncs,
737+
extraLibraryFuncs,
738+
}),
739+
);
695740
} else {
696741
finalCombiner();
697742
}

src/modules.js

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -225,13 +225,15 @@ globalThis.LibraryManager = {
225225
currentFile = filename;
226226
try {
227227
processed = processMacros(preprocess(filename), filename);
228-
vm.runInThisContext(processed, { filename: filename.replace(/\.\w+$/, '.preprocessed$&') });
228+
vm.runInThisContext(processed, {filename: filename.replace(/\.\w+$/, '.preprocessed$&')});
229229
} catch (e) {
230230
error(`failure to execute js library "${filename}":`);
231231
if (VERBOSE) {
232232
const orig = read(filename);
233233
if (processed) {
234-
error(`preprocessed source (you can run a js engine on this to get a clearer error message sometimes):\n=============\n${processed}\n=============`);
234+
error(
235+
`preprocessed source (you can run a js engine on this to get a clearer error message sometimes):\n=============\n${processed}\n=============`,
236+
);
235237
} else {
236238
error(`original source:\n=============\n${orig}\n=============`);
237239
}
@@ -252,7 +254,7 @@ globalThis.LibraryManager = {
252254
if (!BOOTSTRAPPING_STRUCT_INFO) {
253255
let structInfoFile = 'generated_struct_info32.json';
254256
if (MEMORY64) {
255-
structInfoFile = 'generated_struct_info64.json'
257+
structInfoFile = 'generated_struct_info64.json';
256258
}
257259
// Load struct and define information.
258260
const temp = JSON.parse(read(structInfoFile));
@@ -268,19 +270,23 @@ if (!BOOTSTRAPPING_STRUCT_INFO) {
268270
C_STRUCTS = new Proxy(C_STRUCTS, {
269271
get(target, prop, receiver) {
270272
if (!(prop in target)) {
271-
throw new Error(`Missing C struct ${prop}! If you just added it to struct_info.json, you need to run ./tools/gen_struct_info.py`);
273+
throw new Error(
274+
`Missing C struct ${prop}! If you just added it to struct_info.json, you need to run ./tools/gen_struct_info.py`,
275+
);
272276
}
273-
return target[prop]
274-
}
277+
return target[prop];
278+
},
275279
});
276280

277281
cDefs = C_DEFINES = new Proxy(C_DEFINES, {
278282
get(target, prop, receiver) {
279283
if (!(prop in target)) {
280-
throw new Error(`Missing C define ${prop}! If you just added it to struct_info.json, you need to run ./tools/gen_struct_info.py`);
284+
throw new Error(
285+
`Missing C define ${prop}! If you just added it to struct_info.json, you need to run ./tools/gen_struct_info.py`,
286+
);
281287
}
282-
return target[prop]
283-
}
288+
return target[prop];
289+
},
284290
});
285291

286292
// Legacy function that existed solely to give error message. These are now
@@ -383,10 +389,14 @@ function exportRuntime() {
383389
'HEAPF32',
384390
'HEAPF64',
385391
'HEAP_DATA_VIEW',
386-
'HEAP8', 'HEAPU8',
387-
'HEAP16', 'HEAPU16',
388-
'HEAP32', 'HEAPU32',
389-
'HEAP64', 'HEAPU64',
392+
'HEAP8',
393+
'HEAPU8',
394+
'HEAP16',
395+
'HEAPU16',
396+
'HEAP32',
397+
'HEAPU32',
398+
'HEAP64',
399+
'HEAPU64',
390400
];
391401

392402
// These are actually native wasm functions these days but we allow exporting
@@ -424,11 +434,11 @@ function exportRuntime() {
424434
}
425435

426436
if (RETAIN_COMPILER_SETTINGS) {
427-
runtimeElements.push('getCompilerSetting')
437+
runtimeElements.push('getCompilerSetting');
428438
}
429439

430440
if (RUNTIME_DEBUG) {
431-
runtimeElements.push('prettyPrint')
441+
runtimeElements.push('prettyPrint');
432442
}
433443

434444
// dynCall_* methods are not hardcoded here, as they

0 commit comments

Comments
 (0)