Skip to content

Commit 5dfe0a2

Browse files
authored
Support ES6 Set/Map in stringifyWithFunctions (emscripten-core#23678)
Fixes emscripten-core#23672
1 parent cb88605 commit 5dfe0a2

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/jsifier.mjs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
compileTimeContext,
3434
printErr,
3535
readFile,
36+
runInMacroContext,
3637
warn,
3738
warnOnce,
3839
warningOccured,
@@ -79,6 +80,19 @@ function stringifyWithFunctions(obj) {
7980
if (Array.isArray(obj)) {
8081
return '[' + obj.map(stringifyWithFunctions).join(',') + ']';
8182
}
83+
84+
// preserve the type of the object if it is one of [Map, Set, WeakMap, WeakSet].
85+
const builtinContainers = runInMacroContext('[Map, Set, WeakMap, WeakSet]', {
86+
filename: '<internal>',
87+
});
88+
for (const container of builtinContainers) {
89+
if (obj instanceof container) {
90+
const className = container.name;
91+
assert(!obj.size, `cannot stringify ${className} with data`);
92+
return `new ${className}`;
93+
}
94+
}
95+
8296
var rtn = '{\n';
8397
for (const [key, value] of Object.entries(obj)) {
8498
var str = stringifyWithFunctions(value);

test/test_other.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4974,6 +4974,34 @@ def test_jslib_has_library(self):
49744974
''')
49754975
self.do_runf(test_file('hello_world.c'), emcc_args=['-L', '-lfoo.js'])
49764976

4977+
def test_jslib_new_objects_basic(self):
4978+
create_file('lib.js', '''
4979+
addToLibrary({
4980+
$obj: {
4981+
a: new Map(),
4982+
b: new Set(),
4983+
c: new WeakMap(),
4984+
d: new WeakSet()
4985+
}
4986+
});
4987+
''')
4988+
self.run_process([EMCC, test_file('hello_world.c'), '--js-library=lib.js', '-sEXPORTED_FUNCTIONS=obj,_main'])
4989+
self.assertContained("a:new Map,", read_file('a.out.js'))
4990+
self.assertContained("b:new Set,", read_file('a.out.js'))
4991+
self.assertContained("c:new WeakMap,", read_file('a.out.js'))
4992+
self.assertContained("d:new WeakSet,", read_file('a.out.js'))
4993+
4994+
def test_jslib_new_objects_non_empty(self):
4995+
create_file('lib.js', '''
4996+
addToLibrary({
4997+
$obj: {
4998+
bad: new Map([[1,2],[3,4]])
4999+
}
5000+
});
5001+
''')
5002+
err = self.expect_fail([EMCC, test_file('hello_world.c'), '--js-library=lib.js', '-sEXPORTED_FUNCTIONS=obj,_main'])
5003+
self.assertContained('cannot stringify Map with data', err)
5004+
49775005
def test_EMCC_BUILD_DIR(self):
49785006
# EMCC_BUILD_DIR was necessary in the past since we used to force the cwd to be src/ for
49795007
# technical reasons.

0 commit comments

Comments
 (0)