Error out on rval `emscripten::val` assignment Trying to assign properties via naturally-looking syntax `obj["foo"] = ...` bites users because, rather than assigning a JS property as they might expect, it actually changes only a `val` instance that temporarily resides on the stack and isn't accessible afterwards. This change makes such assignment a compilation error, making it easier to catch the misuse.
diff --git a/system/include/emscripten/val.h b/system/include/emscripten/val.h index 413bee7..bb0ed2b 100644 --- a/system/include/emscripten/val.h +++ b/system/include/emscripten/val.h
@@ -410,14 +410,14 @@ return handle; } - val& operator=(val&& v) { + val& operator=(val&& v) & { internal::_emval_decref(handle); handle = v.handle; v.handle = 0; return *this; } - val& operator=(const val& v) { + val& operator=(const val& v) & { internal::_emval_incref(v.handle); internal::_emval_decref(handle); handle = v.handle;
diff --git a/tests/embind/test_val_assignment.cpp b/tests/embind/test_val_assignment.cpp new file mode 100644 index 0000000..51fdda7 --- /dev/null +++ b/tests/embind/test_val_assignment.cpp
@@ -0,0 +1,8 @@ +#include <emscripten/val.h> + +using emscripten::val; + +int main() { + val obj = val::object(); + obj["foo"] = val(42); +}
diff --git a/tests/test_core.py b/tests/test_core.py index 9329433..e2427f3 100644 --- a/tests/test_core.py +++ b/tests/test_core.py
@@ -6973,6 +6973,10 @@ self.emcc_args += ['--bind'] self.do_run_in_out_file_test('embind/test_val.cpp') + def test_embind_val_assignment(self): + err = self.expect_fail([EMCC, test_file('embind/test_val_assignment.cpp'), '--bind', '-c']) + self.assertContained('candidate function not viable: expects an lvalue for object argument', err) + @no_wasm2js('wasm_bigint') def test_embind_i64_val(self): self.set_setting('WASM_BIGINT')