How does Js.cast() perform its type checking? - gwt

I'm using GWT 2.9 with elemental2-1.0.0-RC1.
The following code throws a ClassCastException at runtime:
DocumentRange documentRange = Js.cast(DomGlobal.document); // Fails
Range range = documentRange.createRange(); // Never reaches here
When I change to use an Js.uncheckedCast() instead, it succeeds:
DocumentRange documentRange = Js.uncheckedCast(DomGlobal.document);
Range range = documentRange.createRange(); // Works
The documentation for Js.uncheckedCast() says:
"You should always prefer regular casting over this (unless you know what you are doing!)."
I don't know why I'm having to use it, so I'm feeling nervous. Can someone explain how Js.cast() performs its type-checking and why I need to use an Js.uncheckedCast() in this instance?

Js.cast() is a way to cheat a bit, and do something that the Java language will not permit, but might actually be legal. Ignoring "how it actually works", the idea is that you can now get past issues where Java would complain, even if it turns out to be legit.
An example could be where you take a java.lang.Double or double and want to treat it as a JsNumber so you can call toPrecision(2) on it. Since java.lang.Double is final, it isn't legal to cast to an unrelated type, but Java doesn't know that in GWT, Double is really just a js Number. So, instead you can perform the cast with Js.cast(). The compiler will insert a runtime type check in there, verifying at runtime that your number is in fact a JS Number instance.
Another example could be trying to extend some native type that elemental2 provides, either to implement a workaround for a missing feature, or to do something browser-specific. Your new class may not extend the existing class - from JS's perspective this is okay, you are just describing the API that you know will exist at runtime. As such, we need to avoid the Java language check of "does this cast even make sense?", and just tell the compiler to try it.
On the other hand, you can "lie" to the compiler with Js.uncheckedCast(). This is used in cases where you are even asking the runtime to skip the check, and just pretend that it will work. This can let you do weird things, like treating Strings as if they were arrays, or solve cross-frame problems. No runtime check will be emitted, so instead you might just get a TypeError if a method/property is missing, instead of a proper ClassCastException.
In elemental2-dom 1.0.0-RC1, there is a class called DocumentRange, but it doesnt really make any sense - it is declared as a class, which means it can be type checked in JS, but the browser spec says that it should be an "interface" (which in JS-land means that it just is a description of a type, rather than something you can typecheck). https://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-DocumentRange-method-createRange
This bug is inherited from closure-compiler, which claims that this has a constructor: https://github.com/google/closure-compiler/blob/6a418aa/externs/browser/w3c_range.js#L241-L251
The fix is for closure-compiler to refer to this as an interface, and for a new release of elemental2 to be made so you can use this.
There are two workarounds you can make here. The first is to cheat with Js.uncheckedCast(DomGlobal.document) and say "yes, I know that the Document is not instanceof DocumentRange, but that's because there is no such class as DocumentRange, so just pretend it worked so I can call createRange() on it". This is what you are doing already - it hides the fact there is a bug, but at the end of the day it works.
The "correct" answer is to declare your own DocumentRange, and do a Js.cast() to that instead. This is still gross - you have to keep your new interface around until closure gets fixed, and then elemental2 gets released, and then you have to remember to clean it up.
In this case, I would suggest lying to GWT and using Js.uncheckedCast() - there is only a single method on here, and it is unlikely to change in a meaningful way.

Related

How to avoid not used function to be wiped out by optimizer

While compiling and Xcode swift project for MacOS, not used functions are removed from the binary (removed by the optimizer I guess). Is there a way to tell the compiler to not remove unused functions, perhaps with a compiler option (--force-attribute?) so that even with optimization enabled those functions remain in the binary?
I know that if a global function is declared as public (public func test()) then it's not removed even if not used (Since it can be used by other modules), but I can't use public since that would export the symbol for that function.
Any suggestion?
If this is indeed removed by the optimiser, then the answer is two-fold.
The optimiser removes only things that it can prove are safely removable. So to make it not remove something, you remove something that the optimiser uses to prove removability.
For example, you can change the visibility of a function in the .bc file by running a pass that makes the functions externally callable. When a function is private to the .bc file (also called module) and not used, then the compiler can prove that nothing will ever call it. If it's visible beyong the .bc file, then the compiler must assume that something can come along later and call it, so the function has to be left alive.
This is really the generic answer to how to prevent an optimisation: Prevent the compiler from inferring that the optimisation is safe.
Writing and invoking a suitable pass is left as an exercise for the reader. Writing should be perhaps 20 lines of code, invoking… might be simple, or not, it depends on your setting. Quite often you can add a call to opt to your build system.
As I discovered, the solution here is to use a magic compiler flag -enable-private-imports (described here: "...Allows this module's internal and private API to be accessed") which basically add the function name to the list #llvm.used that you can see in the bitcode, the purpose of the list is:
If a symbol appears in the #llvm.used list, then the compiler,
assembler, and linker are required to treat the symbol as if there is
a reference to the symbol that it cannot see (which is why they have
to be named)
(cit.) As described here.
This solves my original problem as the private function even if not used anywhere and not being public, during compilation is not stripped out by the optimiser.

What causes GWT to output: <SomethingNotNull>.nullMethod()?

I have my own emulation of java.util.Timer (and quite a lot of other stuff missing in GWT). I have even a JUnit test proving it works in the browser.
I've just tried to convert some third-party library to GWT, which needed a Timer, and in some part of it, I call:
SystemUtils.getTimer().scheduleAtFixedRate(timerTask, value, value);
But the GWT compiler turns getTimer().scheduleAtFixedRate() to:
getTimer().nullMethod()
SystemUtils.getTimer() is a static method. I have googled for nullMethod(), but most hits are about:
null.nullMethod();
That doesn't apply to me. What could be going wrong, and what can I do to fix it?
[EDIT] Actually, the java.util.Timer emulation itself works, but it seems that (atm?) SystemUtils.getTimer() returns "undefined". Could that be the reason? Since getTimer() returns an instance created dynamically, how could the GWT compiler possibly make any assumption about the return value of getTimer(), and the presence/usage of the methods of the Timer type?
When I have seen this kind of errors it was caused by unreachable code: GWT had determined that some code was not reachable, turning off compilation for some stuff, but then it still somehow tried to link the unreachable code, showing this kind of errors.
For completeness sake
If this error shows up (which often happens after deploying to App Engine) then compile without obfuscation, turn off super dev mode, restart jetty and refresh the browser. Open the generated javascript and find where the problem occurs by searching for 'nullMethod'. You'll see that the compiler may have removed whole chunks of code that it believes is 'unreachable'.
The code surrounding 'null.nullMethod' is probably very different than what you expected. The simplest way around this is to add a null /undefined check and initializing whatever variable that is generated as 'null'. This forces the compiler to reconsider because now the variable can never be null and the code that follows it must be reachable.
For example, if null.nullMethod is found and 'null' is actually supposed to be var a = ... then add if(a == null) { a = ""; } before it (in Java of course).
For anybody who struggles with this null.nullMethod issue:
It may be possible that your GWT compiler isn't able to find the properties of your JSON bean object if your object variable is declared with its interface type:
MyTypeIF item = ...;
...
item.getStart();
...
In my scenario, GWT compiled that into:
MyTypeIF item = ...;
...
null.nullMethod();
...
Instead, I had to declare and cast it to its real implementation class:
JSMyType item = (JSMyType)...;
...

How to create a scala class based on user input?

I have a use case where I need to create a class based on user input.
For example, the user input could be : "(Int,fieldname1) : (String,fieldname2) : .. etc"
Then a class has to be created as follows at runtime
Class Some
{
Int fieldname1
String fieldname2
..so..on..
}
Is this something that Scala supports? Any help is really appreciated.
Your scenario doesn't seem to make sense. It's not so much an issue of runtime instantiation (the JVM can certainly do this with reflection). Really, what you're asking is to dynamically generate a class, which is only useful if your code makes use of it later on. But how can your code make use of it later on if you don't know what it looks like? For example, how would your later code know which fields it could reference?
No, not really.
The idea of a class is to define a type that can be checked at compile time. You see, creating it at runtime would somewhat contradict that.
You might want to store the user input in a different way, e.g. a map.
What are you trying to achieve by creating a class at runtime?
I think this makes sense, as long as you are using your "data model" in a generic manner.
Will this approach work here? Depends.
If your data coming from a file that is read at runtime but available at compile time, then you're in luck and type-safety will be maintained. In fact, you will have two options.
Split your project into two:
In the first run, read the file and write the new source
programmatically (as Strings, or better, with Treehugger).
In the second run, compile your generated class with the rest of your project and use it normally.
If #1 is too "manual", then use Macro Annotations. The idea here is that the main sub-project's compile time follows the macro sub-project's runtime. Therefore, if we provide the main sub-project with an "empty" class, members can be added to it dynamically at compile time using data that the macro sees at runtime. - To get started, Modify the macro to read from a file in this example
Else, if you're data are truly only knowable at runtime, then #Rob Starling's suggestion may work for you as it did me. I'll share my attempt if you want to be a guinea pig. For debugging, I've got an App.scala in there that shows how to pass strings to a runtime class generator and access it at runtime with Java reflection, even define a Scala type alias with it. So the question is, will your new dynamic class serve as a type-parameter in Slick, or fail to, as it sometimes does with other libraries?

Play route syntax for ignoring a part of slug

What we want is basically this:
/foo/* controllers.FooController.foo
However this doesn't work.
We have found the following workaround:
/foo/*ignore controllers.FooController.foo(ignore)
But this makes the code of the method controllers.FooController.foo slightly ugly. Is there a better way to do this?
Looking at the code over here, the router isn't able to deal with the "slug" part without specifying an identifier... the parser combinator doesn't declare it as optional, and the map (^^) is clearly using it as is.
It could be a good feature request if it wouldn't induce other problems where a pattern will hide all other routes because it's defined higher in the file (or even worst, included).
And it looks like it has been done on purpose if we look here, we can figure out that dynamic parameter cannot be assigned a default value -- indeed, in this case we'll fall in the case I've just mentioned :-/.
My first advice would be to tell you to use ignore as an Option[String] and the action definition to set it as None (rather than an empty String because it's more expressive).
My second would be to incite you to wonder if such case is really relevant, because it's error prone and could hide further problems

Error in objective C

I am trying to run unit test whereby I am getting an warning:
'FileName' may not respond to '-failWithException:'
I wanted to know why this warning occurs and how to fix that?
Either the FileName interface does not declare the failWithException: method, or you have not imported the header file in which the interface is declared.
Whatever sort of object FileName is, the compiler can't find a method named '-failWithException' in that class. The solution is to go implement that method on that class, or to make sure the compiler can find the header file where it already is implemented.
By the way, it's a warning instead of an error because, unlike for instance Java, Objective-C allows you to manipulate classes at runtime. So while you PROBABLY have a problem there, you don't DEFINITELY have a problem, so the IDE gives you a yellow warning rather than a red error. But in your case, this is almost certainly something you need to fix.