Java Object support for JavaScript Object.prototype.valueOf() with '=='
Feature request
Is your feature request related to a problem? Please describe.
In Javascript there is functionality on the Object prototype: Object.prototype.valueOf() which returns the primitive type of an Object. I know GraalVM supports this on any JavaScript Object. But this is not supported for Java Objects in JavaScript.
I wrote a test to show what happens. My problem is I have legacy code riddled with if statements similar to the ones in the script. I am trying not to make any JS changes if possible.
Below is the main method from my test.
Main Test class:
import org.graalvm.polyglot.Context;
public class TestObjectValueOf {
public static void main(final String[] args) {
final String script = """
var TestDummyObject = Java.type("TestDummyObject");
var tdo = new TestDummyObject("99");
if ((typeof tdo) == 'undefined') {
console.log("TDO IS NULL!!");
}
if (tdo == '99') {
console.log("TDO == '99'");
} else {
console.log("Did not call TestDummyObject.valueOf()");
}
var subTdo = tdo.getSubObject();
if ((typeof subTdo) == 'undefined') {
console.log("SUB TDO IS NULL!!");
}
if (subTdo == '99') {
console.log("Sub TDO == '99'");
} else {
console.log("Did not call TestDummySubObject.valueOf()");
}
""";
final Context context = Context.newBuilder().allowAllAccess(true).option("js.foreign-object-prototype", Boolean.TRUE.toString()).build();
context.eval("js", script);
context.close();
}
}
TestDummyObject.java (It is a little complicated, but I was trying to capture as much in as little):
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.proxy.ProxyArray;
import org.graalvm.polyglot.proxy.ProxyExecutable;
import org.graalvm.polyglot.proxy.ProxyObject;
public class TestDummyObject {
private final String id;
private final Object subObject;
public TestDummyObject(final String id) {
this.id = id;
subObject = new TestDummyProxyObject(new TestDummySubObject(id));
System.out.println("Finished creating TestDummyObject");
}
public Object getSubObject() {
return subObject;
}
public Object valueOf() {
System.out.println("Calling TestDummyObject.valueOf()");
return (Supplier<String>) () -> id;
}
public static class TestDummyProxyObject implements ProxyObject {
private final Map<String, Object> members = new HashMap<>();
final List<Object> keys = new ArrayList<>();
public TestDummyProxyObject(final TestDummySubObject tdo) {
final Method[] methods = tdo.getClass().getMethods();
for (final Method method : methods) {
members.put(method.getName(), new TestDummyProxyExecutable(tdo, method));
}
keys.addAll(members.keySet());
System.out.println("Finished creating TestDummyProxyObject with Keys: " + keys);
}
@Override
public Object getMember(final String key) {
System.out.println("Get Member: " + key);
return members.get(key);
}
@Override
public Object getMemberKeys() {
System.out.println("Keys: " + keys);
return ProxyArray.fromList(keys);
}
@Override
public boolean hasMember(final String key) {
System.out.println("Has Key: " + key);
return keys.contains(key);
}
@Override
public void putMember(final String key, final Value value) {
System.out.println("Putting Key: " + key + ", with Value: " + value);
members.put(key, value);
}
}
public static class TestDummySubObject {
private final String id;
public TestDummySubObject(final String id) {
this.id = id;
System.out.println("Finished creating TestDummySubObject");
}
public Object valueOf() {
System.out.println("Calling TestDummySubObject.valueOf()");
return (Supplier<String>) () -> id;
}
@Override
public String toString() {
System.out.println("Calling TestDummySubObject.toString()");
return id;
}
@Override
public boolean equals(final Object o) {
System.out.println("Calling TestDummySubObject.equals()");
if (this == o) {
return true;
}
if (o instanceof final String objString) {
return StringUtils.equals(id, objString);
}
if (o instanceof final TestDummySubObject that) {
return new EqualsBuilder().append(id, that.id).isEquals();
}
return false;
}
@Override
public int hashCode() {
System.out.println("Calling TestDummySubObject.hashCode()");
return new HashCodeBuilder(17, 37).append(id).toHashCode();
}
}
public static class TestDummyProxyExecutable implements ProxyExecutable {
private final TestDummySubObject tdo;
private final Method method;
public TestDummyProxyExecutable(final TestDummySubObject tdo, final Method method) {
this.tdo = tdo;
this.method = method;
System.out.println("Finished creating TestDummyProxyExecutable for Method: " + method.getName());
}
@Override
public Object execute(final Value... arguments) {
System.out.println("Executing Method: " + method.getName());
try {
if (method.getParameterCount() == 0) {
return method.invoke(tdo);
}
final Value argValue = arguments[0];
Object arg;
if (argValue.isHostObject()) {
arg = argValue.asHostObject();
} else {
arg = argValue.toString();
}
return method.invoke(tdo, arg);
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
}
}
The output I get is:
Finished creating TestDummySubObject
Finished creating TestDummyProxyExecutable for Method: equals
Finished creating TestDummyProxyExecutable for Method: toString
Finished creating TestDummyProxyExecutable for Method: hashCode
Finished creating TestDummyProxyExecutable for Method: valueOf
Finished creating TestDummyProxyExecutable for Method: wait
Finished creating TestDummyProxyExecutable for Method: wait
Finished creating TestDummyProxyExecutable for Method: wait
Finished creating TestDummyProxyExecutable for Method: getClass
Finished creating TestDummyProxyExecutable for Method: notify
Finished creating TestDummyProxyExecutable for Method: notifyAll
Finished creating TestDummyProxyObject with Keys: [getClass, wait, hashCode, valueOf, equals, notifyAll, toString, notify]
Finished creating TestDummyObject
Did not call TestDummyObject.valueOf()
Did not call TestDummySubObject.valueOf()
If you look at the TestDummyObject, I put a simple output in each method saying the method is being called. Even on the ProxyObject, Graal is not calling the interface. It looks like (and I may be wrong) if there is if ([Java Object] == [primitive value]) and the Java Object is NOT a primitive (byte. short, int, long, float, double, String) , then Graal compares Object references and does not call valueOf on the Object?
According to the link below, the functionality of using valueOf when== is executed is part of JavaScript. Not sure if it has been there since the beginning, or at least since ES5. (Andreas Woess mentioned: "BTW, that has changed since, but there's a more or less equivalent ToPrimitive operation now.")
- Click on the link
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
- Under the Try It section, do the following:
- After line 9:
const object1 = new MyNumberType(4); - Add the following code, and then run:
- After line 9:
if (object1 == 4) {
console.log("Object is 4");
}
- NOTE: You can even change the 4 to be '4' in either the creation of MyNumberType, or the if statement.
- You will see the following output for an Integer in the creation of MyNumberType:
> "Object is 4"
> 7
- You will see the following output for a String in the creation of MyNumberType:
> "Object is 4"
> "43"
Describe the solution you'd like.
We have been using Nashorn on JDK 8&9, and are converting to GraalVM 22.1 on JDK 17. So, adding a method on the Proxy interface valueOf(), or getDefaultValue(), That would behave similar to Nashorn's getDefaultValue():
https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/nashorn/api/scripting/AbstractJSObject.html#getDefaultValue-java.lang.Class-
This link (not my company’s link), but if you scroll down to Section 3.2.2 Object character, there is a section for how the getDefaultValue is supposed to work.
https://docs.deistercloud.com/content/Axional%20development%20libraries.20/Server%20sid[…]index.xml?embedded=true&navbar=0¶m-iframe=index-iframe
After some discussion on the #general Slack channel with myself and Andreas Woess and Christian Humer.
Christian Humer: Note that in a very past revision of the API we had something called ProxyPrimitive, that allowed unboxing to primitives, like valueOf in a language agnostic way. Unfortunately that API did not make the final cut due to lack of use-cases. Looks like we got one now. But tbh, I am not sure the ProxyPrimitive solution would be much simpler than the JS proxy solution here.
....
....
Andreas Woess: I think we should just change == to call valueOf() for foreign/Java objects, too. Not sure why we don't do that already. Looks like an oversight. :confused:
Andreas Woess: No need for ProxyPrimitive.
Peter Minearo: So, you are saying that if a Java Object has a valueOf() method, Graal would call that when == is used?
Andreas Woess: Unfortunately, it doesn't currently, but I think it should, yeah.
Christian Humer: Well that is what the == in JS specifies, kind of. I am a bit worried that we are calling methods that should not be called. E.g. methods just named "valueOf" do not really have a meaning in Java.
Andreas Woess: Of course, ProxyPrimitive would work, too, and also cross-language (since valueOf() is a JS-specific thing).
Christian Humer: So Pro for the JS solution is that it just works, but with the asterix to potentially accidentally calling method not designed for this.
Describe who do you think will benefit the most. GraalVM users who develop JavaScript can utilize the Object.prototype.valueOf() functionality even with Java Objects in JavaScript.
Describe alternatives you've considered. In order to get around this, we would need to create an extension to the JavaScript Object class:
Object.isEquals(obj, value);
This would then do a series of comparison on the 2 parameters to see if there is some way we could figure out if they are equal.
Additional context.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
- https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/nashorn/api/scripting/AbstractJSObject.html#getDefaultValue-java.lang.Class-
- https://docs.deistercloud.com/content/Axional%20development%20libraries.20/Server%20sid[…]index.xml?embedded=true&navbar=0¶m-iframe=index-iframe
Express whether you'd like to help contributing this feature Not sure I am qualified for doing any coding in this feature.
I came across the same issue. It has been giving me a big headache the past few days, glad to see someone else has already found the same problem. I hope it gets fixed soon!
I did some more testing, and it seems that when it comes to the concatenation operator '+', it works as prescribed. As an example, if you take my previous test and replace the script with the following, it will work.
var TestDummyObject = Java.type("TestDummyObject");
var tdo = new TestDummyObject("99");
var tdoConcat = tdo + 99;
if (tdoConcat == 9999) {
console.log("TDO == '9999'");
} else {
throw "TDO does not equal to '9999': " + tdoConcat;
}
var subTdo = tdo.getSubObject();
var subTdoConcat = subTdo + '99';
if (subTdoConcat == '9999') {
console.log("Sub TDO == '9999'");
} else {
throw "Sub TDO does not equal to '9999': " + subTdoConcat;
}
So, it seems that this functionality was not added to the == operator.
For a little more information for anyone not completely familiar with how JavaScript handles primitive conversions:
https://javascript.info/object-toprimitive
I've been experiencing the same issue and this feature is a must have for my company. Please implement a fix asap.
Hi, Thank you for reporting this, we will take a look into it and get back to you.
Tracked internally at GR--38895
A thought crossed my mind over the weekend. I am not sure where in the code base this exists and how it functions now; but I was thinking, is there a way to create a hook for languages to add their own custom functionality to an operator? That way languages, like JavaScript could add their own 'quirks' to an operator?
Operators have a base set of functionality that every language follows. But then some add their own 'quirk' to it. So, adding functionality like this could be custom to each language and easily added. That way there will be no side effects for other languages.
It may not be the right way of doing it, but it was just a thought.
I was thinking, is there a way to create a hook for languages to add their own custom functionality to an operator?
I think this is not what you want to do, because it would be non-standard and it would be equivalent to forking the language. We typically restrict ourselves to things that are already possible in the language and that we can map our interop contracts. We are actively trying to not be inventive here to maximize compatibility with other JS runtimes. If we start forking language semantics we might navigate ourselves into difficult situations, like what if JS decides to integrate operator overloading themselves? So if you want operator overloading, I'd recommend pushing for an ECMA proposal.
Here is one: https://github.com/tc39/proposal-operator-overloading
Out of curiosity, is there a release this is slated for? Or has it not been assigned to a release yet?
@pminearo we're going to fix the issue of valueOf() not being called by == in 22.2.0.
Has been fixed in GraalVM 22.2, thus closing this ticket. If that did not fix your issue, please reopen.